Skip to main content

Operations

Local development​

git clone <cse-http-be repo>
cd cse-http-be
npm install

Prerequisites: Node 24 (matches the Lambda runtime), npm (the repo is an npm workspaces monorepo: packages/core, packages/api), and AWS credentials for account 574317420690 only when you synth, diff or deploy. Tests and typecheck need no AWS access.

Fastest feedback loop for pure logic changes is still the test suite and typecheck, no server or Docker needed:

npm run typecheck # tsc --noEmit
npm test # vitest run — unit + CDK assertion tests only

Running the full API locally (dev:api, CR-27)​

A local-first harness (CR-27) stands in for API Gateway + Lambda + Cognito entirely in one Node process — no SAM, no LocalStack, no AWS credentials, no deployed stack of any kind. The order below matters: DynamoDB Local must be up before dev:api starts (both read DDB_ENDPOINT/TABLE_NAME), and dev:api should be running before seed:local for seeded users to be sign-in-able (see below).

docker compose -f scripts/dynamodb-local/docker-compose.yml up -d # HUMAN step
npm run dev:api # STAGE=local tsx watch packages/api/src/local/server.ts
  • STAGE=local is a hard guard, not a convenience default. The script sets it itself and refuses to run under any other value (packages/api/src/local/server.ts); LocalIdentityProvider's constructor separately refuses to construct unless STAGE=local too (packages/core/src/auth/local-identity-provider.ts) — belt-and-braces against this ever running where it could be mistaken for a real backend.
  • PORT is optional, default 3000.
  • TABLE_NAME/DDB_ENDPOINT default to cse-http-be-local-main / http://localhost:8000 when not already set in your shell — the same values scripts/seed-local.ts (below) uses, so the two agree without either of you having to export anything. An explicit env var always wins over these fallbacks.
  • dev:api maps every incoming request to the exact APIGatewayProxyEventV2WithJWTAuthorizer shape API Gateway would build, resolves the route from lib/routes.ts (the one route table — nothing is duplicated here), and calls the same route-family handler (packages/api/src/handlers/families/<family>.ts) a deployed Lambda calls. No request-handling logic is reimplemented for local dev.
  • CORS: only http://localhost:* and https://localhost:* are allowed origins (LOCALHOST_ORIGIN_RE in server.ts) — a page served from anywhere else, including 127.0.0.1, is rejected. Allowed request headers: Content-Type, Authorization, Idempotency-Key, X-Org-Id, X-Correlation-Id, If-Match, If-None-Match.

Minting a local test JWT​

No Cognito user pool, no admin-create-user, no phone_number workaround (KI-16 doesn't apply locally). With dev:api running:

curl -s -X POST http://localhost:3000/_local/auth/sign-up \
-H 'content-type: application/json' \
-d '{"email":"dev@example.invalid","password":"<placeholder>","displayName":"Dev User"}'
# or, for an already-signed-up user:
curl -s -X POST http://localhost:3000/_local/auth/sign-in \
-H 'content-type: application/json' \
-d '{"email":"dev@example.invalid","password":"<placeholder>"}'

Both return { "accessToken", "idToken", "refreshToken", "expiresInSeconds" } (illustrative — every email/password here is a placeholder, never a real credential). Send either token as a bearer on a real /v1/ call:

curl -s -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:3000/v1/plants | jq

POST /_local/auth/sign-up and /_local/auth/sign-in are not /v1/ routes, never appear in lib/routes.ts, and exist only on this local server (packages/api/src/local/server.ts) — they are never deployed to any real stage. The token itself is a self-signed HS256 JWT with an in-memory key generated fresh at dev:api start-up (nothing written to disk or committed); it verifies only against that same running process.

Seeding local data (seed:local)​

npm run seed:local # tsx scripts/seed-local.ts

Creates a handful of fake plants, devices and plant members (OWNER, ADMIN, VIEWER roles) with placeholder data — no real phone numbers, emails or credentials (CLAUDE.md Hard Rule 3). It's idempotent: re-running it converges on the same seeded rows instead of piling up duplicates.

  • Refuses to run unless DDB_ENDPOINT resolves to localhost/127.0.0.1 — there is no override flag, and the script never connects to AWS under any environment variable combination.
  • Run dev:api first for fully exercisable seed data. If dev:api is already reachable, seed:local signs each seed user up for real via POST /_local/auth/sign-up, recovers the sub LocalIdentityProvider minted, and seeds that user's plants/devices under it — so you can sign in as owner1@example.invalid (etc., see the script for the full list and the shared placeholder password) and immediately see their seeded plants through dev:api. If dev:api is NOT running, it falls back to fixed local-<key> subs — still real DynamoDB rows for direct inspection, but not sign-in-able until dev:api is started and seed:local re-run.
  • Why seeded users can't simply be pre-registered for sign-in: LocalIdentityProvider keeps its users in an in-memory Map scoped to ONE running dev:api process, with a fresh sub (ulid()) minted at sign-up and no persistence to disk or DynamoDB — a separate, short-lived script like seed:local cannot create a sub that process will ever recognise unless it asks that same running process to mint one (which is exactly what the fallback above does). This is a deliberate property of the local-dev harness, not a bug: restarting dev:api always starts every identity fresh.
  • 002 has no stored "org" entity — orgId is just an opaque string used to partition search tokens and codes. seed:local prints a couple of fixed org-local-* strings to pass as X-Org-Id while exercising GET /v1/search/suggestions locally; it writes no org record anywhere.

Simulating the TCP side (dev:tcp-sim, T002-153)​

npm run dev:tcp-sim # STAGE=local tsx watch packages/api/src/local/tcp-simulator.ts

A separate process from dev:api, standing in for cse_tcp_be. It polls dev:api's loopback bus control surface (GET /_local/bus/drain, POST /_local/bus/publish — see below) for messages on the fake to-tcp.fifo line and replies with realistic command.status.v1/report.render.status.v1 envelopes for command.requested.v1/report.render.requested.v1 input, plus an exported simulateAlert(plantId, deviceId?) a developer or scripts/smoke-local.sh (below) can call directly to raise an alert.changed.v1 event on demand. Never opens a network connection to cse_tcp_be, NATS or Postgres — same hard invariant as the rest of this service; the only network call it makes is to dev:api itself.

Smoke-testing the whole loop (scripts/smoke-local.sh, T002-154)​

scripts/smoke-local.sh # human-run only — never run by the coding agents

Drives sign-up → create plant → register (claim) device → alert against a running dev:api + dev:tcp-sim. The first three steps go through real /v1/ routes; no HTTP route raises an alert, so the last step invokes dev:tcp-sim's simulateAlert() and drains the alert-events queue. The former command step was removed with ADR 0012 phase 3 (device commands are sent to the TCP server over the WebSocket). See docs/local-dev.md in cse-http-be for the full order of operations.

In-memory fakes for SNS/SQS/S3/KMS/SES (T002-152)​

packages/core/src/local/fake-clients.ts implements an in-memory fake for each of SNS, SQS, S3, KMS and SES, all sharing one in-process "bus" (a named list of messages per topic/queue) so a publish from one fake and a receive from another can see each other without any network call. packages/core/src/local/client-factory.ts is the one place that decides real vs. fake, gated on config.stage === 'local' — only SNS is wired up today (createSnsClient(), used by packages/core/src/outbox.ts's transactional-outbox relay, which runs in-process against the fake bus under STAGE=local); SQS/S3/KMS/SES have no real @aws-sdk/client-* dependency in this repo yet, so their fakes exist ready for 008/009/notifications to wire up the same way once those features add that dependency.

What's not testable locally​

  • GET /v1/me fails under STAGE=local. Its handler (packages/api/src/handlers/get-me.ts) unconditionally constructs a real CognitoIdentityProvider (not routed through client-factory.ts's local/real switch) and calls it whenever the caller's token has no email claim or a stored profile has an empty one — which, for every dev:api sign-up/sign-in (an access token never carries email at all), is the normal path. That real Cognito call has no local pool to reach and fails. Known gap, not yet fixed.
  • The local IdentityProvider is a self-signed HS256 token, not a real Cognito-issued JWT — it doesn't exercise API Gateway's actual HttpUserPoolAuthorizer verification, audience checks across the four real app clients, or anything Cognito-plan-specific (LITE vs ESSENTIALS, Managed Login, SES delivery).
  • SQS/S3/KMS/SES fakes exist but aren't wired into any real call site yet (see above) — there's nothing to exercise locally for those services until a later feature adds one.
  • The edge stack (CloudFront + WAF) and the integration stack (SNS/SQS to/from cse-tcp-be) are opt-in, deployed-only infrastructure — there is no local equivalent of either; see Edge and integration stacks below.

Test layout​

KindLocationNeedsRun by
Unitpackages/*/test/**/*.test.ts (excludes *.int.test.ts)Nothing: no AWS, no Dockernpm test
Integrationpackages/*/test/integration/**/*.int.test.tsDynamoDB Local (Docker)npm run test:integration, human or CI only
Contractpackages/api/test/contract/** (directory not created yet)Nothingnpm test. Intended to keep docs/openapi.yaml in step with the route table
CDK assertionspackages/api/test/infra/**Nothing: offline synthnpm test

No test file lives at the repo root. Unit tests mock ddb.send and the repository functions, so they verify handler/repository logic, not real DynamoDB request validity. That's exactly how the now-fixed PUT /v1/me/selected-plant key-shape bug (see PUT /v1/me/selected-plant) shipped unnoticed — setSelectedPlant() used to pass GSI-only attributes in a GetItem key, and the mock never raised DynamoDB's real ValidationException. Integration tests exist to cover that gap against a real (local) DynamoDB engine.

DynamoDB Local (integration tests)​

Docker is a prerequisite for integration tests only. The compose file is scripts/dynamodb-local/docker-compose.yml: the amazon/dynamodb-local image, -inMemory -sharedDb, port 8000. Tests reach it through the DDB_ENDPOINT environment variable (typically http://localhost:8000). Because it is in-memory, data is gone when the container stops.

docker compose -f scripts/dynamodb-local/docker-compose.yml up -d
npm run test:integration # vitest run --config vitest.integration.config.mts
docker compose -f scripts/dynamodb-local/docker-compose.yml down

npm run test:integration is not part of npm test and is not run by the coding agents in this repo. A person or CI runs it. DynamoDB Local is the only local-infrastructure dependency: code that touches S3 (later features) is unit-tested against a faked client instead of a container.

Environment setup​

Stage, account and region come from CDK context at synth/deploy time (bin/app.ts). cdk.json ships defaults for all of them:

Context keyOverrideDefault (from cdk.json)
stage-c stage=<value>dev
account-c account=<value> (then CDK_DEFAULT_ACCOUNT)574317420690
region-c region=<value> (then CDK_DEFAULT_REGION)us-east-1
alertEmail-c alertEmail=<value>"", meaning no email subscriber on the alert topic or budgets
webOrigins-c webOrigins=https://a,https://b (comma-separated, or a JSON array), or cdk.json stages.<stage>.webOrigins (persisted for dev since 2026-11-30: https://cse-admin-web.vercel.app,http://localhost:3000,http://localhost:5173)http://localhost:5173 in dev when neither is set; required (synth throws if empty) in every other stage — see Infrastructure → ApiStack
webConsoleClientIds (feature 003, T003-140)-c webConsoleClientIds=id1,id2The deployed web-console app client's own id (props.webClient.userPoolClientId) — override only when a stage has more than one SRP-only web client that should satisfy MFA
mfaEnforcement (feature 003, T003-140)-c mfaEnforcement=onNo effect since 2026-11-11 (two-factor is never required, so the gate never forms; kept for a future policy). Earlier: warn — logs what would have been a 403 MFA_REQUIRED refusal instead of returning it. Flip to on only after (1) the email-OTP-only mobile app build has shipped, (2) staff who need MFA have enrolled TOTP, and (3) the warn logs have been watched — first for reason=WEB_CONSOLE_SIGN_IN_REQUIRED (the request would be refused, plant access would be refused and org access would be refused messages), which shows who would be locked out of mobile/non-web access (owner OQ-09, 2026-10-27). The OQ-09 verification procedure (specs/003-organizations-access/quickstart.md §6, repo-internal) still applies. See Authorization → MFA enforcement rollout
otpSenderEmail-c otpSenderEmail=<verified SES identity>Unset — no sign-in codes are sent; CreateAuthChallengeFn logs email_signin_sender_not_configured. A public address, not a secret; synth throws if it isn't an email address. Grants the trigger ses:SendEmail on that identity (plus its domain identity, and the configuration set if given) with an ses:FromAddress condition pinned to it. Real users also need SES DKIM and sandbox exit (owner actions, KI-6)
otpSesConfigurationSet-c otpSesConfigurationSet=<name>Unset. Requires otpSenderEmail (synth throws otherwise)
realtimeTicketsEnabled-c realtimeTicketsEnabled=trueUnset (realtime routes/KMS key absent entirely) — see Realtime ticket signing key rotation below

At Lambda runtime, packages/core/src/config.ts reads these environment variables. It validates them lazily (on first property access, not at module import), so importing @cse/core doesn't require a Lambda environment:

VariableRequiredPurpose
TABLE_NAMEYes, for any code touching DynamoDB (throws Missing required environment variable otherwise)The table name, injected by CDK per function
STAGENo (defaults to 'dev')Set by ApiFunction
LOG_LEVELNo (defaults to 'INFO'; CDK sets 'WARN' in prod)Set by ApiFunction. Not used to filter logs yet
DDB_ENDPOINTNo (unset in every deployed Lambda)Test-only. Read by config.ddbEndpoint; only the integration-test global setup sets it, to point the SDK at DynamoDB Local instead of real DynamoDB. No CDK stack ever sets this
ACCOUNT_IDNo — reserved, not wired yetRead by config.toTcpTopicArn(stage) to build this service's outbound SNS FIFO topic ARN (cse-http-be-<stage>-to-tcp.fifo) without a cross-stack import. No CDK stack currently sets ACCOUNT_ID on any function, and no code calls toTcpTopicArn yet — both land with the feature that publishes to that topic
ROUTE_CONFIG (feature 003)Yes, set by ApiStack on every family functionJSON, keyed by "METHOD /path" — strict/idempotency/versioned/actions/actionIdempotency per route, serialised from lib/routes.ts. Parsed once at cold start; the family router and http/idempotent.ts/http/versioned.ts read it when a handler doesn't pass an explicit per-call override
WEB_CONSOLE_CLIENT_IDS (feature 003, T003-140)Yes, set on every family (not just members)Comma-separated Cognito app client ids — non-secret, public identifiers. http/context.ts's MFA check treats a request from one of these as SRP-authenticated (TOTP-capable); every other client (the mobile app's CUSTOM_AUTH-capable ones) never satisfies an MFA requirement regardless of profile.mfa.enabled. Defaults to the deployed web-console client id; see -c webConsoleClientIds above
MFA_ENFORCEMENT (feature 003, T003-140)Yes, set on every familyNo effect since 2026-11-11. warn (default) or on — see -c mfaEnforcement above and Authorization → MFA enforcement rollout
USER_POOL_ID / SERVER_CLIENT_ID (feature 003)Only on the me, invitation-accept and (USER_POOL_ID alone) members familiesNon-secret identifiers. Used by IdentityProvider.getUserEmail/getUserContact (an access-token caller with no email claim) and memberAction's :reset-mfa (AdminSetUserMFAPreference)
REALTIME_TICKET_KEY_ARN / REALTIME_TICKET_PREVIOUS_KEY_ARN / REALTIME_WS_URL (feature 003)Only on the realtime family, only when -c realtimeTicketsEnabled=trueThe KMS signing key ARN(s) and the TCP ws-gateway URL — see Realtime ticket signing key rotation below

ApiFunction also sets NODE_OPTIONS=--enable-source-maps and AWS_NODEJS_CONNECTION_REUSE_ENABLED=1 (see Infrastructure → Lambda functions). No .env file is read anywhere, and there are no application secrets to configure.

Deployment process​

:::caution dev is deployed; prod is not A dev stack exists (deployed 2026-09-17, see Infrastructure → Deployed dev resource IDs). There's no prod stack yet. Deploy commands change live AWS resources in an account shared with the production TCP Server. Run them yourself, after reviewing npm run diff. :::

:::info New requirement as of T002-058: webOrigins context on a non-dev deploy ApiStack now fails cdk synth/cdk deploy for any stage other than dev if the webOrigins CDK context isn't set — CORS for the web console (FR-034/FR-035) needs at least one explicit allow-listed origin, and * is rejected everywhere, dev included. dev alone falls back to http://localhost:5173 when webOrigins is omitted. A future prod deploy must pass it explicitly, e.g.:

npx cdk deploy --all -c stage=prod -c webOrigins=https://console.example.com

See API overview → Conventions → CORS for the full allowed-origins/methods/headers contract. :::

npm run synth # cdk synth — the 4 always-on stacks compile
npm run diff # cdk diff — stage defaults to dev via cdk.json
npm run deploy:dev # cdk deploy --all -c stage=dev --require-approval broadening
npm run deploy:hotswap # cdk deploy --all -c stage=dev --hotswap — DEV ONLY, drifts the stack
npm run destroy:dev # cdk destroy --all -c stage=dev — RETAIN resources are orphaned, not deleted

--all (and so deploy:dev/destroy:dev/deploy:hotswap) only ever touches DataStack, AuthStack, ApiStack and ObservabilityStack. It never creates or touches EdgeStack or IntegrationStack — see the next section.

To wire the alert email on a deploy:

npx cdk deploy --all -c stage=dev -c alertEmail=<your-address>

Then click the SNS confirmation link in the email. The subscription sits in PendingConfirmation while the stack reports CREATE_COMPLETE.

CDK's stack dependency graph enforces deploy order (see Infrastructure → Resource dependencies): Data → Auth → Api → Observability. --require-approval broadening pauses for confirmation whenever a deploy widens IAM or security-group permissions.

deploy:hotswap skips CloudFormation for a handler-code-only redeploy. It's much faster, but it drifts the stack: CloudFormation's recorded state and the deployed Lambda code diverge. Never use it for infrastructure changes (new resources, IAM, routes) or in prod. Run a normal deploy:dev afterwards to reconcile.

Route-area stacks (Q27)​

Area stacks now exist in code for service, notify, reports-settings, reports and account (ROUTE_AREAS in lib/routes.ts). None of the N-37 … N-51 routes is deployed yet (see Infrastructure → ApiStack):

  • Deploy order. cse-http-be-<stage>-api first (it creates the SSM parameters), then each cse-http-be-<stage>-api-<area>. deploy:dev (--all) honours this automatically through the stack dependency.
  • SSM trade-off. Area stacks read the HttpApi and authorizer ids from SSM at deploy time, not through CloudFormation exports. If the HttpApi or authorizer is ever replaced, an area stack keeps pointing at the old id until it is itself redeployed; redeploy every area stack after such a change.
  • Adding a family to an area. Set the same area on every route of that family in lib/routes.ts (do not set throttle), then run npx cdk synth --quiet and npm test. The family moves out of ApiStack into the area stack; the first family in any area also turns on the SSM publishing in ApiStack.

Edge and integration stacks (human-only, opt-in)​

EdgeStack (CloudFront + WAF, T002-060) and IntegrationStack (SNS/SQS bus to the TCP Server, T002-085) are both authored, not deployed — see Infrastructure. bin/app.ts only instantiates either one when its own CDK context flag is passed, and deploying either is always a separate, targeted, human-run command — never folded into deploy:dev or any --all:

# Edge (CloudFront + WAF) — real recurring cost + a real public surface
npx cdk deploy cse-http-be-dev-edge -c stage=dev -c edgeEnabled=true

# Integration bus (SNS/SQS to/from cse-tcp-be) — cross-account IAM surface
npx cdk deploy cse-http-be-dev-integration -c stage=dev -c busEnabled=true

Renamed (T002-148, CR-26): edgeEnabled was withEdge; busEnabled was withIntegration — same gates, same cost story, name only. busEnabled's scope also changed: previously it only flipped event-source mappings on inside an already-created IntegrationStack (the separate withIntegration flag created the stack shell first, mappings still disabled). Now the ONE busEnabled flag both creates the whole stack (SNS topic, SQS queues, stream mapping, tcp-events consumer) and enables every event-source mapping in it (stream-router, from-tcp, alert-events) in the same deploy — there is no longer a separate second flag/deploy to flip mappings on afterwards. Treat -c busEnabled=true itself as a human deploy decision (B-01, the quota, is closed: L-B99A9384 is now 1000) — see Infrastructure → IntegrationStack.

:::info dev runs with the bus on (since 2026-10-29) cdk.json sets context.stages.dev.busEnabled: true, so a plain npm run deploy (= deploy:dev) keeps the integration, notify, service and reports stacks. First deployed to dev on 2026-10-28 with npx cdk deploy --all -c stage=dev -c busEnabled=true. To turn it off for one deploy pass -c busEnabled=false — that deletes those four stacks (queues and any messages in them). prod still defaults to off. :::

Three more flags are declared in bin/app.ts for later features and currently read but unused (no resource to gate yet): realtimeTicketsEnabled (007's KMS ticket-signing key) and reportsEnabled/notificationsEnabled (009's report/notification infra; ReportsStack is gated by busEnabled, not reportsEnabled). All default false, same as edgeEnabled and busEnabled (except busEnabled on dev, set in cdk.json; see above) — a plain cdk deploy --all never creates a resource with a fixed monthly cost.

Cost-gate posture (T002-148, enforced by packages/api/test/infra/cost-gates.test.ts): the default synth — no -c flags at all — creates neither EdgeStack nor IntegrationStack; has no CloudFront distribution, WAF Web ACL or SQS queue anywhere in the stack graph (one SNS topic only, the always-on alert topic); declares at most 10 CloudWatch alarms; and the whole service emits at most 10 distinct custom EMF metric names total.

destroy:dev deletes the API, observability and trigger resources. The table and user pool are RETAIN, so they're orphaned, not deleted. On the next deploy:dev, the table create fails, because its name is fixed (cse-http-be-dev-main) and still taken. The user pool is silently recreated as a new pool (pool names aren't unique), with a new ID, new client IDs and no users. Every previously issued token, and the Flutter app's configured IDs, would stop working. Treat destroy:dev as a last resort.

One-time account prerequisites​

These are already done or verified for account 574317420690 (see docs/getting-started.md in cse-http-be):

  • CDK is bootstrapped (v32, qualifier hnb659fds). Don't run cdk bootstrap. The bootstrap stack is shared with the live TCP Server, and bootstrap rewrites it in place.
  • Lambda concurrency quota is 1000 (quota L-B99A9384, raised from 10; verified 2026-10-26), still shared with the live TCP Server's ingest functions. Don't set reservedConcurrentExecutions without the owner's approval, and never load-test from this account.
  • SES is in sandbox (200/day, verified recipients only). Request production access, and complete DKIM verification, before pointing Cognito at SES.

Useful commands​

npm run typecheck # tsc --noEmit (same as `npm run lint`)
npm test # vitest run (unit + CDK assertion + contract; no *.int.test.ts)
npm run test:integration # DynamoDB Local over DDB_ENDPOINT — human/CI-run, needs Docker
npm run test:watch # vitest watch mode
npm run synth # cdk synth
npm run diff # cdk diff
npm run deploy:dev # cdk deploy --all -c stage=dev
npm run deploy:hotswap # fast handler-only redeploy — dev only
npm run destroy:dev # cdk destroy --all -c stage=dev

Read deployed IDs from SSM instead of hardcoding them:

aws ssm get-parameter --name /cse-http-be/dev/user-pool-id --query Parameter.Value --output text
aws ssm get-parameter --name /cse-http-be/dev/mobile-client-default-id --query Parameter.Value --output text
aws ssm get-parameter --name /cse-http-be/dev/table-name --query Parameter.Value --output text
aws cloudformation describe-stacks --stack-name cse-http-be-dev-api \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text

Minting a test JWT​

The server-admin + ADMIN_USER_PASSWORD_AUTH recipe in docs/getting-started.md works against dev (KI-18 fixed, T002-048): lib/api-stack.ts adds serverClient to the authorizer's trusted audience only when stage === 'dev', so a server-admin token is accepted there. It is never accepted in prod or any other stage — that's a deliberate dev-only convenience for CI/smoke testing, not a general credential. Don't rely on server-admin tokens working against anything but dev; sign in over SRP against a mobile client with a Cognito client SDK (e.g. amazon-cognito-identity-js) to test what a real client gets everywhere else.

Creating a test user (the pool requires phone_number; see KI-16). Generate the password; never write a literal one down:

POOL=$(aws ssm get-parameter --name /cse-http-be/dev/user-pool-id --query Parameter.Value --output text)
DEV_PASSWORD="$(openssl rand -base64 18)Aa1!"

aws cognito-idp admin-create-user --user-pool-id "$POOL" \
--username dev@example.com --message-action SUPPRESS \
--user-attributes Name=email,Value=dev@example.com Name=email_verified,Value=true \
Name=phone_number,Value=+10000000000

aws cognito-idp admin-set-user-password --user-pool-id "$POOL" \
--username dev@example.com --password "$DEV_PASSWORD" --permanent

An admin-created user never goes through ConfirmSignUp, so PostConfirmation doesn't fire. The first GET /v1/me provisions the profile instead, without displayName or termsAcceptedAt.

Once you have a mobile-client ID token (never paste it into a doc, a commit, or a ticket):

curl -s -H "Authorization: Bearer $ID_TOKEN" "$API/v1/me" | jq

Static assets (npm run deploy:assets)​

Images under cse-http-be/assets/ are served from the cse-http-be-dev-assets stack (separate CDK app). Add or overwrite a file, then:

npm run deploy:assets # cdk deploy (dev, assets app only) + regenerate the docs manifest
npm run synth:assets # synth only, into cdk.out.assets/
npm run assets:manifest # rewrite the docs gallery manifest from cdk.out.assets/outputs.json

CDK asks for approval when IAM changes (first deploy). URLs never change on redeploy; see Static assets.

Logs​

Every ApiFunction Lambda logs JSON (loggingFormat: JSON) to its own CloudWatch LogGroup, with 14-day retention (destroyed with the stack outside prod, retained in prod). The log groups have no explicit name, so CloudFormation generates one prefixed with the stack name. They are not under /aws/lambda/…:

aws logs describe-log-groups --log-group-name-prefix cse-http-be-dev-api --query 'logGroups[].logGroupName'
aws logs describe-log-groups --log-group-name-prefix cse-http-be-dev-auth --query 'logGroups[].logGroupName'

The API stage access-log group is in the cse-http-be-dev-api list as well.

Request/response bodies are never logged. These are all the structured events the code emits:

msgLevelEmitted byFields
request_completedINFO (2xx/3xx), WARN (4xx), ERROR (5xx)handler() / publicHandler() wrapper, exactly one per requestrequestId, correlationId, subHash, orgIdHeader, routeKey, status, code (error responses only), latencyMs, coldStart
validation_failedWARNWrapper, on an escaping ZodErrorrequestId, routeKey, issues (path + Zod code only, no values)
unhandled_errorERRORhandler() wrapper, any routerequestId, routeKey, name, error, stack
post_confirmation_provisioning_failedERRORPostConfirmationFnerror
email_signin_code_issuedINFOCreateAuthChallengeFn—
email_signin_throttledINFOCreateAuthChallengeFn—
email_signin_unverified_addressINFOCreateAuthChallengeFn—
email_signin_send_failedERRORCreateAuthChallengeFnerror (SDK error name)
email_signin_sender_not_configuredERRORCreateAuthChallengeFnhint
email_signin_succeededINFOVerifyAuthChallengeFn—
email_signin_failed_bad_codeINFOVerifyAuthChallengeFn—
email_signin_failed_expiredINFOVerifyAuthChallengeFn—

The email address and the code are never logged.

subHash is the first 16 hex chars of SHA-256 of the Cognito sub, so requests can be grouped per user without logging the identifier. The logger redacts the keys body, authorization, password, token, email and phone (value becomes [REDACTED]) unless a call opts in. A user's requestId from an error response (or the X-Request-Id header) finds that request's request_completed line.

Custom metrics​

Metrics are written as CloudWatch Embedded Metric Format log lines in the namespace CseHttpBe/<stage>, with no extra API call. Dimensions are restricted to Dependency, Result, EventType and ErrorClass: any other key throws, to keep custom-metric cost bounded ($0.30 per unique metric per month).

MetricUnitDimensionWhenEmitted by
DependencyUnavailableCountDependency (DynamoDB, SNS, SQS, S3, KMS, SES, Cognito, or AWS when the SDK error doesn't identify the service)Each time an AWS throttle/unavailable error is mapped to 503 DEPENDENCY_UNAVAILABLEAny route handler
StreamRecordsCountResult: okOnce per DynamoDB stream record stream-router successfully plans and executesstream-router (IntegrationStack, authored, not deployed — see Infrastructure)
OutboxPublishedCount—Once per record, with the count of publish actions that succeeded via publishOutbox (0 is not emitted)stream-router
OutboxPublishFailedCountResult: errorWhen executeActions throws for a record that had publish actions, with the count of planned publishes for that recordstream-router
CounterUpdatesCount—Once per record, with the count of counterDelta actions planned (0 is not emitted)stream-router
TcpEventsCountResult (applied, duplicate, stale, ignored, invalid, error), EventType (the envelope's type, or unknown if the body didn't parse)Once per SQS record tcp-events processestcp-events (IntegrationStack, authored, not deployed)
PlantDeviceReleaseFailedCount— (namespace CseHttpBe/<stage> carries the stage)Owner (mobile) DELETE /v1/plants/{plantId}: the second device release, after the plant META transaction, throws. Logged alongside plant_after_deleting_hook_failed — see TroubleshootingPlants route handler
DeviceRemovalStuck——Removed (ADR 0012) with the device-registry-sweeper; never deployed—
DeviceInboundAnomaly——Removed (ADR 0012): the inbound device events it counted are no longer consumed—

No alarm is attached to any of these yet. The five stream-router/tcp-events metrics are authored and unit-tested, but — same caveat as the stacks that emit them — they produce no real data in any stage today: IntegrationStack needs -c busEnabled=true to even exist, and that same flag gates whether either Lambda is ever actually invoked (see Edge and integration stacks above).

API Gateway stage access logs go to a separate LogGroup, one JSON line per request (fields in Infrastructure → ApiStack). Use them to tell "the authorizer rejected this before Lambda ran" (status: 401, authorizerError set, no integrationStatus) apart from "the Lambda itself failed".

Device registry sweeper (feature 005)​

Removed (ADR 0012). The hourly device-registry-sweeper (rule DeviceRegistrySweepRule) and its DeviceRemovalStuck metric were never deployed and are no longer in code. Devices, transfers and imports belong to the TCP server.

Logs Insights queries​

All errors across the route functions:

fields @timestamp, @log, msg, name, error
| filter level = "ERROR"
| sort @timestamp desc

Email sign-in funnel (run against the CreateAuthChallengeFn and VerifyAuthChallengeFn log groups):

fields @timestamp, msg
| filter msg like /email_signin_/
| stats count() by msg

Authorizer rejections and slow requests (run against the access-log group):

fields @timestamp, routeKey, status, authorizerError, responseLatency, integrationLatency
| filter status >= 400 or responseLatency > 1000
| sort @timestamp desc

Inbound device anomalies by kind (run against the tcp-events log group):

fields @timestamp, kind, eventId
| filter msg = "device_inbound_anomaly"
| stats count() by kind

Everything the handler logged for one request, once you have its requestId (from an error response body, the X-Request-Id header, or an access-log line) — run against a route function's own log group:

fields @timestamp, @log, msg, level, routeKey, status, code, latencyMs
| filter requestId = "<requestId>"
| sort @timestamp desc

requestId is per-request and per-function; it does not follow a write through the stream/outbox/SQS pipeline into stream-router or tcp-events. correlationId does (EventContext.correlationId, outbox.ts): it starts as the originating API request's own id, rides inside the published Envelope.correlationId, and (per Architecture → Outbound) is the field to trace an HTTP-originated write across to whatever the TCP side logs for the event it received. Today stream-router/tcp-events don't log correlationId themselves (their own structured events are the StreamRecords/TcpEvents metrics in Custom metrics, not a log line with that field) — the query below is written against the originating request's own log group, and is the query to use once stream-router gains a log line that includes it:

fields @timestamp, @log, msg, routeKey, correlationId
| filter correlationId = "<correlationId>"
| sort @timestamp desc

Device registry operations (feature 005)​

All of the below are human-run; agents never run them. No command here mutates AWS state except the existing scripts, which default to a dry run.

Import troubleshooting (D14). Removed (ADR 0012) — the D14 routes, the uploads bucket, the device-import-jobs queue, its DLQ, DeviceImportWorkerFn and the DeviceImportDlqDepth alarm were never deployed and are no longer in code.

DLQ replay. Inbound TCP events that failed five times land in from-tcp-dlq; inspect the cause in the tcp-events log group first, then use the existing scripts/redrive-dlq.sh (see Replay, rebuild and redrive), dry run first:

scripts/redrive-dlq.sh --stage dev --queue from-tcp --dry-run

Stuck removal re-publish. Removed (ADR 0012) — device.removed.v1, device.erasure.completed.v1 and DeviceRemovalStuck no longer exist on this side.

Legacy conflict log query. Removed (ADR 0012) — the lazy legacy-device migration (migrateLegacyPlantDevices, legacy_device_conflict log line) no longer exists. Legacy claim items are read as bindings unchanged; see Plant devices.

Alarms runbook​

All alarms below (ObservabilityStack, lib/observability-stack.ts, T002-093) use an absolute count/duration threshold with treatMissingData: NOT_BREACHING — a deliberate dev-phase choice (near-zero traffic means a rate-based alarm would otherwise sit in INSUFFICIENT_DATA forever) that also means any single occurrence pages, not just a sustained run. All of them publish to one SNS topic, cse-http-be-<stage>-alerts (AlertTopicArn); confirm the email subscription once per stage (aws sns list-subscriptions-by-topic --topic-arn <AlertTopicArn>) — a PendingConfirmation subscription delivers nothing, and the stack still reports CREATE_COMPLETE.

The first six (through PlantDeletionOverdue) are always present. BacklogAge exists only when ObservabilityStack is given the integration refs — bin/app.ts only does that with -c busEnabled=true. With busEnabled, ReportsStack adds ReportsOverdue and NotifyStack adds NotifyReconcileStale (8 alarms in all; no DLQ alarm, no DependencyUnavailable alarm). Cost (CloudWatch pricing page, read 2026-10-27). Standard alarms bill $0.10 per alarm metric (each metric in a metric-math expression counts) after 10 free; a Metrics Insights query alarm bills $0.10 per metric the query analyses and is outside the free tier. Default synth: 5 alarms = 5 standard alarm metrics = $0. busEnabled: 8 alarms = 10 standard alarm metrics (the 5 above + BacklogAge 3 inputs + ReportsOverdue + NotifyReconcileStale) → exactly the free tier = $0 (the notify-recompute BacklogAge input was dropped by owner decision 2026-10-27). The DependencyUnavailable Metrics Insights alarm was dropped by owner decision 2026-11-10 (Q12) because Insights alarms bill per series outside the free tier; the DependencyUnavailable metric is still emitted and can be graphed or queried. The DlqDepth alarm (8 metrics) was dropped by owner decision 2026-10-27 to stay near the free tier; DLQs are kept but checked by hand (runbook).

AlarmFires onScopeFirst step
cse-http-be-<stage>-LambdaThrottlesAWS/Lambda Throttles sum >= 1 over 1 min, no dimensionAccount-wide — shares the account's Lambda concurrency quota (1000, L-B99A9384) with the live TCP Server's ingest functionsCheck which function throttled (per-function Throttles metric, or the function's own log group for a missing invocation). If it's a TCP Server function, this project's traffic may be starving production inverter ingestion — stop any load test immediately. Never set reservedConcurrentExecutions as a fix; it fails the deploy below the account's unreserved minimum
cse-http-be-<stage>-LambdaErrorsAWS/Lambda Errors sum >= 1 over 5 min, no dimensionAccount-wide, same reasonFind the function via its own log group's unhandled_error line (or the TCP Server's logs, if the account-wide metric came from there). See Debugging for the HTTP-side triage path
cse-http-be-<stage>-Api5xxAWS/ApiGateway 5xx sum >= 1 over 5 min, dimensioned to this stage's ApiIdThis APIPull the access-log group for the matching time window; authorizerError set with no integrationStatus means the authorizer rejected before Lambda ran, otherwise check the route function's own log group for unhandled_error
cse-http-be-<stage>-DynamoThrottlesAWS/DynamoDB ThrottledRequests sum >= 1 over 5 min, dimensioned to this stage's tableThis tableOn-demand billing mode still throttles on a hot partition key (a single PK taking disproportionate traffic) — check CloudWatch Contributor Insights for DynamoDB, if enabled, or the access patterns touching the busiest entity type
cse-http-be-<stage>-PlantDeletionOverdueCseHttpBe/<stage> PlantDeletionOverdue ≥ 1 over 5 min, no dimensionsplant-deletion-sweep Lambda, hourly (T004-714; IntegrationStack, so only with -c busEnabled=true)Look in the sweep's log group for plant_deletion_overdue: it lists up to 50 overdue plantIds. For each one, check whether TCP sent plant.erasure.completed.v1 (search the tcp-events logs for plant_erasure_*) and whether the message is sitting in the from-tcp DLQ
cse-http-be-<stage>-DeviceRemovalStuckRemoved (ADR 0012)—Never deployed; device removal belongs to the TCP server
cse-http-be-<stage>-BacklogAgeMAX of inputs normalised to seconds: stream-router IteratorAge / 1000, from-tcp and alert-events ApproximateAgeOfOldestMessage — > 300 (i.e. iterator/queues > 5 min; notify-recompute dropped 2026-10-27)busEnabled onlyFind which input: open the alarm graph (one line per input), or use the second command below the table; the stream-router lag is its IteratorAge metric. Then check that consumer's log group and the account-wide LambdaThrottles/LambdaErrors
cse-http-be-<stage>-ReportsOverdueReports still in flight > 10 min past deadline (log-based)ReportsStack, busEnabled onlySee Reports
cse-http-be-<stage>-NotifyReconcileStaleNo completed notify reconcile in a 7-day periodNotifyStack, busEnabled onlySee Notifications

Finding the queue behind BacklogAge​

Replace <stage>:

# BacklogAge: one queue (<queue> is from-tcp or alert-events)
aws sqs get-queue-attributes --queue-url $(aws sqs get-queue-url --queue-name cse-http-be-<stage>-<queue> \
--query QueueUrl --output text) --attribute-names ApproximateNumberOfMessages

The stream-router lag is its IteratorAge metric (no queue to inspect).

Checking DLQs by hand (no DLQ alarm)​

There is no DLQ alarm (owner decision 2026-10-27: DlqDepth dropped to stay within the CloudWatch free tier). A message landing in any HTTP-side DLQ (stream-router, from-tcp, alert-events, plant-jobs, notify-recompute, report-dispatch, report-runs, plan-cycles, digest) pages nobody. Check them by hand, e.g. after a deploy, after a LambdaErrors alarm, and on a regular cadence:

# 1. List every HTTP-side DLQ and its depth (visible + in flight)
for q in $(aws sqs list-queues --queue-name-prefix cse-http-be-<stage>- --query 'QueueUrls[?ends_with(@, `-dlq`)]' --output text); do echo $q; aws sqs get-queue-attributes --queue-url $q --attribute-names ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible --output text; done

# 2. Peek at messages without deleting them (visibility timeout 0 = they stay visible)
aws sqs receive-message --queue-url <url> --max-number-of-messages 10 --visibility-timeout 0 --attribute-names All

# 3. After fixing the cause, redrive the DLQ back to its source queue
aws sqs start-message-move-task --source-arn <dlq-arn>

Do not redrive the stream-router DLQ this way: it holds DynamoDB stream records, not source-queue messages — reprocess manually or use scripts/replay-outbox.ts. scripts/redrive-dlq.sh remains for from-tcp/alert-events.

Deploy note. IntegrationStack no longer exports the DLQ names. If a bus-on ObservabilityStack is already deployed, deploy the observability stack first (npx cdk deploy cse-http-be-<stage>-observability -c stage=<stage> -c busEnabled=true), then the rest; otherwise deploy --all can fail with "export … in use".

The former per-queue alarms (StreamRouterDlqDepth, FromTcpDlqDepth, AlertEventsDlqDepth, PlantJobsDlqDepth, StreamRouterIteratorAge, FromTcpQueueAge, AlertEventsQueueAge, NotifyRecomputeDlqDepth, NotifyRecomputeQueueAge, ReportDlqDepth, PlanCyclesDlqDepth) were merged into DlqDepth and BacklogAge (owner decision Q12, 2026-10-27); DlqDepth was then dropped the same day.

The busEnabled alarms are created together with IntegrationStack itself, i.e. only once a human passes -c busEnabled=true (CR-21/B-01) — there is no longer an intermediate state where the stack exists but its event-source mappings are disabled; busEnabled now gates stack creation and mapping enablement as one deploy (see Edge and integration stacks above). There is still no alarm on any of the stream-router/tcp-events custom metrics in Custom metrics (StreamRecords, OutboxPublished, OutboxPublishFailed, CounterUpdates, TcpEvents) — the DLQ-depth and queue/iterator-age alarms above are the operational signal for that path today.

Realtime ticket signing key rotation (FR-061, ADR 0003)​

:::caution Code-complete, off by default — not yet exercised in production lib/auth-stack.ts's KMS key, packages/core/src/realtime/{ticket,jwks,kms-signer}.ts and packages/api/src/handlers/realtime-{ticket,jwks}.ts are landed and unit-tested, including a synth exercising the full rotation context combo (realtimeKeyGeneration=2 + realtimeTicketPreviousKeyArn=<arn>) — feature 003 batch 25, 2026-10-03. The whole subsystem is still off by default in every stage behind -c realtimeTicketsEnabled=true (same opt-in-flag convention as busEnabled — see Edge and integration stacks). This procedure has not yet been exercised against a real deployed stage — dry-run each step (cdk diff before every deploy below) the first time it's actually needed. :::

Human-run only — never agent-run, same rule as every other state-changing operational procedure on this page (rotating a signing key while tickets are live in the field has the same blast-radius shape as a DLQ redrive: get the overlap window wrong and either live TCP connections start rejecting valid tickets, or a compromised key stays trusted longer than necessary).

The mechanism, as landed: AuthStack provisions the signing key under a generation-suffixed logical id, RealtimeTicketKey<N> (-c realtimeKeyGeneration=<N>, an integer, default 1), with alias cse-http-be-<stage>-realtime-ticket-gen<N> — KeySpec.ECC_NIST_P256, KeyUsage.SIGN_VERIFY, RemovalPolicy.RETAIN on both the key and the alias. Bumping realtimeKeyGeneration on a redeploy creates a genuine new physical key under a new logical id (CDK adds it; the old generation's key construct simply drops out of the template rather than being deleted or replaced — RemovalPolicy.RETAIN keeps it in AWS, orphaned from the stack). A CfnOutput named RealtimeTicketKeyGeneration reports which generation is currently live, alongside the existing RealtimeTicketKeyArn output and the /cse-http-be/<stage>/realtime-ticket-key-arn SSM parameter (always the CURRENT generation's ARN). The current generation's ARN reaches the realtime Lambda family as REALTIME_TICKET_KEY_ARN (config.realtimeTicketKeyArn) — the only key POST /v1/realtime/tickets signs with. A second, independent CDK context value, -c realtimeTicketPreviousKeyArn=<arn>, supplies an arbitrary KMS key ARN that GET /v1/realtime/jwks additionally publishes (REALTIME_TICKET_PREVIOUS_KEY_ARN, kms:GetPublicKey only — the realtime function is never granted kms:Sign on it, lib/api-stack.ts) without ever signing anything new.

Why rotation needs an overlap window at all: a ticket is valid for up to 10 minutes (TICKET_TTL_SEC) from issue, and a client may have cached the GET /v1/realtime/jwks response for up to its Cache-Control: public, max-age=300 (5 minutes) beyond that. Retire a key's public entry from JWKS before every ticket signed with it has either expired or been verified, and the TCP side starts failing signature checks on in-flight tickets it can no longer find a matching kid for.

  1. Capture the current (soon-to-be-previous) key's ARN. Read the RealtimeTicketKeyArn stack output (or the /cse-http-be/<stage>/realtime-ticket-key-arn SSM parameter) for the CURRENT generation before touching anything:

    aws cloudformation describe-stacks \
    --stack-name cse-http-be-<stage>-auth \
    --query "Stacks[0].Outputs[?OutputKey=='RealtimeTicketKeyArn'].OutputValue" \
    --output text
    # -> arn:aws:kms:us-east-1:574317420690:key/<old-key-id> (save this)
  2. Bump the generation AND publish the old key, in the SAME deploy. -c realtimeKeyGeneration=<N+1> and -c realtimeTicketPreviousKeyArn=<old key ARN from step 1> MUST be passed together, on one cdk deploy:

    npx cdk deploy cse-http-be-<stage>-auth cse-http-be-<stage>-api \
    -c stage=<stage> \
    -c realtimeTicketsEnabled=true \
    -c realtimeKeyGeneration=<N+1> \
    -c realtimeTicketPreviousKeyArn=<old key ARN from step 1>

    Do not split this into two deploys (bump the generation now, add realtimeTicketPreviousKeyArn later) — between those two deploys REALTIME_TICKET_KEY_ARN would already be the new key (so POST /v1/realtime/tickets starts signing with it immediately) while GET /v1/realtime/jwks would NOT yet be publishing the old key, because the deploy that adds realtimeTicketPreviousKeyArn hasn't happened yet. Any ticket issued in that gap under the new key is fine, but any ticket still in flight from BEFORE this deploy (signed with the old key, valid up to 10 more minutes) would fail verification the moment a TCP client's JWKS cache refreshes and no longer finds the old kid. One combined deploy closes that window entirely — the new key becomes active and the old key starts being published at the same instant.

  3. Confirm both keys are actually live — GET /v1/realtime/jwks (curl it directly; it's public, unauthenticated) should list both kids. Note that today's CloudFront distribution for this API uses a CACHING_DISABLED origin policy (see Architecture → Overall architecture), so the client-respected Cache-Control: max-age=300 header is the dominant cache, not an edge TTL — re-check this note if that policy changes.

  4. Hold the overlap, then retire the old key from JWKS. Keep -c realtimeTicketPreviousKeyArn set for at least 1 hour beyond the 5-minute JWKS cache window (so: ticket TTL 10 min + JWKS cache 5 min + 1 hour margin ≈ comfortably over an hour total) — long enough that no ticket signed by the old key, and no client JWKS cache entry predating its removal, can still be in play. After that window, redeploy WITHOUT realtimeTicketPreviousKeyArn (same realtimeKeyGeneration=<N+1>):

    npx cdk deploy cse-http-be-<stage>-auth cse-http-be-<stage>-api \
    -c stage=<stage> \
    -c realtimeTicketsEnabled=true \
    -c realtimeKeyGeneration=<N+1>

    GET /v1/realtime/jwks now serves only the new key. RemovalPolicy.RETAIN on both the dropped-generation Key and its Alias means neither is deleted by this deploy — the old key (and its alias) sit in AWS, orphaned from the CDK app, costing roughly $1/month (KMS's per-key charge) until someone acts on them, same as any other retained-but-unused key in this account. If the old key truly needs to be destroyed (compromise response, not routine rotation), do that as its own deliberate, separately-approved AWS console/CLI action against that specific key id (KMS enforces a minimum 7-day pending-deletion window itself), never as a side effect of a stack deploy — otherwise, leaving it retained-and-idle indefinitely is a known, accepted small ongoing cost, not a bug.

Routine rotation cadence and compromise-response urgency are operational decisions, not something this runbook fixes a schedule for — the mechanism above is the same either way; only the time between steps 2 and 4 differs.

Replay, rebuild and redrive (FR-026, FR-049)​

Three human-run, never agent-run tools exist for the outbox/integration pipeline, none of which are wired into npm test or any CI gate:

  • scripts/redrive-dlq.sh (T002-096) — moves messages from one of IntegrationStack's DLQs (from-tcp-dlq, alert-events-dlq) back to its source queue, via aws sqs start-message-move-task. Prints the exact source/destination queue ARNs and the DLQ's current depth, then refuses to proceed without the operator typing the destination queue's name back as confirmation. Supports --dry-run (prints the plan, makes no AWS call) and an optional --rate cap. stream-router's own DLQ has no source queue to redrive into (its source is the table's DynamoDB stream, not a queue) — the script refuses --queue stream-router and points at inspecting it with aws sqs receive-message instead.

    scripts/redrive-dlq.sh --stage dev --queue from-tcp --dry-run
    scripts/redrive-dlq.sh --stage dev --queue alert-events
  • scripts/replay-outbox.ts / npm run replay:outbox (T002-091) — republishes outbox items (OUTBOX#<hour>#<shard> keys, blueprint 03 §6.7) for an operator-given hour range, querying each of the 10 shards per hour directly by key (never a Scan) and re-running publishOutbox for the items found. Defaults to a dry run; an explicit --execute flag is required to actually publish. Human-run with the operator's own AWS credentials and environment (TABLE_NAME, STAGE, AWS_REGION, ACCOUNT_ID, same as a deployed Lambda) — never invoked by an agent.

    npm run replay:outbox -- --from 2026092812 --to 2026092814 # dry run
    npm run replay:outbox -- --from 2026092812 --to 2026092812 --execute
  • scripts/rebuild-projections.ts / npm run rebuild:projections (T002-091) — recomputes the facet-counter (COUNT#…) and search-token (SRCH#…) projections for one organization and one registered collection, by querying GSI2 for that org/collection's entities (never a Scan) and re-deriving the projections from their current state, restoring any that were deleted or desynced. Defaults to a dry run; --execute writes. Upserts tokens for live entities only — it doesn't sweep SRCH# tokens left behind by entities deleted since the last correct run. Also human-run, never invoked by an agent.

    Since 2026-11-03 (committed, not yet deployed) the tokens come from the stream planner itself (planRecord on a synthetic INSERT), so the script rebuilds plant, customer, partner and tag tokens and writes rows in the same shape as the stream-router (entityId, label, sublabel, code, words). Before that it only rebuilt tokens of collections with a generic search list, which skipped plants, customers and partners entirely. Run it once per org and collection after that change is deployed: older token rows have no words, so multi-word and code searches (A12) miss them, and they show the field name instead of the entity name. --gsi2pk is the collection's list key:

    Collection--gsi2pk
    plantsORG#<orgId>#PLANTS
    customersORG#<orgId>#CUSTOMERS
    partnersORG#<orgId>#PARTNERS
    tagsORG#<orgId>#TAGS
    members (2026-11-25)ORG#<orgId>#MEMBERS
    shares (2026-11-25)ORG#<orgId>#SHARES

    Members (2026-11-25, deployed to dev). ORG#<orgId>#MEMBERS recomputes every COUNT#members#… counter (status, role, department, scope kind, MFA) and the member name tokens, and deletes each COUNT#members#… item of the org it did not recompute (dry run prints [dry-run] delete stale …). REMOVED members are not counted. --all-orgs runs members and shares for every org in the ORGCODE# guards, any kind, the Crown org included. Ran on dev 2026-11-25 (--all-orgs --execute: 40 orgs, 443 tokens, 0 failures) after deploying the fix (KI-57). Re-run only if counters drift again.

    Access requests (2026-11-26; dev dry run found no access requests to count). --all-orgs also recounts each of those orgs' COUNT#accessRequests#status#… counters (the badges.pendingAccessRequests badge and the access-requests work-queue tile) from its own ORG#<orgId> / ACCESSREQ# partition, since access requests have no GSI2 list key. It counts the stored status, like the stream: a PENDING request past its 30-day expiresAt still counts as PENDING. Counters no request accounts for are deleted. Dry run prints [dry-run] ORG#… COUNT#accessRequests#… lines; the summary line reports N access-request counter(s). A script change only, so no deploy is needed before running it.

    npm run rebuild:projections -- --org 01ORG... --gsi2pk 'ORG#01ORG...#PLANTS' # dry run
    npm run rebuild:projections -- --org 01ORG... --gsi2pk 'ORG#01ORG...#PLANTS' --execute

    Every org at once (--all-orgs, ADR 0015, committed 2026-11-03, not yet deployed). Runs the same rebuild for every operator org in the platform directory (GSI2 ORGS#OPERATOR) for plants, customers, partners and tags, and for every personal org for plants and tags. Personal orgs come from the ORGCODE# guards (every personal org, including one no user points to any more) and, when USER_POOL_ID is set, also from Cognito users → personal-org pointer; each org is rebuilt once (since 2026-11-12; before that only Cognito users were walked). No Scan. One failing org/collection is reported and the run carries on (exit code 1 at the end). Needs TABLE_NAME/STAGE; USER_POOL_ID is optional (without it the Cognito pass is skipped). The directory must be filled (npm run backfill:org-directory if it never ran on the stage). Run this once after deploying ADR 0015: platform-wide search reads only token rows that carry the new GSI1 keys.

    npm run rebuild:projections -- --all-orgs # dry run
    npm run rebuild:projections -- --all-orgs --execute

    Platform-wide plant list entries (ADR 0016, committed 2026-11-03, not yet deployed). For every schema v2 plant META it reads on ORG#<orgId>#PLANTS (operator = that org), the rebuild also puts the plant's PLANT#<plantId>/LISTALL entry, which the platform-wide plant list reads. Dry run lists them as [dry-run] LISTALL plant=… PLANTS#ALL#<lifecycle>#<shard>. It only puts (an absolute value, idempotent) and never deletes. Run --all-orgs --execute once after deploying ADR 0016; until then plants created before the deploy are missing from the Super Admin "all plants" list only (each org's own list is unaffected). New plants get their entry from the create/rename/archive/restore/delete transactions, so a re-run is never needed after that. After migrate:legacy-plants --apply, the migrated plants already have an entry (the migration writes it too).

    Facet counters are still rebuilt for generic facets only; the plant, customer and partner counters (written by their extractors) are not.

See cse-http-be's packages/core/test/integration/replay.int.test.ts (authored only, never run by an agent — same convention as every other *.int.test.ts in this repo) for what's asserted: replay only selects items in the given hour range, and rebuild restores counters/tokens a direct delete had wiped out.

Fleet dashboard counters (ADR 0024)​

:::note Status Committed 2026-11-11, not deployed, and the backfill has not been run on any stage. :::

The Crown HQ dashboard (GET /v1/dashboard fleet view) reads one fleet-wide partition, FLEET#ALL:

  • COUNT#plants#ALL#ALL, COUNT#plants#lifecycle#<ACTIVE|ARCHIVED>, COUNT#plants#SUM#ALL (capacityKwp, expectedAnnualYieldKwh), COUNT#plants#regionTagId#<tagId> and COUNT#plants#GEO#<tagId>. The region items also hold tagOrgId. The plants stream projector updates them in the same transaction as each org's own counters, so they need the stream-router (busEnabled, on for dev).
  • SETUP#<plantId>, a copy of each org's setup-incomplete marker with operatorOrgId, written and deleted in the same transactions as the org's own marker.

Plants written before the deploy are not in it. Run this once after deploying ADR 0024, in a quiet window (its absolute writes race the stream's increments for plants changed during the run):

npm run rebuild:projections -- --all-orgs # dry run: lists every FLEET#ALL item it would write or delete
npm run rebuild:projections -- --all-orgs --execute

Besides the ADR 0015/0016 work, --all-orgs now adds up every org's plant META into absolute FLEET#ALL counters, copies every org's SETUP# markers, and deletes FLEET#ALL items that no org accounts for. If any org or collection fails, it leaves FLEET#ALL untouched and says so (FLEET#ALL NOT rebuilt), because a partial walk would under-count. Fix the failure and re-run; a re-run is idempotent. Same environment as above (TABLE_NAME, STAGE, optionally USER_POOL_ID), and the org directory must be filled.

To check the result (read only), query PK = FLEET#ALL with SK beginning COUNT#plants# and compare COUNT#plants#ALL#ALL with the number of ACTIVE plants in the Super Admin "all plants" list.

Legacy plant migration (npm run migrate:legacy-plants, FR-026)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

scripts/migrate-legacy-plants.ts (T004-318) converts old mobile-era plant items to the current schema (v2). A web PATCH with If-Match: "0" does the same thing one plant at a time. Each plant gets a PL- code, its owner's personal org as both operator and customer, version: 1, the new index keys, and a plant.upserted.v1 outbox event.

  • Dry run by default. Without --apply the script only reports what it would migrate.
  • --stage is required. There is no default.
  • No Scan. It pages through Cognito users with listUsers, queries each user's PLANT# memberships (OWNER only), and reads each plant's META item.
  • Safe to re-run. The write only succeeds if the item is still legacy. A plant that is already migrated, or that a PATCH migrated in the meantime, is counted as skipped.
  • Environment. It uses the operator's own AWS credentials and needs TABLE_NAME, AWS_REGION, ACCOUNT_ID and USER_POOL_ID. SERVER_CLIENT_ID can be any placeholder.
  • Exit code. It exits 1 if any plant failed.
  • Mobile app impact. A migrated plant is a schema v2 item. Before the fix that lets the app edit and delete a migrated plant owned by its personal org, the app gets 409 INVALID_STATE on edit and delete for every migrated plant (KI-39). Deploy that fix to the stage first.
  • New app plants are not legacy. Since 2026-11-03 the app's POST /v1/plants writes a schema v2 plant, so a run is only needed for plants created before that change reached the stage.
  • Setup Required records (B-6, 2026-11-19). A migrated plant with no device registered also gets its setup-incomplete records (ORG#<org>/SETUP#<plantId> and FLEET#ALL/SETUP#<plantId>). For plants migrated before then, run the setup-record backfill.
  • Only owned plants are found. The walk goes from Cognito users to their OWNER memberships, so a legacy plant with no owner record, or whose owner account was deleted, is never seen and is not counted as skipped.
npm run migrate:legacy-plants -- --stage dev # dry run
npm run migrate:legacy-plants -- --stage dev --apply

Last run on dev: dry run on 2026-11-19 found 30 users, 0 legacy plants (nothing to apply).

What still needs the migration (B-1). GET /v1/me/favorites already returns favourited legacy plants (without entity), but legacy plants have no org id and no search tokens, so they stay out of search suggestions and the web plant list until this script has run on the stage.

packages/core/test/integration/migrate-legacy-004.int.test.ts covers the script against DynamoDB Local only. Like every *.int.test.ts, it is never run by an agent.

Setup-record backfill (npm run backfill:setup-markers, B-6)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name. Script: scripts/backfill-setup-markers.ts; logic: packages/core/src/plants/setup-marker-backfill.ts.

Why. The dashboard's "Setup Required" list (setupIncomplete on GET /v1/dashboard) is read from per-plant setup-incomplete records: ORG#<operatorOrgId>/SETUP#<plantId> and its fleet copy FLEET#ALL/SETUP#<plantId>. "Setup Required" means an ACTIVE plant with no device registered (no plant ↔ serial binding), owner-confirmed 2026-11-19. Until 2026-11-19 only the web create wrote these records, so plants created from the app, plants created for an end user by Crown staff, and legacy plants already migrated had none and were left out of the count. Every create path and the legacy migration write them now; the first device binding (HTTP claim or TCP binding) deletes both in its own transaction.

What it writes. For each ACTIVE schema v2 plant with no device registered, whichever of the two records is missing. Nothing else changes; plant META is only condition-checked.

  • Skips legacy plants (no org; run migrate:legacy-plants first), DELETING and ARCHIVED plants (an archived plant's record is parked on META and restored by the restore), plants with a device, and plants that already have both records. The summary counts each reason (legacy, notOperator, duplicate, gone, notActive, parked, hasDevice, hasMarker, changed, raced).
  • Race-safe. Each write is a transaction that checks the plant is still ACTIVE in that org. After writing it re-reads the bindings; if a device was registered in that instant, it deletes the records again (raced).
  • No Scan. Same walk as resync:plants: org code guards, then each org's GSI2 plant collection (operator side), then consistent GetItems of META and the two records, and a key-only Query of the bindings.
  • Idempotent. A rerun finds every record present (hasMarker) and writes nothing. Writes pause 1 s every 25.
  • Known effect. A plant whose devices were all removed later has no binding now, so it gets the records too and counts as "Setup Required" again. The live unbind paths do not re-add them.
  • Flags. --stage <stage> (required); dry run by default; --apply (or --execute) to write; --org <orgId> for one org; --limit <N> to stop after N plants. Unknown flags are rejected. Exit code 1 when any plant failed.
  • Environment. Your own AWS credentials (default SDK chain), TABLE_NAME (required) and AWS_REGION.
  • Order. Deploy first (so new creates write the records), then migrate:legacy-plants, then this.
npm run backfill:setup-markers -- --stage dev # dry run
npm run backfill:setup-markers -- --stage dev --org <orgId> --limit 10 --apply # small first batch
npm run backfill:setup-markers -- --stage dev --apply

Last run on dev: 2026-11-19 with --apply: 26 orgs, 21 plants, 12 eligible, 24 records written, 9 skipped (hasDevice), 0 failed.

Plant type migration (npm run migrate:plant-types, owner decision Q1)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

PlantType is now RESIDENTIAL | COMMERCIAL | INDUSTRIAL only. Plants written earlier may still store the retired UTILITY or OTHER; every read already maps them (UTILITY → INDUSTRIAL, OTHER → COMMERCIAL, readPlantType), so nothing breaks before the migration runs. scripts/migrate-plant-types.ts rewrites the stored values.

  • Dry run by default. Without --apply it only reports what it would change. --stage is required.
  • No Scan. It pages Cognito users (ListUsers), reads each user's mobile plant access rows and org memberships, then each org's operator plant partitions (GSI3), then each distinct plant's META item.
  • Also rewrites references found in the same walk: maintenance-plan scopeRule.plantTypes (org PLAN#), notification-rule PLANT_TYPE targets, and saved-view plantType filters (team views per org, personal views per user VIEW#PLANTS#). The final line reports refs (found) and refsUpdated.
  • Conditional writes. Each update is conditional on the current value (and on version for web plants, which is bumped). An item that changed meanwhile is reported, not retried; an unknown value is reported and never changed.
  • Output. A final migrate-plant-types: {…} JSON line. Exit code 2 if anything raced or was unknown, 1 on a fatal error.
  • Environment. The operator's own AWS credentials; needs TABLE_NAME, AWS_REGION, ACCOUNT_ID, USER_POOL_ID.
npm run migrate:plant-types -- --stage dev # dry run
npm run migrate:plant-types -- --stage dev --apply

Strip retired plant battery fields (npm run migrate:strip-plant-battery, 2026-11-18)​

Human-run only, dev only. Agents never run it with --apply (Hard Rule 2). Battery data moved from plants to devices on the TCP server; plant hasBattery is now derived from the plant's devices (META batteryDeviceCount, kept by the stream). Older items still store hasBattery, batteryCapacityKwh, batteryPowerKw, batteryBrand and batteryBrandOther on plant META, and a copy of batteryBrand on every access-index row (USER#<sub>/PLANT#<p>). Nothing reads them; scripts/strip-plant-battery-fields.ts removes them.

  • Dry run by default. Without --apply it prints each REMOVE it would make. --stage dev is required; any other stage is refused.
  • No Scan. Same walk as the plant type migration: Cognito users → their plant rows and org memberships → each org's operator plant partitions (GSI3) → each plant's META and its access-index rows (GSI1 PLANT#<p>).
  • Idempotent. Each write is REMOVE of the attributes found, conditioned on the item existing; a rerun reports 0. It never touches batteryDeviceCount or binding items.
  • When. After the HTTP deploy that stops writing the fields. Every plant edit also removes them on its own.
  • Output. A final strip-plant-battery-fields: {…} JSON line (plants, metaToStrip, rowsToStrip, stripped, gone). Exit code 1 on a fatal error.
AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> ACCOUNT_ID=574317420690 npm run migrate:strip-plant-battery -- --stage dev # dry run
AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> ACCOUNT_ID=574317420690 npm run migrate:strip-plant-battery -- --stage dev --apply

Plant owner backfill (2026-11-20)​

npm run migrate:plant-owners — scripts/backfill-plant-owners.ts, logic in packages/core/src/plants/owner-backfill.ts (ADR 0029).

Human-run only, dev only. Agents never run it with --apply (Hard Rule 2). Every plant created since 2026-11-20 stores its owner (ownerUserSub) on META; older plants may have none. This stores one and republishes plant.upserted.v1 so TCP re-owns the plant's devices (and their batteries).

  • Owner chosen, first match: the plant's End User (customerSub) → the owner of its personal customer org → its creator (createdBy) → the legacy ownerSub. A plant where none resolves is reported unresolved and left alone.
  • Dry run by default. Without --apply it prints, per plant, the owner source it would use. --stage dev is required; any other stage is refused. Optional --org <orgId> and --limit <N>.
  • No Scan. Org directory → GSI2 ORG#<o>#PLANTS filtered on plants without ownerUserSub → consistent META read → one transaction: Update META (ownerUserSub, version + 1, conditioned on version, lifecycle, operator and still no owner) + the plant.upserted.v1 outbox row at the new version.
  • Idempotent. A plant with an owner is not selected again; a rerun reports 0. Writes pause 1 s every 25.
  • When. After the HTTP deploy that stores owners on create.
  • Output. A final backfill-plant-owners: summary line (would update / updated by source, skipped by reason, failed). Exit code 1 when any plant failed.
AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main npm run migrate:plant-owners -- --stage dev # dry run
AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main npm run migrate:plant-owners -- --stage dev --apply

Re-key TCP-owned bindings (npm run migrate:binding-keys, ADR 0020)​

Human-run only, dev only. Agents never run it (Hard Rule 2). It re-keys every binding TCP already owns (tcpDeviceId set) from PLANT#<p>/DEVICE#<serialNorm> to PLANT#<p>/DEVICE#TCP#<deviceId> and writes one serial guard per current serial. Bindings TCP hasn't confirmed are left for the consumer to convert on TCP's next event.

TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> npm run migrate:binding-keys -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> npm run migrate:binding-keys -- --stage dev --apply

Run it after deploying the ADR 0020 consumer. It walks plants with Query/Get only (no Scan), is idempotent (a rerun finds nothing left), and exits 2 when a binding changed mid-run or a guard is held by another plant (printed, never overwritten). deviceCount doesn't change. Any --stage other than dev is refused.

Device binding guard backfill (npm run backfill:binding-guards, ADR 0012)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

scripts/backfill-binding-guards.ts (helpers in packages/core/src/plants/binding-guard-backfill.ts) closes KI-36. Legacy device claim items have no SERIALBIND#<serialNorm>/GUARD item, so the same serial can be bound to two plants. The script writes the missing guards.

  • Dry run by default. Without --apply it prints [dry-run] would guard <serialNorm> → plant <plantId> lines and the totals. Run the dry run first and read the conflicts before applying.
  • --stage is required. There is no default. Any other argument is an error.
  • No Scan. It pages Cognito users with listUsers, reads each user's PLANT# access-index rows, then each plant's DEVICE# bindings and the existing guards.
  • Conflicts are never changed. [conflict] <serialNorm> on plants <a>, <b> means the same normalised serial is bound to more than one plant, or a guard already points at another plant. The script leaves those bindings alone. Decide which plant keeps the device, unbind it from the others (DELETE /v1/plants/{plantId}/devices/{serial}), then re-run. [invalid] marks a legacy serial that fails the 3–64 [A-Z0-9._] rule. It gets no guard.
  • Safe to re-run. Guards are written with attribute_not_exists(PK). A guard that appears meanwhile is counted as a conflict and left unchanged.
  • Output. A final JSON line: plants, bindings, written, alreadyGuarded, conflicts, invalid.
  • Exit code. 2 if there were any conflicts, 1 on a fatal error.
  • Environment. It uses the operator's own AWS credentials and needs TABLE_NAME, AWS_REGION, ACCOUNT_ID and USER_POOL_ID.
npm run backfill:binding-guards -- --stage dev # dry run
npm run backfill:binding-guards -- --stage dev --apply

First platform org and Super Admin (scripts/bootstrap-org.ts)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

A new stage has no Crown PLATFORM org and therefore no Super Admin to invite anyone. This script creates the org and promotes one existing Cognito user (they must have signed up already) to Super Admin. It never creates a user and never handles a password; email and name are read from Cognito.

  1. Find the user's sub (read-only): aws cognito-idp list-users --region us-east-1 --user-pool-id <pool-id> --filter 'email = "<email>"' --query 'Users[0].Username' --output text
  2. Dry run, then the same command with --execute:
TABLE_NAME=cse-http-be-<stage>-main AWS_REGION=us-east-1 ACCOUNT_ID=<account-id> USER_POOL_ID=<pool-id> SERVER_CLIENT_ID=placeholder npx tsx scripts/bootstrap-org.ts --stage <stage> --kind PLATFORM --name "Crown Solar Energy (HQ)" --super-admin-sub <sub>
  • Run --execute once per stage. A second run creates a second PLATFORM org.
  • Resume. If the org was created but the promotion failed (the output shows [ok] created org <orgId> and then an error), fix the cause and re-run with --org <orgId> --execute added: it promotes the member in that org and creates nothing.
  • Fixed 2026-11-02: --execute used to be ignored (the CLI always dry-ran), and the promotion failed with MFA_POLICY_FLOOR (see Team API). Both are fixed; use a checkout at or after that date.
  • After it runs, the user signs out and in again to see the platform org.

RBAC roles backfill (npm run backfill:rbac-roles, ADR 0014)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

scripts/backfill-rbac-roles.ts (logic in packages/core/src/repositories/rbac-backfill.ts) brings orgs created before the RBAC policy in line with new ones:

  1. Installer template. Every non-personal org except the PLATFORM (Crown) org gets the seeded Installer role (code R-91), the same one new orgs get. Since 2026-12-01 (QA 2026-11-30) the PLATFORM org never gets it, at create or in this backfill: an Installer-template copy already there is deleted through the normal role delete (ROLE_DELETED), or kept and counted in-use while a member or pending invitation holds it. Counted under installer.platform and platformInstaller (deleted / wouldDelete / inUse). Run on dev 2026-12-01 (--only installer --apply): Crown's copy deleted (deleted: 1), 11 Business orgs unchanged, no failures. An org that already has an Installer template, or any role named "Installer", is left alone. An existing Installer-template role below sharing: MANAGE is raised to MANAGE (2026-11-03, R-5) through the normal role edit (ROLE_UPDATED in that org's access log); the dry run prints would raise … lines. Since 2026-11-06 (IO-9, ADR 0021) every category below the new Installer default is raised to it in the same edit (plants, devices, alerts → MANAGE; commands, service, reports, registersWrite → EDIT; customers → VIEW). Raise only: a category the Business set higher is kept. Since 2026-11-26 (owner, reversing RBAC-S6) the template is back at sharing: MANAGE, so a template role at VIEW is raised to MANAGE again, and a plain copy of the Installer role in a Business (a custom SCOPED role with no template key) is raised on sharing only — its other levels are the Business's choice. Counted under installerSharing. Run on dev 2026-11-26 (--only installer --apply, with TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1): 41 orgs walked, 1 Installer role raised (installerSharing.raised: 1), 0 failures — the other 6 Business Installer roles were already at MANAGE, and no plain copies needed raising.
  2. Business role. Every ACTIVE Administrator member of a non-personal OPERATOR org (a Business) moves to the Business system role. The move goes through the normal member role-change path: a MEMBER_ROLE_CHANGED entry in that org's access log (actor system:rbac-backfill) and an access.revoked.v1 event, because Business is lower than Administrator in several categories (the run prints them: the FULL ones become MANAGE, firmware becomes NONE). Those members' realtime sessions refresh. Business holds no FULL level, so the role-based MFA requirement no longer applies to them; an explicit per-member MFA requirement stays. PARTNER, CUSTOMER and PLATFORM Administrators are not touched.
  3. Retired templates (2026-11-03, R-2). Every Operations Manager, Technician, Sales or Compliance Auditor template copy is deleted through the normal role delete (ROLE_DELETED). A copy that a member or pending invitation still holds is kept and counted under retired.inUse; reassign them in the web console and re-run.
  4. Personal-org owners (2026-11-06, IO-8, ADR 0021). Every ACTIVE Administrator member of a personal org moves to the built-in End User role through the same member role-change path (MEMBER_ROLE_CHANGED, and access.revoked.v1 because End User is lower: team, settings, customers, roles and audit drop to NONE, reports to VIEW). Scope stays ALL (their own plants). The dry run prints would move <sub> Administrator → End User. Since 2026-11-12 (console request §4) the same step also moves every ACTIVE Administrator of a customer org to End User (the scope is kept), and --only personal covers both. The Installer step also raises existing Installer roles to reports: MANAGE (§5). Not yet run on dev for these two changes — dry-run first; see Role boundaries.
  • Dry run by default. Without --apply (alias --execute) it prints would move <sub> Administrator → Business lines and the totals. Read them before applying: an Administrator you want to keep as Administrator can be moved back afterwards in the web console (or run with --only installer).
  • --stage is required. --org <orgId> limits it to one org. --only installer, --only business, --only retired or --only personal runs one step.
  • No Scan. Orgs come from the ORG code counter and code guards; Administrators from each org's member collection (GSI2 ORG#<o>#MEMBERS, filtered by roleId), paged.
  • Safe to re-run. A rerun finds nothing left to do. A member changed since it was listed is skipped, and an "Installer" role created by the app during the run is counted under name-taken, not as a failure.
  • Edited roles. If a Super Admin has edited the Administrator or Business role, the printed list of lowered categories and the move itself use the edited versions.
  • Output. A final JSON line: orgs, installer (created, would-create, exists, name-taken, personal, missing-org), installerSharing (raised, wouldRaise), retired (deleted, wouldDelete, inUse), business (converted, wouldConvert), personalOwner (converted, wouldConvert), failures. Each failure is printed.
  • Exit code. 1 if anything failed.
  • Environment. It uses the operator's own AWS credentials and needs TABLE_NAME and AWS_REGION.

--stage does not set the table: put TABLE_NAME and AWS_REGION in front of every command, or the run stops with Missing required environment variable: TABLE_NAME before reading anything. Dev's table is cse-http-be-dev-main.

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:rbac-roles -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:rbac-roles -- --stage dev --org <orgId> --apply # one org first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:rbac-roles -- --stage dev --apply
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:rbac-roles -- --stage dev --only retired --apply # delete unused retired templates only
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:rbac-roles -- --stage dev --only personal --apply # personal-org owners → End User only

Run on dev, 2026-11-06 (captured output). 12 orgs. 11 personal-org owners moved to End User. The HQ Installer role was raised to the IO-9 defaults on a second --apply: the first attempt hit KI-47, fixed in 349e2e2. A final dry run reported personalOwner.wouldConvert: 0, installerSharing.wouldRaise: 0 and failures: 0.

Customer list backfill (npm run backfill:customer-list, ADR 0017, console request §8)​

The Crown-wide customer list (GET /v1/orgs/{crownOrgId}/customers for a Crown Super Admin / Administrator, Role boundaries) reads one ORG#<customerOrgId>/LISTALL#CUSTOMER entry per customer. Customers and personal orgs created before ADR 0017's write side shipped have none, so they are missing. rebuild:projections does not write these entries; this does:

  • every Business (non-personal OPERATOR org): one entry per customer profile (ORG#<op>#CUSTOMERS);
  • every personal org (Independent End User): one entry with personal: true.

Each entry is written whole with an absolute plantsLive (the org's v2 plants that are ACTIVE or ARCHIVED), so a rerun converges; plant writes add to it live, so run it in a quiet window. Query/Get only, no Scan; sequential writes pausing 1 s every 25. Dry run by default; dev only.

Since 2026-11-12, a run over every org (no --org) also sets the four PLATFORM#CUSTOMERS/COUNT#<shard> items to absolute active, churned, noPortal and personal totals; the Crown-wide list's tiles read them. It prints the totals (platform counters would be set: … on a dry run) and skips the write if any org failed. A single-org run leaves them alone. Customer writes add to these counters live, so this too belongs in a quiet window. Since 2026-11-25 (console request C1) the same run also sets one city#<normalised city> count per city of the ACTIVE Business customers on each shard and removes cities no longer present; the Crown-wide list's tiles.cities reads them. Run it once over every org after deploying that change.

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-list -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-list -- --stage dev --org <orgId> --apply # one Business first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-list -- --stage dev --apply # all orgs

Run on dev 2026-11-25 (after the End User customers and C1 city changes; dry run first, then --apply over all 40 orgs): 2 Business customer entries and 32 personal-org entries written, platform counters active=34 churned=0 noPortal=1 personal=32, 0 failures. The output does not print the city# counts; both Business customers are End User rows, which have no city, so the Crown-wide tiles.cities is expected to be empty on dev. Previous run: 2026-11-12, 19 personal-org entries, platform counters active=19 personal=19, 0 failures.

End User customer backfill (npm run backfill:end-user-customers, 2026-11-25)​

Since 2026-11-25 an End User attached to a Business is one of its customers (End Users are customers). Plants shared before then only carry customerSub, and End Users who joined with their own plants have no profile, so they are missing from the customer list. For every Business (or one --org), this:

  • groups the Business's plants that have a customerSub by End User (one GSI2 Query per Business);
  • for each End User who is still an ACTIVE End User member: creates their customer profile on their personal org (creating and closing that org when they never had one), plus the Crown-wide list entry and platform counters;
  • points each shared plant (not brought in) whose customerOrgId is still the Business at that personal org: META (version + 1), customer link, plantsLive and plant.upserted.v1, in one transaction.

Reruns converge. Query/Get only, no Scan; sequential writes pausing 1 s every 25. Dry run by default; dev only. Not yet run on dev.

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:end-user-customers -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:end-user-customers -- --stage dev --org <businessOrgId> --apply # one Business first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:end-user-customers -- --stage dev --apply # all Businesses

backfill:customer-list knows about these customers: a personal org with an ACTIVE customer profile is written as that Business's row, and a closed End User customer leaves the personal row in place.

Business owner's own plants (npm run backfill:owner-own-plants, 2026-12-01 report F12)​

A person who used the app as an Independent End User and then became a Business owner brought their personal plants into the new Business, but those plants kept the owner's personal org as their customer. That org is CLOSED, and a CLOSED personal org is never listed or counted (owner decision 2026-12-01), so the plant's customer appeared in no customer list or filter (dev: plant "End User Plant", 01M8R5R6ATJZYE87YZQ09DA4DV, in Abdullah Business).

Owner decision 2026-12-02: such plants are the Business's own — customerOrgId is the Business ("no separate customer"). New move-ins do this already (plants/moves.ts, when the joiner holds the BUSINESS role). For plants moved before, a human runs (dry-run first; Query/Get only, no Scan):

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:owner-own-plants -- --stage dev [--org <businessOrgId>]
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:owner-own-plants -- --stage dev --apply
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-list -- --stage dev --apply

Per plant it sets customerOrgId to the Business (conditional on version), deletes the PLANT#<p>/CUSTOMER link and takes one off the personal org's plantsLive. Only plants whose customerSub is an ACTIVE BUSINESS-role member of the operator and whose customer is that member's personal org are touched; End User customers are left alone. Reruns converge.

API custom domain (apiDomainName, 2026-12-02)​

The domain is inv-api.crownsolarenergy.com (owner, 2026-12-02; it replaced api.crownsolarenergy.com, whose certificate and custom domain the next deploy deletes — remove its two old records at the DNS provider). At Cloudflare every record here must be DNS only (grey cloud): API Gateway serves its own certificate, and a proxied record answers an empty 404 from Cloudflare.

cdk.json sets apiDomainName = inv-api.crownsolarenergy.com (dev only — synth refuses it for any other stage). The cse-http-be-dev-api stack then creates an ACM certificate (us-east-1, DNS validation), an API Gateway regional custom domain and a path-less mapping to the HTTP API's default stage, so https://inv-api.crownsolarenergy.com/v1/... is the same API. The deploy also disables the execute-api URL (owner, 2026-12-03: only inv-api may work), so it answers 403 Forbidden — move every client first: web console, mobile app, qa-cross-tenant-dev.sh (API_BASE), and the TCP server's realtime JWKS URL (cse_tcp_be/cdk/cdk.json, /v1/realtime/jwks). Switch-over without an outage: first npm run deploy:dev -- -c keepExecuteApi=true (domain live, old URL still on), move the clients and deploy ws-gateway, then a plain npm run deploy:dev disables the old URL. ACM public certificates and the custom domain cost nothing. DNS is at an external provider (no Route 53 zone), so two records are added by hand:

  1. Run npm run deploy:dev. CloudFormation waits on the certificate (up to ~72 h before it fails).
  2. While it waits, get the validation record — ACM console (us-east-1) → the inv-api.crownsolarenergy.com certificate → "Create records" details, or aws acm list-certificates --region us-east-1 then aws acm describe-certificate --region us-east-1 --certificate-arn <arn> --query "Certificate.DomainValidationOptions[0].ResourceRecord" — and add that CNAME (name _xxxx.inv-api.crownsolarenergy.com → value _yyyy.acm-validations.aws) at the DNS provider. Leave it in place: ACM renews with it.
  3. When the deploy finishes, read the ApiCustomDomainTarget output of cse-http-be-dev-api (d-xxxxxxxxxx.execute-api.us-east-1.amazonaws.com) and add CNAME inv-api.crownsolarenergy.com → that target.
  4. Check: curl -i https://inv-api.crownsolarenergy.com/v1/about answers 401 without a token, and curl -i https://jaqui4ocdf.execute-api.us-east-1.amazonaws.com/v1/about answers 403 — an empty 404 with server: cloudflare means the record is proxied or points at the wrong target.

Removing apiDomainName from cdk.json and deploying deletes the domain and certificate and turns the execute-api URL back on. CORS is unchanged — it governs the console's origin, not the API's hostname.

Names instead of user ids (npm run backfill:display-names, 2026-12-01 report BE-08 / BE-09)​

Older records show a user id where a name belongs: report createdBy.displayName (manual reports before 2026-11-30, e.g. RPT-2026-0007), plant installedBy.displayName (e.g. PL-0125) and work-order createdBy.displayName; older work orders also have no customerName (e.g. WO-2026-0001 on PL-0003). This fills each from the user's profile (else the email's local part) and the operator's customer profile. Dry-run first; Query/BatchGet only, no Scan; every update is conditional, so reruns converge and a newer write is never overwritten:

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:display-names -- --stage dev
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:display-names -- --stage dev --apply
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run rebuild:projections -- --stage dev # report author search

User names to TCP (npm run republish:user-profiles, 2026-12-02)​

user.profile.v1 (see integration bus) is emitted on profile creation and name change. To give cse-tcp-be the names of existing users, after deploying this change and after TCP's consumer (migration 0165) is live, a human runs (dry-run first; pages the identity provider's user list, no table Scan):

TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> AWS_REGION=us-east-1 npm run republish:user-profiles -- --stage dev
TABLE_NAME=cse-http-be-dev-main USER_POOL_ID=<dev user pool id> AWS_REGION=us-east-1 npm run republish:user-profiles -- --stage dev --apply

Crown staff masking backfill (npm run backfill:via-platform, console request §3)​

Since 2026-11-12 records written by Crown staff through platform access carry viaPlatform: true, and readers outside the Crown org see "Crown Support" instead of the person (Role boundaries). This one-off backfill marks records written before that, where they can be matched:

  • Access-log entries with the same requestId or correlationId and the same actor as one of the org's PLATFORM_ACCESS entries.
  • Work-order events with such a requestId (marker on actor.viaPlatform), in orgs where Crown staff used a work-order route.

Not reachable this way, because they store no request id: work-order attachments, plant installedBy and installer history, and anything done before 2026-10-27 (when PLATFORM_ACCESS entries began).

--by-membership (opt-in, 2026-11-12) reaches those by who acted instead: work-order events (actor), attachments (uploadedBy), plant installedBy and installer history (by) whose actor is an ACTIVE member of the Crown org with no membership item in the org that owns the record. Trade-off: a person who was a member of that org at the time, has since been removed and is now Crown staff would also be masked; someone who has left Crown is not caught unless you add --include-former-crown (2026-11-27, needs --by-membership), which also counts SUSPENDED and REMOVED Crown memberships (never INVITED). It reads every org's members, work orders and plants (Query only), so the dry run is slower — read its would mark … (uploadedBy.viaPlatform | installedBy.viaPlatform | by.viaPlatform | actor.viaPlatform) lines first.

How it walks: orgs from the ORGCODE# guards (Query/Get only, no Scan). An org without a PLATFORM_ACCESS entry costs one access-log Query. Writes are conditional on the marker being absent, so a rerun finds nothing to do; they are sequential and pause 1 s every 25. Dry run by default; dev only.

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:via-platform -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:via-platform -- --stage dev --org <orgId> --apply # one org first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:via-platform -- --stage dev --apply # all orgs
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:via-platform -- --stage dev --by-membership # dry run, membership pass too
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:via-platform -- --stage dev --by-membership --include-former-crown # dry run, former Crown staff too

The dry run prints would mark <PK>/<SK> (viaPlatform | actor.viaPlatform) per record and a summary; exit code 1 if anything failed. Run it after the deploy that adds the masking, so newly marked records are masked straight away. Run on dev 2026-11-12 with --by-membership: 19 access-log entries and 2 work-order events marked, 0 failures. Run on dev 2026-11-27 with --by-membership --apply: 1 plant installedBy marked, 0 failures (3 ACTIVE Crown members). A dry run with --include-former-crown the same day (4 ACTIVE or former Crown members) found nothing to mark, so no apply was needed.

Org directory backfill (npm run backfill:org-directory, owner decision Q38)​

Human-run only. Never run by an agent, CI or any Lambda. It writes to the table of the stage you name.

Since 2026-10-27 every org create and rename writes the platform directory keys (GSI2 ORGS#<kind> / <normName(name)>#<orgId>; never for personal orgs). scripts/backfill-org-directory.ts (helpers in packages/core/src/repositories/org-directory-backfill.ts) adds them to orgs created before that. Run it before relying on the ORG_SETTINGS_ALL republish or the weekly reconcile ORGS pass.

  • Dry run by default. Add --apply to write. --stage is required.
  • No Scan. It enumerates orgs through the ORG code counter and code guards.
  • Add-only. Writes are conditional; an org that already has directory keys is left alone.
  • Environment. Operator's own AWS credentials, plus TABLE_NAME, AWS_REGION and ACCOUNT_ID.
npm run backfill:org-directory -- --stage dev # dry run
npm run backfill:org-directory -- --stage dev --apply

Plant re-sync to TCP (npm run resync:plants)​

Human-run only. Never run by an agent, CI or any Lambda. It writes outbox rows to the table of the stage you name. Script: scripts/resync-plants-to-tcp.ts; logic: packages/core/src/plants/resync-to-tcp.ts.

Why. The TCP Server builds its plant_projection only from plant.upserted.v1 bus events. The bus has been off, and outbox rows expire after 7 days, so when the bus is first turned on the TCP Server would not know any schema-v2 plant that was not written in the last 7 days. Business, tag, region and customer grants and filters on the TCP side would miss those plants. See KI-43.

When. Once per stage, right after the first deploy with -c busEnabled=true. The rows reach TCP through the normal outbox → stream-router → SNS FIFO path, which exists only with the bus on.

What it writes. For each v2 plant, the same plant.upserted.v1 outbox row a plant write builds, from the plant's current META and stored tariff, with seq = the plant's current version and correlation id resync-plants-to-tcp/<plantId>. Plant META is never modified (except version, with --bump-version). Each write is a transaction that also checks the META version, lifecycle and operator are unchanged.

  • Emits ACTIVE and ARCHIVED plants, with their real lifecycle in the payload.
  • Skips DELETING plants (TCP has plant.deletion.requested.v1), legacy plants (no org; run migrate:legacy-plants first) and plants changed during the run (their own write already emitted a newer event).
  • No Scan. It walks the org code counter and code guards, then Queries each org's GSI2 plant collection (operator side only), then reads each plant's META and tariff with consistent GetItems.
  • Idempotent. TCP applies an event only when version is newer and dedups by event id, so a rerun is a no-op there; it costs one outbox write per plant. Writes are sequential, pausing 1 s every 25.
  • Flags. --stage <stage> (required); dry run by default; --apply (or --execute) to write; --org <orgId> for one org; --limit <N> to stop after N plants; --bump-version (below). Unknown flags are rejected. Exit code 1 when any plant failed.
  • --bump-version. Because TCP ignores an event at a version it already holds, a plain rerun cannot deliver a field that was added to plant.upserted.v1 after TCP last saw the plant. The cases that need it: plant coordinates (latitude/longitude, added 2026-11-02; without them TCP fetches no irradiance and the console's performance ratio stays null) and city/region (B-3, added 2026-11-19; without them TCP's get_plant_health returns both as null), and a plant tariff cleared on TCP by a write made before 2026-11-23 (until then installer assignment, transfer, customer link/release, moves, unshare, user block/unblock, the RBAC v2 backfill and the legacy migration sent plant.upserted.v1 without tariff, and TCP's projection sets tariff to null when the field is absent; the TCP console's get_plant_overview prices savings with that projected tariff). With this flag the transaction updates META version to version + 1 (same condition; no other attribute changes, not updatedAt) and emits the event at the new version, so TCP applies it. A client holding the old ETag gets one 409/412 and re-reads.
  • Environment. Your own AWS credentials (default SDK chain), TABLE_NAME (required) and AWS_REGION. STAGE is set from --stage and becomes the envelope source cse-http-be/<stage>.
npm run resync:plants -- --stage dev # dry run
npm run resync:plants -- --stage dev --org <orgId> --limit 10 --apply # small first batch
npm run resync:plants -- --stage dev --apply
npm run resync:plants -- --stage dev --bump-version --apply # push fields added since TCP's copy

Last run on dev: 2026-11-25 with --bump-version --apply (to deliver createdAt, added to plant.upserted.v1 that day for console request P9): 40 orgs, 29 plants seen, 29 emitted, 0 skipped, 0 failed. The events were built from the local checkout, so they carry createdAt whether or not the HTTP change was deployed. TCP stores it only if migration 0153_plant_projection_created_at and its new consumer were live when the events arrived; otherwise rerun this once they are. Whether list_plants now returns createdAt for these plants has not been checked yet. Earlier runs: 2026-11-23 (--bump-version, tariffs; 30 orgs, 24 plants, 0 failed), 2026-11-19 (21 plants, 0 failed).

The script needs TABLE_NAME (dev: cse-http-be-dev-main) and AWS_REGION=us-east-1 in the environment, e.g. AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main npm run resync:plants -- --stage dev.

If the stream-router fails to publish some rows, they stay in the outbox for 7 days and npm run replay:outbox can republish them (see Replay, rebuild and redrive).

Org re-publish to TCP (npm run republish:orgs)​

Human-run only. Never run by an agent, CI or any Lambda. It writes outbox rows to the table of the stage you name. Script: scripts/republish-orgs-to-tcp.ts; logic: packages/core/src/orgs/republish-to-tcp.ts (added 2026-11-04, not yet run on any stage).

Why. The TCP Server builds its org_projection only from org.upserted.v1 bus events. It uses that table for the Business, installer and customer names on the web console's Device Inventory and fleet screens. It only ever sees changes, so an org last written before TCP started consuming the event, or more than 7 days before the bus was turned on (outbox TTL), has no name on the TCP side.

When. Once per stage, after the bus is deployed with -c busEnabled=true and TCP's org_projection consumer is live. Run it again any time TCP's projection needs rebuilding. It is safe to rerun.

What it writes. For every org of every kind (PLATFORM, OPERATOR, PARTNER, CUSTOMER, personal orgs included), the same org.upserted.v1 outbox row an org write builds, from the org's current META:

  • seq and data.version are the org's current version;
  • subject (FIFO group) is org/<orgId>;
  • the correlation id is republish-orgs-to-tcp/<orgId>;
  • data is exactly the schema fields (orgId, kind, personal, name, timezone, currency?, status, version, per docs/events/org.upserted.v1.schema.json).

Org META is never modified. Each write is a transaction that also checks the META version is unchanged.

  • Skips orgs whose META vanished (gone) and orgs changed during the run (changed: their own write already emitted a newer event).
  • Fails, without sending, an org whose META can't satisfy the event schema (no integer version, no timezone, or an unknown kind/status). It is listed with the reason, and the exit code is 1.
  • No Scan. It reads the ORG code counter PLATFORM/SEQ#ORG#ALL, BatchGets the ORGCODE#ORG-NNNN/GUARD items, then does a consistent GetItem of each ORG#<o>/META. Every org takes an ORG- code when it is created, memberless customer orgs included.
  • Idempotent. TCP keeps the row with the newest max(seq, version) and ignores redeliveries, so a rerun is a no-op there; it costs one outbox write per org. Writes are sequential, pausing 1 s every 25.
  • Flags. --stage <stage> (required); dry run by default; --apply (or --execute) to write; --org <orgId> for one org; --limit <N> to stop after N orgs. Unknown flags are rejected.
  • Environment. Your own AWS credentials (default SDK chain), TABLE_NAME (required) and AWS_REGION. STAGE is set from --stage and becomes the envelope source cse-http-be/<stage>.
npm run republish:orgs -- --stage dev # dry run, with counts by kind
npm run republish:orgs -- --stage dev --org <orgId> --apply # one org first
npm run republish:orgs -- --stage dev --apply

Plant reconcile to TCP (npm run republish:plants)​

Added 2026-11-30 (web-console Analytics, FO-3). The event bus reached TCP on dev on 2026-11-19, so plants archived or deleted on HTTP before then can still read active in TCP's plant projection and count in fleet totals. This script resends each plant's current HTTP state. It is human-run only, dry run by default, and never modifies a plant (it writes outbox rows only; Get/Query, no Scan).

Input: a file with one plant id per line, optionally followed by the version TCP holds (plantId,tcpVersion). The list comes from TCP (plants its projection holds as active).

HTTP stateEvent sent
ACTIVEplant.upserted.v1 at the current version (also refreshes capacity)
ARCHIVEDplant.archived.v1 at the current version
DELETINGplant.deletion.requested.v1
Gone (hard-deleted)plant.archived.v1 at tcpVersion + 1; skipped without a TCP version. Never a deletion: on TCP a deletion erases the history of every device still bound
TABLE_NAME=cse-http-be-dev-main npm run republish:plants -- --stage dev --ids tcp-active-plants.txt # dry run
TABLE_NAME=cse-http-be-dev-main npm run republish:plants -- --stage dev --ids tcp-active-plants.txt --apply # write

Rerunning is safe: TCP applies upsert/archive only when the version is newer and dedups by event id.

Customer status re-publish to TCP (npm run republish:customer-status)​

Bug fix 2026-12-02. TCP's console "Needing attention" count (get_plant_health counts.attention) leaves out CHURNED customers and suspended End Users. It learns both only from customer.status.v1 (integration bus), which write paths emit from this change on. This emits one per existing Crown-wide customer list entry (Query on the CUSTOMERS#ALL#<status>#<shard> partitions, no Scan; sequential, 1 s pause every 25). Idempotent: TCP keeps the newest seq. Human-run only.

Order: deploy this change (npm run deploy:dev), then cse_tcp_be applies its migration 0161_customer_status_projection and deploys its consumer, then:

AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main npm run republish:customer-status -- --stage dev # dry run: counts, churned, suspended
AWS_REGION=us-east-1 TABLE_NAME=cse-http-be-dev-main npm run republish:customer-status -- --stage dev --apply

Exit code 1 when any customer failed (rerun; it converges). Not yet run on dev.

Tag re-publish to TCP (npm run republish:tags)​

Human-run only. Never run by an agent, CI or any Lambda. It writes outbox rows to the table of the stage you name. Script: scripts/republish-tags-to-tcp.ts; logic: packages/core/src/tags/republish-to-tcp.ts (added 2026-11-27, not yet run on any stage).

Why. The TCP Server shows tag labels in the console Plants list from its tag_projection, built only from tag.upserted.v1 / tag.deleted.v1 (first emitted 2026-11-27). Tags written before then have no label there. This re-emits tag.upserted.v1 for every ACTIVE tag of every org at its current version (DELETING tags are skipped; tags are never modified). Query/Get only, no Scan; a tag edited mid-run is skipped (changed) because its own write emitted a newer event. Idempotent on TCP's side. Run it after the deploy that adds the tag events.

npm run republish:tags -- --stage dev # dry run
npm run republish:tags -- --stage dev --org <orgId> --apply # one org first
npm run republish:tags -- --stage dev --apply

Device Inventory backfill order (web console, 2026-11-04)​

The TCP Server serves the web console's Device Inventory. Its names, Business scope and plant picker come only from this server's plant.upserted.v1 and org.upserted.v1 events. To make every existing plant and org visible there, a human runs these once per stage, in this order, after deploying with -c busEnabled=true. Every step is idempotent and dry-run by default.

  1. npm run migrate:legacy-plants converts plants the app created before mobile create wrote schema v2 (committed 2026-11-03, not yet deployed). For each plant it writes the per-Business list keys, the platform-wide list entry and a plant.upserted.v1. Read its staging/prod precondition in KI-39 first.
  2. npm run rebuild:projections -- --all-orgs --execute adds the ADR 0016 platform-wide list entry to v2 plants written before that change, mobile plants included.
  3. npm run resync:plants re-emits plant.upserted.v1 for every v2 plant, so TCP's plant_projection holds plants written more than 7 days earlier.
  4. npm run republish:orgs re-emits org.upserted.v1 for every org.

New writes need no backfill. Since 2026-11-03, mobile POST /v1/plants writes the per-Business list keys, the platform-wide list entry and plant.upserted.v1 in its create transaction, and it creates the personal org (with its own org.upserted.v1) when needed.

Work-order lifecycle v2 backfill (npm run backfill:wo-lifecycle-v2, ADR 0023)​

Human-run only, dev only. Never run by an agent, CI or any Lambda. It writes to the table. The script refuses any stage other than dev and any TABLE_NAME other than cse-http-be-dev-main (Hard Rule 4). It has not been run yet.

ADR 0023 (work-order lifecycle v2) is built but not deployed. scripts/backfill-wo-lifecycle-v2.ts (logic in packages/core/src/service/wo-lifecycle-backfill.ts) migrates orders written before it. Run it once, after the deploy that ships ADR 0023. Until then the API reads older orders in v2 terms on the fly, so nothing breaks, but some lists and counts stay incomplete (orders stored before v2).

For each org it reads every work order from the org's open and closed queues (GSI2; no Scan). Orgs come from the ORG code counter and code guards, or from --org. Per order:

  1. Status v2. It applies these rewrites to META and the plant link, at the same version (conditioned on it; ETags do not change). It writes no event.
    • ASSIGNED + acceptance → ACCEPTED.
    • COMPLETED + businessClosure → CLOSED.
    • COMPLETED without closure stays COMPLETED, but closedAt is removed, so it moves back into the open queue (awaiting verification).
    • NEW + lastDecline with no technician → REJECTED.
    • Hold reasons PART / APPROVAL / SITE_ACCESS are renamed.
    • assignedAt is set from the latest ASSIGNED / REASSIGNED event (or updatedAt).
  2. List entry. It writes the WO#<w>/LISTALL entry that the Crown-wide list and the createdAt sorts read. This is an idempotent Put, written for every order.
  3. With --counters. It rebuilds the org's COUNT#WO#TOTAL, COUNT#WO#OPEN, open facets, COUNT#WOSTATUS#<status>, COUNT#WOCUST#OPEN#<c> and the PLANT#<p>/COUNT#WO#OPEN of every plant that has an order, as absolute values from the orders read. Org counters it did not compute are reset to 0 (tech-day counters are left alone). It also writes every order's search tokens. The Crown-wide ORG#ALL counters are rebuilt only when every org is walked (no --org).

Not handled.

  • The COUNT#WOHIST#<day> rollups, so E12 tiles from them stay approximate.
  • Tech-day counters, and the per-plant open count of a plant that no longer has any order.
  • A COMPLETED order moved back to the open queue does not re-acquire its alert's open guard.

Counter writes are absolute Puts, so an order write that lands mid-run can be overwritten; run it when the console is quiet, and rerun --counters if in doubt.

  • Dry run by default. It prints each status change and the counter item counts. Add --apply to write.
  • Flags. --stage dev (the default; anything else is refused); --apply; --counters; --org <ULID> (repeatable; skips the Crown-wide counters). Unknown flags are rejected.
  • Exit codes. 2 when no org was walked ("that does NOT mean there is nothing to fix"); 1 on an error.
  • Safe to rerun. Status rewrites are conditioned on the version, list entries and counters are absolute Puts, search tokens are idempotent Puts.
  • Environment. Your own AWS credentials (default SDK chain). TABLE_NAME defaults to cse-http-be-dev-main and AWS_REGION to us-east-1.
npm run backfill:wo-lifecycle-v2 # dry run, every org
npm run backfill:wo-lifecycle-v2 -- --org <orgId> --apply # one org first (no Crown-wide counters)
npm run backfill:wo-lifecycle-v2 -- --apply --counters # every org, statuses + entries + counters + tokens

Since ADR 0023 D10, new work-order writes update the counters and search tokens on the request path (KI-43), so the backfill is needed once, for orders written before the deploy.

Customer plant-name backfill (npm run backfill:customer-plant-names, console 4.4)​

Human-run only. Writes the plantNames map ({plantId: name}) on every Business customer profile (ORG#<op>/REL#CUSTOMER#<c>) from the Business's plant records, so GET /v1/orgs/{orgId}/customers?q= matches plant names. Absolute values, safe to rerun. Query/Get only, no Scan; writes are sequential with a 1 s pause every 25. Dry run by default. Afterwards run npm run rebuild:projections so the customer search tokens pick the names up (the stream-router that would do it is not deployed, KI-43).

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-plant-names -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-plant-names -- --stage dev --org <orgId> --apply # one Business first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:customer-plant-names -- --stage dev --apply # all

Work-order console indexes (npm run backfill:wo-console-indexes, ADR 0030)​

Human-run only. For orders written before 2026-11-24 it writes the five column-sort entries per order (WO#<w>/SORT#<field>, E01 sort=planned|priority|status|plant|technician) and sets each technician's history counter (ORG#<o>/COUNT#WOHISTTECH#<sub>, E12b) to an absolute total. New writes keep both current on the request path. Query only, no Scan; sort-entry writes are version-guarded (never overwrite a newer one). Run in a quiet window: an order closed while the technician totals are being set can be lost until the next rerun. Dry run by default. Exit code 1 on any failure.

TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:wo-console-indexes -- --stage dev # dry run
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:wo-console-indexes -- --stage dev --org <orgId> --apply # one Business first
TABLE_NAME=cse-http-be-dev-main AWS_REGION=us-east-1 npm run backfill:wo-console-indexes -- --stage dev --apply # all

Since 2026-11-25 each order has eight sort entries (device, cost and due added) and each entry also carries the Crown-wide copy (GSI2 WO#ALL#WOSORT#<field>), so rerun it once after that change.

Run on dev 2026-11-25 (dry run, then --apply): 40 orgs, 4 orders, 32 sort entries written, 0 technician counters (no order had a technician), 0 failures.

Audit wave 1 operational notes (2026-10-27)​

  • Per-stage context: set non-secret per-stage values in cdk.json context.stages.<stage> instead of retyping -c flags. The key list and precedence are in Infrastructure.
  • Alarms and metrics deploy and emit only in prod by default. Override with -c alarmsEnabled=true|false / -c metricsEnabled=true|false. In dev, look for msg:"metric" log lines instead of CloudWatch metrics.
  • Scripts accept both --apply and --execute.
  • Log redaction (packages/core/src/observability/logger.ts): a field is replaced with [REDACTED], at any depth up to 6, when its name contains authorization, password, passwd, token, email, phone, secret, cookie or ticket. It is also redacted when the name has a whole word body, otp, totp, jti, ip, refresh, pin or cvv, or is code with a secret qualifier (otpCode, verificationCode and so on). A bare code, errorCode, statusCode or plantCode is kept. Deeper nesting becomes [TRUNCATED].

Debugging​

  • A route returns 401 with body {"message":"Unauthorized"}: the gateway authorizer rejected the token before any Lambda ran. Check that the token is (a) not expired (1 h), (b) issued by pool us-east-1_L8woOafje, and (c) issued to flutter-app-default, flutter-app-remembered, or — dev only — server-admin. The authorizerError field in the access log says why.
  • A route returns 401 with the UNAUTHENTICATED envelope: the request reached a handler without authorizer claims, so that route was deployed without the authorizer. Fix lib/api-stack.ts immediately: until then, that route is open to the internet, and only requireClaims() stands in the way.
  • A handler returns 200 but the body is an error object: almost certainly a return { ... } that bypassed respond.ts's ok()/fail() helpers. Payload format 2.0 turns any return value without statusCode into a successful 200.
  • A 500 INTERNAL: find the matching unhandled_error line (same time window, same function) for the real exception, and check the known triggers first: KI-7, KI-8.
  • A gateway 5xx with {"message": ...}: no envelope means the handler never returned. Look for a Lambda timeout (10 s), an init/bundling error (MODULE_NOT_FOUND), or a throttle (the LambdaThrottles alarm; the account quota is 1000, shared with TCP ingest).

Service / O&M plan worker and attachments (feature 006)​

:::warning Applies once deployed The -service stack (plan-cycles queue/DLQ, plan-tick schedule, plan-worker; its DLQ has no alarm — check by hand) is built in code but not deployed, and exists only with -c busEnabled=true; the hourly tick is DISABLED unless -c servicePlansEnabled=true. Without busEnabled, :run-now answers 503 DEPENDENCY_UNAVAILABLE (infrastructure). This runbook describes how they are meant to be operated once they exist. Mutating steps are human operator actions (through CDK where possible — no console changes); agents never run them. :::

Plan-worker logs (structured JSON, read-only). Log events to search for: plan_tick (due, dispatched, skipped), plan_run_stopped (reason), plan_tick_not_dispatchable, plan_order_invalid, plan_order_create_failed (code), plan_runner_queue_unconfigured (the PLAN_CYCLES_QUEUE_URL env var is missing — runner no-ops), plan_worker_message_invalid (poison message, goes to the DLQ), plan_worker_message_failed. Example (read-only):

aws logs tail /aws/lambda/<plan-worker-function-name> --since 1h --filter-pattern plan_ --region us-east-1

DLQ redrive. A failed PLAN_CYCLE/TICK is retried by SQS and parks in the DLQ after 5 receives (no alarm fires — check DLQs by hand). Retries are safe: each plant's order is guarded by its cycle key, so a redriven page creates nothing twice (only run counters may double-count). Fix the cause first (logs above), then an operator redrives the DLQ back to plan-cycles (SQS "start message move task"). A poison (unparseable) message will just fail again — inspect it and discard it instead.

Pausing the schedule. Globally: set SERVICE_PLANS_ENABLED off and redeploy the -service stack — the plan-tick schedule is disabled and no new cycles start. One plan: POST …/maintenance-plans/{planId}:pause (MANAGE); an in-flight run then stops at its next page (plan_run_stopped).

Attachments troubleshooting.

SymptomCause / fix
503 DEPENDENCY_UNAVAILABLE on every E09 callSERVICE_FILES_BUCKET unset (bucket not deployed) or S3 unavailable
409 INVALID_STATE OBJECT_MISSING on :confirmclient never finished the presigned PUT (or it expired after 15 min) — create a new attachment
422 VALIDATION_FAILED with details.reason SIZE_MISMATCH / TYPE_MISMATCH (and details.field sizeBytes / contentType) on :confirmuploaded bytes differ from the declared sizeBytes/contentType; the object was deleted — start again with exact headers
Browser PUT blocked by CORSorigin missing from the webOrigins context of the bucket CORS rule
Download link failspresigned GET expires after ≤ 5 min — fetch E09 GET again
Pending uploads accumulateexpected; the pending/ lifecycle rule removes them after 1 day

Presigned URLs are never logged.

Troubleshooting / common failure scenarios​

  • Intermittent 503 DEPENDENCY_UNAVAILABLE (KI-38): an AWS SDK call was throttled or unavailable (packages/api/src/http/respond.ts). The handler logs a WARN whose message field is msg = dependency_unavailable with a dependency field. In CloudWatch Logs Insights, over the API function log groups:

    fields @timestamp, dependency, requestId
    | filter msg = "dependency_unavailable"
    | stats count() by dependency

    Lambda throttling is unlikely to be the cause on its own: the account Lambda concurrency quota is 1000 (not 10), shared with the live cse-tcp-be ingest functions.

  • MFA re-check failures (B-4) (cannot occur since 2026-11-11 — no MFA requirement forms): when the live Cognito MFA re-check in packages/api/src/http/context.ts fails, the API logs WARN mfa_recheck_failed (field error = the error name). Under MFA_ENFORCEMENT=on with a stale cached value the request answers 503 DEPENDENCY_UNAVAILABLE + Retry-After: 1 (fails closed); under warn it uses the cached value. A cached false is reused for 5 minutes before Cognito is asked again. Find the failures:

    fields @timestamp, error, requestId
    | filter msg = "mfa_recheck_failed"

    To check that the old 500s on the notification-settings route have stopped:

    fields @timestamp,name,error | filter msg="unhandled_error" and routeKey="GET /v1/orgs/{orgId}/notification-settings"
  • Emails not arriving (KI-37): SES is in sandbox (DKIM + sandbox exit pending), so password-reset and report emails (invitations are in-app only, never emailed) reach only SES-verified recipients.

  • Requests to a route succeed without a token: a newly added HTTP API v2 route defaults to open. Every entry in lib/api-stack.ts's routes array must pass the shared authorizer to addRoutes.

  • AccessDenied on a GSI query while base-table reads work: the function's IAM policy doesn't cover table/<name>/index/*. Use grantReadData/grantReadWriteData in ApiStack, which include it, rather than hand-written statements.

  • Deploy fails with a Lambda concurrency error: something set reservedConcurrentExecutions. Reservations need the owner's approval; the account quota (1000) is shared with the live TCP Server. Remove it.

  • Users don't receive sign-up / password-reset emails: Cognito's built-in sender is capped at roughly 50 emails/day. That's expected until Cognito is moved to SES. Don't switch Cognito to SES while SES is still sandboxed. Every sign-up to an unverified address would then fail to deliver, leaving the account stuck UNCONFIRMED with no retry path. Complete DKIM verification and sandbox exit first.

  • An email sign-in code never arrives: expected for retry rounds 2 and 3 of the same session — only round 1 sends an email, and rounds 2/3 reuse its code (see Authentication). Otherwise check CreateAuthChallengeFn's logs: email_signin_sender_not_configured (deployed without -c otpSenderEmail), email_signin_unverified_address (the account's email is not verified), email_signin_throttled (a code went out under 60 s ago), email_signin_send_failed (SES refused — in the SES sandbox the recipient must be a verified address), or email_signin_code_issued (sent). No line at all means Cognito treated the email as an unknown user. See KI-6.

  • A device claim returns 500 instead of 409: re-claiming a serial already on the same plant (KI-8).

  • The alert email never arrives: confirm the SNS subscription (aws sns list-subscriptions-by-topic); a pending one delivers nothing. The two Lambda alarms are account-wide, so they can also fire for TCP Server functions.

  • plant_after_deleting_hook_failed in a plants function's logs / PlantDeviceReleaseFailed metric > 0: on an owner (mobile) plant delete, the plant META transaction committed but the second device release failed. Find it in CloudWatch Logs Insights: fields @timestamp, plantId, error, reason | filter message = "plant_after_deleting_hook_failed" | sort @timestamp desc. The handler then skips the final sweep and deliberately leaves the plant's serial bindings in place so the release can be re-run for that plantId; until it is, those serials stay bound to the deleted plant and cannot be claimed elsewhere. Manual remedy today: re-run unbindAllBindingsForPlant(plantId) (packages/core/src/plants/device-bindings.ts) — this needs a code-level invocation by a developer; there is no operator command, script or alarm for it yet.

Configuration changes​

Stage-specific behavior comes entirely from the stage CDK context value and the prod checks in the stack code (isProd / props.stage === 'prod'): log group removal policy, X-Ray tracing, LOG_LEVEL, table PITR, and table/pool deletion protection. There's no per-stage config file.

Docs sync hook​

cse-http-be ships scripts/git-hooks/pre-commit. It warns (never blocks) when a commit touches routes, handlers, schemas, keys, repositories, CDK stacks, docs/openapi.yaml, docs/data-model.md or docs/cost-model.md, while ../cse-solar-docs/http-docs/** has neither an uncommitted change nor a commit in the last 24 h. Install it once per clone:

cp scripts/git-hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit

Capturing real execution results​

Every request/response example in the API reference is currently illustrative, derived from the code. To replace one with a real trace:

  1. Get a mobile-client ID token (see Minting a test JWT; server-admin tokens are rejected).
  2. curl the endpoint against dev. Redact the Authorization header and any real userId, email, or phone number before pasting.
  3. Replace the "— illustrative example" heading with "— captured <date> against dev", and keep the payload as close to literal as possible.

Only replace an example once it has actually been run. Don't backfill from memory.

Device operations (feature 007) — removed​

Removed (ADR 0012). The 007 routes, the api-devices-ops stack and its command-sweep, the bulk-task-driver, the firmware and engineering-files buckets, the command.* events and the commandsDispatchEnabled / firmwareTasksEnabled context flags are gone from code. There is nothing to operate here; devices and commands are served by the TCP server.

Notifications (routed)​

The 008 routes are routed — the area stacks are created by a default cdk synth (no -c flags); the web team observed these routes answering on dev on 2026-10-28 (stack cse-http-be-<stage>-api-notify). The NotifyStack (cse-http-be-<stage>-notify: recompute/reconcile and digest workers) is built but exists only when synthesized with -c busEnabled=true. The owner deploys it explicitly, never with --all:

npx cdk diff cse-http-be-dev-notify -c stage=dev -c busEnabled=true
npx cdk deploy cse-http-be-dev-notify -c stage=dev -c busEnabled=true

Optional context keys (leave unset while SES is in sandbox): -c notifyEmailFrom=<verified sender> sets NOTIFY_EMAIL_FROM and grants ses:SendEmail; -c notifySesConfigurationSet=<name> sets NOTIFY_SES_CONFIGURATION_SET.

  • Watching the queues: the notify-recompute DLQ has no alarm (check by hand); its oldest message (> 900 s) part of …-BacklogAge, and …-NotifyReconcileStale (no completed reconcile in a 7-day period; silent if the function never logs at all) go to the alerts topic. To look by hand: aws sqs get-queue-attributes --queue-url <url> --attribute-names ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible (queue URLs are the stack outputs NotifyRecomputeQueueUrl and DigestJobsQueueUrl). The digest DLQ has no alarm.

  • Channel availability flags: set SSM /cse-http-be/<stage>/notify/email-enabled to true to mark EMAIL available; PUSH reads TCP's /cse-tcp-be/<stage>/notify/push-enabled. Unset means unavailable. Do not enable email while SES is in sandbox.

  • DLQ redrive: after fixing the cause, redrive cse-http-be-<stage>-notify-recompute-dlq or …-digest-jobs-dlq with the SQS console-free CLI aws sqs start-message-move-task --source-arn <dlq-arn>.

  • Running a reconciliation: the weekly schedule cse-http-be-<stage>-notify-reconcile-start (Sunday and Wednesday 21:00 UTC) sends a RECONCILE_PAGE message to the recompute queue; a manual run sends {"kind":"RECONCILE_PAGE"} (optional generation, reason ≤ 64 chars; NotifyRecomputeRequest). With no generation it starts or resumes the current run; a message for an older generation is dropped.

  • Logs: npm run logs -- notify-recompute (reconcile pages log here too; a finished walk logs notify_reconcile_completed) and npm run logs -- digest, once the stack is deployed.

Reports (feature 009)​

The report routes are routed — the area stacks are created by a default cdk synth (no -c flags); the web team observed these routes answering on dev on 2026-10-28 (stack cse-http-be-<stage>-api-reports). Generating needs ReportsStack (-c busEnabled=true) and -c reportsGenerateEnabled=true; without them generation answers 503/422. Deploy order (human only, all with -c busEnabled=true):

  1. npx cdk deploy cse-http-be-<stage>-data cse-http-be-<stage>-observability -c stage=<stage> -c busEnabled=true (reports bucket, no expiry notification yet).
  2. npx cdk deploy cse-http-be-<stage>-reports cse-http-be-<stage>-integration -c stage=<stage> -c busEnabled=true (add -c reportsGenerateEnabled=true to let scheduled runs generate reports). Copy the ReportDispatchQueueArn stack output.
  3. Second data-stack deploy: npx cdk deploy cse-http-be-<stage>-data -c stage=<stage> -c busEnabled=true -c reportDispatchQueueArn=<ReportDispatchQueueArn output>. This adds the s3:LifecycleExpiration:Delete notification. S3 validates the queue on deploy, so step 3 fails if step 2 has not run. Keep passing -c reportDispatchQueueArn on every later data-stack deploy — leaving it out removes the notification (reads still compute EXPIRED).

Dev (since 2026-11-04): cdk.json context.stages.dev sets reportDispatchQueueArn (arn:aws:sqs:us-east-1:574317420690:cse-http-be-dev-report-dispatch), reportsGenerateEnabled: true, reportDispatchPerMinute: 10 and tcpRendererRoleArn, so a plain npm run deploy:dev keeps all four and no -c flag is needed. Before that, a plain dev deploy set REPORTS_GENERATE_ENABLED=false (generation returned 422 REPORTS_GENERATE_DISABLED) and left the expiry notification and the renderer bucket grant off.

Without step 2 the stream router skips dispatch (WARN) and schedules are stored but not armed.

Logs: npm run logs -- report-dispatcher, report-schedule-runner, report-sweeper. Alarms: the report DLQs have no alarm (check by hand; redrive the DLQ to its source queue after fixing the cause) and ReportsOverdue (the sweeper is failing or late — check its log for report_sweeper_overdue and errors).

Tuning dispatch pacing. Set reportDispatchPerMinute in cdk.json stages.<stage> or add -c reportDispatchPerMinute=<n> to the cse-http-be-<stage>-reports deploy (default 30, 0 turns pacing off; dev uses 10). Lower it if the TCP renderer is overloaded; deferred reports wait in the queue (never the DLQ) and their deadlines move with them. The code also supports optional report retention floors (REPORT_RETENTION_DAILY_DAYS / REPORT_RETENTION_ALERT_DAYS), but no stage sets them, and enabling one needs a CDK change. Never set them by editing a Lambda in the console.

Once deployed: stuck QUEUED/RENDERING reports are failed by the sweeper (users then Regenerate); report-dispatch DLQ messages are replayed by redriving the DLQ to the source queue; audit log lines are report_created, report_regenerated, report_deleted, report_download, schedule_created, schedule_updated, schedule_deleted, schedule_paused, schedule_resumed, schedule_run_now and schedule_run (ids, kinds and counts only — never bodies, names, recipients or signed URLs). See Reports pipeline.

Account settings (feature 010) — routed​

Routes live in cse-http-be-<stage>-api-account; routed — the area stacks are created by a default cdk synth (no -c flags); the web team observed these routes answering on dev on 2026-10-28. No execution below has been captured.

Log event names (structured JSON, no request bodies, no phone numbers, no IPs): profile_updated, profile_name_sync_failed, settings_idp_unavailable, mfa_disabled, mfa_disabled_out_of_band, mfa_snapshot_refresh_failed, mfa_disable_audit_failed, mfa_reconcile_failed, mfa_reconcile_slow, password_change_reported, sessions_ended_all (now with pointersEnded), and since 2026-11-12 (not deployed) sessions_ended_others {ended}, session_ended_individually, session_signed_out, session_touch_failed, session_geoip_failed, session_end_all_pointer(s)_failed, session_end_others_audit_failed. sign_in_recorded / sign_in_record_failed come from the Cognito PostAuthentication trigger (PostAuthenticationFn, wired in lib/auth-stack.ts, T010-061 / Q41), logged once per sign-in.

Inspecting a user's sign-in records safely. Use the product route first: the user calls GET /v1/me/sessions themselves. If an operator must look at the table, use a key-bounded read-only Query (never Scan): PK = USER#<sub> and begins_with(SK, "SESSION#"). Records (and their SESSIONJTI# pointers) expire by TTL one day after their refresh token (issue #29, 2026-11-12, not deployed; was 90 days), and the API stops listing them the moment the refresh token expires. Rows written before the change keep their 90-day TTL (hidden from lists once expired); a still-live one gets the new TTL when its sign-in next updates lastActiveAt. They hold the parsed device label and class (never the raw user agent) and, since 2026-11-12 (not deployed), the user's public IP as forwarded by the web console (ipAddress) and a city/country when one is resolved. SESSIONJTI#<origin_jti> items are the per-sign-in pointers (endedAt = ended); GEOIP#<ip> items are the location cache. Treat IPs as personal data: do not copy them into tickets or chat. Any database or console access follows the read-only rule in CLAUDE.md.

No SMS. Phone OTP and phone change were removed (owner decision OQ-09); this product sends no SMS, and the phoneChangeSmsEnabled context flag no longer exists.

Web console additions (N-37 … N-51) — owner actions​

Nothing on this page is deployed. Owner actions:

  1. Deploy with npm run deploy:dev. This deploys --all, including the new cse-http-be-<stage>-api-reports-settings stack (brand assets) and the existing area stacks (-api-service for work-order drafts, -api-account for layouts and session end, and -api-notify for notification settings). Run npm run diff first.

  2. Set the optional CDK context you want, then synth and deploy. Every key is non-secret, and an unset key just omits the field:

    KeyEffect
    reportSamplesBaseUrlhttps base URL. Adds samplePreviewUrl to report templates (REPORT_SAMPLES_BASE_URL)
    shareLinkBaseUrlThe web console's public https origin, with no path. Makes plant share-link urls (/share/<token>) and report links absolute (SHARE_LINK_BASE_URL on every API function). Also sets INVITE_LINK_BASE to <origin>/accept-invite on the invitations function, which is what makes invitation acceptUrl appear outside prod. Unset, links are relative and invitations return no acceptUrl. Saved for dev in cdk.json context.stages.dev as https://cse-admin-web.vercel.app (applies from the next dev deploy)
    aboutBuildCommitSets GET /v1/about build.commit (git hash)
    aboutBuiltAtSets build.builtAt (ISO-8601)
    supportEmail, supportUrlSet support.*
    privacyUrl, termsUrlSet legal.* (https)

    For example: npx cdk deploy --all -c stage=dev -c supportUrl=https://<your-support-site>.

  3. Platform status banner: an operator writes the PLATFORM/STATUS item (state, optional message, updatedAt) out of band. Agents never write to the table.

Customer counter backfill (N-46)​

Run this once after the N-46 projector is deployed. Until it has run, the customer overview and list counts miss older plants and open work orders. Owner-run only. There is no npm script.

TABLE_NAME=<table> AWS_REGION=us-east-1 npx tsx scripts/backfill-customer-counters.ts --stage dev # dry run (default)
TABLE_NAME=<table> AWS_REGION=us-east-1 npx tsx scripts/backfill-customer-counters.ts --stage dev --apply # write

It uses Query only, never Scan. It writes absolute values to COUNT#plants#customer#<c> and COUNT#WOCUST#OPEN#<c>, and zeroes stale counters. Its writes race the stream's ADDs, so run it in a quiet window. A rerun is idempotent. Credentials come from your environment.

Counters change only through the stream-router, which does not run while busEnabled is off (every stage today, see KI-43). Run the backfill after the bus is turned on; run before that, the counters drift again with the next writes.