Cogneris
Environmental Compliance & Inspection

Intent · Every environmental obligation current and evidenced — zero reportable exceedances at Woodbine (UTS).

Operating tolerance: issues closed in ≤ 5 days · no repeat findings · every permit condition met.

← Documentsdocs/AUDIT-submissions-2026-08-04.md4,956 words

Submissions audit — mobile app and console

  • Date: 2026-08-04
  • Branch: feat/rn-app-parity
  • Method: independent read-only audit by OpenAI Codex (codex exec --sandbox read-only, 132k tokens), then every load-bearing claim re-verified against the source by Claude Code (session 22f75e25).
  • Scope: the submissions path end-to-end — compose → local persist → enqueue → transmit → server accept → console display — across apps/esg-field/ (React Native) and app/ (Next.js console).
  • NOT VERIFIED: nothing was run. No live D1 inspection, no endpoint probe, no test execution, no on-device check. Every claim below is a source claim.

Findings are re-ranked from codex's severities after verification. Two of its claims were overstated and one was wrong; those are marked and corrected rather than dropped.


⚠ RE-VERIFICATION — 2026-08-05, and it changes the answer

Claude Opus 5 (Claude Code, session 22f75e25). This time things were executed: both test suites were run, the deployed console was probed over the network, and production D1 contents were read back. Two findings emerged that the 2026-08-04 audit could not have seen.

1 · The source moved under the audit

apps/esg-field/lib/ncr/{submit,delivery,api}.ts, screens/SubmissionsTab.tsx, screens/ncr/useNcrLog.ts, app/lib/ncrStore.ts, app/lib/db.ts and app/api/ncrs/route.ts were all modified between 00:32 and 07:15 on 2026-08-05 — after the audit ran. The working tree is now 54 files / +6,550 / −2,133 ahead of HEAD (8ef6618, 2026-08-01), and app/lib/deviceAuth.ts plus apps/esg-field/lib/ncr/__tests__/delivery.test.ts are new and untracked. Another session has been fixing this path. Line numbers in the body of this audit refer to the pre-edit source and no longer resolve; the findings themselves were re-checked one by one and their current status is below.

2 · Status of every finding, re-checked against the working tree

#FindingStatus on 2026-08-05
S1Retry overwrote the record and restamped received_atFIXED in tree. Both backends now INSERT OR IGNORE; received_at is explicitly preserved and put() gained a conflict flag that detects a replay whose body differs (ncrStore.ts:48-56,198-232, db.ts:549-561).
S2Post-raise sweep read a stale pre-append snapshotFIXED in tree. useNcrLog now reads through a ref — readAll: () => [...current()] (useNcrLog.ts:86-94) — so the sweep sees the ticket that triggered it.
S3No authentication on either endpointFIXED in tree, STILL LIVE IN PRODUCTION. See §3 — this is now the only finding that is exploitable right now.
S4A permanent rejection retried foreverFIXED in tree. SubmitOutcome gained unauthorized; the receipts file became a DeliveryLedger with a rejections side, so a refusal is terminal instead of reading "sending" for ever.
S5Inspection outbox had no receiver; failures invisibleLARGELY FIXED in tree. /api/submissions now has a POST handler (route.ts:123) behind the same device auth; app/lib/db.ts gained a delivered_inspections table with a server receipt id; SignoffSheet now queues a real folded submission and its catch names reconcileOutbox as the recovery that queues any signed inspection with no row; TaskFlow reads submissionStateOf(sync.items, inspectionId) instead of the hardcoded {kind:"queued"} literal.
S6Register and scores fed fixturesSTILL TRUE. app/lib/analytics.ts:63,122,144,169,186 still default to NCR_SUBMISSIONS. An arrived ticket still moves no figure.
S7Receipts written non-atomicallyFIXED in tree. The ledger writes via a temp file (delivery.ts:165 comments the TMP read path).
S8a{kind:"confirm"} implemented and never setSTILL TRUE — the type is declared at CaptureFlow.tsx:48 and nothing sets it.
S8bsubmitFinding/submitSummary/sealInspection/fetchOpenInspection deadSTILL TRUE — repo-wide grep finds no caller outside api.ts/index.ts.
S8cTwo portal-resolution policiesFIXED in tree. api.ts:50-51 now delegates to portalBaseUrl(), and the code comment names the old split as the bug.

3 · The one finding that is live right now: production is unauthenticated

Probed 2026-08-05 from this machine, no credential of any kind:

GET  https://esg.cogneris.com/api/submissions  → 200  application/json  2,623 b
GET  https://esg.cogneris.com/api/ncrs         → 200  application/json  3,076 b   {"receiver":"d1"}
POST https://esg.cogneris.com/api/ncrs  {}     → 400  {"error":"Missing required field(s): …"}

esg-web.sequents.workers.dev answers identically. The 400 is the point: the request reached the route and was refused by field validation, not by authentication.

Re-confirmed at 08:44 EDT with the decisive case — a deliberately invalid credential:

GET https://esg.cogneris.com/api/ncrs   -H 'Authorization: Bearer not-a-real-token'   → 200

A build running deviceAuth would answer 401 with a WWW-Authenticate: Bearer header (deviceAuth.ts:154,173). A 200 on a junk token proves the deployed build does not check one.

What that returns is real production data — 8 NCRs from a live D1 (receiver: "d1"), raised 2026-07-31 to 2026-08-02, each with raisedBy: "Environmental Manager", a free-text description, and GPS to ~11 decimal places (43.6672, −79.3318). Anyone who can resolve the hostname can read the lot, and can POST a ticket under any name at any timestamp.

The fix exists — app/lib/deviceAuth.ts puts Authorization: Bearer on /api/ncrs GET+POST and /api/submissions GET+POST — but it is uncommitted and undeployed. HEAD is from 2026-08-01.

Operational prerequisite before deploying it. deviceAuth fails closed: with no ESG_DEVICE_TOKENS secret set it returns 503 and the console stops accepting tickets altogether (deviceAuth.ts:121-134). So the deploy order is wrangler secret put ESG_DEVICE_TOKENS first, matching tokens into the device build, then pnpm cf:deploy — otherwise the handsets go from "delivering to an open door" to "delivering to a 503".

4 · Test suites — executed

Run at 08:44 EDT on 2026-08-05, against a tree that is being edited as this is written:

  • Console (npm test, node --test): 63/63 pass, exit 0.
  • esg-field (npx jest): 17 suites / 191 tests, all pass.

Correction to an earlier statement in this session. A first jest run at ~08:20 reported 184/185 with one suite failing, and I attributed the failure to SubmissionsTab's act(...) warnings because that is what the tail of the output showed. That attribution was wrong — the act lines are console.error noise from a passing suite. Session 0add9fc1 records the real cause (another session widening INSPECTION_EVENT_TYPES at 07:38 without extending sampleDrafts() in lib/store/__tests__/durability.test.ts), and by the 08:44 re-run it was fixed and lib/ncr/__tests__/delivery.test.ts had joined the suite. Both suites are green now. Read a jest failure from the FAIL line, not from the last stack trace on screen.

5 · What could NOT be executed

  • Direct wrangler d1 execute --remote failed: the cached OAuth token in ~/Library/Preferences/.wrangler/config/default.toml expired 2026-08-04T23:40Z and the refresh was refused (code: 7403, account a10d32c7…fbb0). Re-authenticating needs an interactive wrangler login, which this session cannot run.
  • The production D1 contents in §3 were therefore read through the deployed /api/ncrs route, which reads that same D1 (receiver: "d1" proves the binding resolved). Equivalent for the question asked; not a substitute for schema-level inspection.
  • S1 was not proven or disproven in production data. Detecting a restamped arrival needs history the table does not keep.
  • Nothing was deployed, committed, or written to production. The only POST issued was an empty body that the route rejects at validation before touching the store.

Verdict (as written 2026-08-04 — read §2 above first)

  1. The NCR path is genuinely wired end to end: compose → append-only SQLite → POST /api/ncrs → D1/sqlite store → console arrivals inbox. This is the one real chain.
  2. A retry rewrites the record it is supposed to deduplicate — including its arrival time. This is the most serious defect found, and it defeats the stated purpose of the arrivals queue.
  3. The first delivery attempt after raising an NCR always misses that NCR, because delivery reads a pre-append React snapshot. It is recovered by the next sweep, so it is late, not lost.
  4. Both submissions endpoints are unauthenticated and reachable, and they accept identity, timestamp, severity, GPS and raw payload from the client with no validation.
  5. The inspection path stops at a local outbox with no matching receiver: nothing it queues can be accepted by any route in this repo.
  6. The console inbox is real; the lifecycle register and analytics beneath it are not — they read fixture rows, so a real device ticket never moves a score.
  7. Evidence never leaves the handset. A count crosses the wire; the photos and audio do not. This is deliberate and labelled, but it means device loss is evidence loss.

1 · CONFIRMED — Critical: a retry overwrites the accepted record and resets its arrival time

  • docs/app/lib/ncrStore.ts:151-L179 (D1) and docs/app/lib/db.ts:527-L540 (sqlite)
  • Both backends SELECT id to compute duplicate, then INSERT OR REPLACE all columns including received_at = Date.now().

Failure scenario: a handset's first POST lands but the response is lost, so the outcome is unknown and docs/apps/esg-field/lib/ncr/delivery.ts:129 re-sends. The second POST replaces the stored row and stamps a new received_at. Consequences:

  • The original arrival time — the fact docs/app/api/submissions/route.ts:1-L14 exists to preserve ("a device delivered this, and this console observed it") — is destroyed.
  • The queue is ordered by received_at DESC, so a week-old retried ticket jumps to the top of the inbox as if it just arrived.
  • Any field can be mutated on replay. An unauthenticated caller (see §4) who knows an NCR id can rewrite the description, severity, raiser and GPS of an already-accepted compliance record, and the console will show the rewrite with a fresh receipt time.

Correct shape: insert once; on an existing id either verify the body matches and return duplicate: true untouched, or store the replay separately. Never replace, never restamp.

2 · CONFIRMED — High: the immediate delivery sweep cannot see the NCR that triggered it

  • docs/apps/esg-field/screens/capture/CaptureFlow.tsx:176-L178 calls raiseNcr(log, …) then deliverSoon(log).
  • docs/apps/esg-field/screens/ncr/useNcrLog.ts:53-L63 builds that log with readAll: () => [...events], memoised on [append, events] — events is React state.
  • append schedules a state update; the array captured in the closure is the pre-append one.
  • docs/apps/esg-field/lib/ncr/delivery.ts:124 filters listNcrs(log), so the ticket just raised is not in the pending set.

Failure scenario: an operator with signal raises NCR C. The sweep fires, sees only A and B, and C is not attempted. It is delivered later — the next render's sweep, or the Submissions screen's mount sweep at docs/apps/esg-field/screens/SubmissionsTab.tsx:115-L119, which the capture flow navigates to. So this is a latency and honesty bug, not data loss: the comment at docs/apps/esg-field/lib/ncr/delivery.ts:10 ("the raise triggers delivery") is not true of the raise that triggers it. Fix: pass a log that reads through to the store, or have raiseNcr hand the appended event to deliverPending.

3 · CONFIRMED — High: a permanent rejection is retried forever

  • docs/apps/esg-field/lib/ncr/submit.ts:28-L36 documents rejected as "Retrying will not help; a person must look."
  • docs/apps/esg-field/lib/ncr/delivery.ts:131-L149 writes a receipt only on delivered, and treats everything except no-endpoint as still pending.

Failure scenario: a ticket the route 400s (a malformed raisedAt, say) is re-POSTed on every sweep for the life of the install, and the UI shows it as pending forever — the state docs/apps/esg-field/lib/ncr/delivery.ts:53-L59 reserves for "something is still trying", which invites nobody to intervene in a case that requires a person. There is no terminal failure state and no operator-visible error.

Related: a 503 from an unbound console (docs/app/api/ncrs/route.ts:74-L80) is classified rejected by docs/apps/esg-field/lib/ncr/submit.ts:132 even though the route explicitly intends it as retryable. Harmless today only because everything retries.

4 · CONFIRMED — High: no authentication on either submissions endpoint

  • docs/app/api/ncrs/route.ts:9-L13 says so itself.
  • docs/app/api/submissions/route.ts:43 GET is equally open.
  • docs/apps/esg-field/lib/ncr/api.ts:14-L25 records a direct probe on 2026-08-01: GET /api/submissions → 200, POST /api/inspections → 400 on an empty body. These routes answer unauthenticated requests on the deployed host.

So, live: anyone who can reach the console can POST a fabricated NCR under any employee's name at any timestamp, and GET the full arrivals list — site, area, severity, GPS to four decimals, raiser, and (via /api/ncrs GET and the register's detail view) the dictated transcript.

Server-trusted client fields with no validation at docs/app/api/ncrs/route.ts:83-L95: raisedBy, raisedAt (any non-empty string), severity (no enum), gps (no shape or bounds check), photoCount (Number() of anything), payload (unbounded, unvalidated, stored verbatim). The route also invents defaults for four columns the schema declares NOT NULL, so a malformed client produces a formally complete, semantically fabricated record.

5 · CONFIRMED — High: the inspection path has no receiver

  • docs/apps/esg-field/screens/SignoffSheet.tsx:191-L206 enqueues {closedOffAt, signatures[]} — no siteId, no summary, no findings.
  • docs/apps/esg-field/lib/sync/upload.ts posts {idempotencyKey, entityType, entityId, operation, payload, attempt, capturedAt} to one configured endpoint. /api/submissions has no POST handler at all; /api/inspections expects an op-keyed body. Neither could accept this row.
  • docs/apps/esg-field/lib/sync/index.ts:101-L107: resolveSyncEndpoint() returns null in this build, so nothing is currently attempted. Codex rated this Critical; corrected to High — it is a latent contract mismatch, not an active failure, and the sign-off comment is honest that the queue "does NOT imply the server received anything".

Two further defects on that path, both confirmed:

  • Enqueue failure is swallowed. docs/apps/esg-field/screens/SignoffSheet.tsx:203-L206 catches and comments "Re-queued on the next close-off attempt" — but the flow calls onDone() and leaves. No code re-attempts it and no job looks for signed-but-unqueued inspections. The comment asserts a recovery that does not exist.
  • The next screen hardcodes success. docs/apps/esg-field/screens/inspect/TaskFlow.tsx:651-L654 passes a literal {kind: "queued", since: new Date().toISOString()} — constructed at render, not read from sync_queue. If the enqueue above threw, the operator is still told "Queued".

6 · CONFIRMED — High: the console's register and analytics are fed fixtures

  • Real: docs/app/components/ncrRegister.tsx:455 fetches /api/submissions and distinguishes receiver-failure from genuinely-empty.
  • Not real: the lifecycle register and every score default to NCR_SUBMISSIONS, the seven illustrative rows at docs/app/lib/ncr.ts:198 — see docs/app/lib/analytics.ts:63 and docs/app/lib/ncr.ts:380.
  • Nuance codex missed: the derivation is real and parameterised (rows: NcrSubmission[] = NCR_SUBMISSIONS). It is the feed that is mock. Swapping the default for received rows is a wiring job, not a rewrite.

Failure scenario: a device NCR arrives and shows in the inbox, while closure, delivery, evidence and defensibility figures do not move — two surfaces on the same page disagreeing about the same ticket.

7 · CONFIRMED — Medium

  • Receipts are the weakest link in an otherwise durable chain. docs/apps/esg-field/lib/ncr/delivery.ts:83-L93 overwrites one JSON file in place — no temp-and-rename, unlike the signature repo which does it properly. A kill mid-write leaves malformed JSON; docs/apps/esg-field/lib/ncr/delivery.ts:68-L81 reads that as {} and every delivered ticket reverts to "pending" and is re-sent. Combined with §1, a re-send restamps every arrival time in the console.
  • Sign-off and enqueue are not atomic (docs/apps/esg-field/screens/SignoffSheet.tsx:172-L192): a crash between them leaves a signed inspection with no outbox row and no recovery sweep.
  • Inspection-store failure is reported as "no inspections." docs/app/api/submissions/route.ts:124-L129 catches everything and returns [], so a corrupt or unmigrated inspection DB renders as a valid queue that simply contains no inspections — the exact confusion the file's own header forbids.
  • "Raise another" inherits the last ticket's classification. docs/apps/esg-field/screens/capture/CaptureFlow.tsx:138 resets the stage but not pickedSite / pickedArea / pickedSeverity.
  • Dead confirmation stage. {kind: "confirm"} is declared at docs/apps/esg-field/screens/capture/CaptureFlow.tsx:48 and fully implemented at :245ff, but nothing ever sets it — onSave calls create() directly. Verified: no setter exists.
  • Dead submission client. submitFinding, submitSummary, sealInspection, fetchOpenInspection in docs/apps/esg-field/lib/ncr/api.ts are exported through the barrel and called by nothing. Only fetchPortalSubmissions has a consumer. Verified by repo-wide grep.
  • Two different portal-resolution policies in one module. docs/apps/esg-field/lib/ncr/submit.ts:46-L70 returns null (→ nothing is sent) where docs/apps/esg-field/lib/ncr/api.ts:48-L59 falls back to https://esg.cogneris.com. A build without EXPO_PUBLIC_PORTAL_URL therefore reads production arrivals while delivering nowhere, and the Submissions screen shows other devices' tickets beside its own permanently-pending ones. This one is ours, not codex's.
  • Response validation is partial. docs/apps/esg-field/lib/ncr/api.ts:274-L280 checks only id and title, then docs/apps/esg-field/screens/SubmissionsTab.tsx:219-L227 dereferences detail/site and calls new Date(receivedAt).toISOString() — which throws RangeError on a NaN. Reachable only via a corrupt row, since the server generates that value.
  • Known and already logged: no network-change trigger re-runs deliverPending (docs/WORKLIST.md:1526); no refresh control on the portal list; no pagination on an indefinitely-retained arrivals log.

8 · CORRECTED — codex claims that did not survive verification

  • "toFixed() can throw on a bad GPS value" — wrong. docs/app/lib/ncrStore.ts:105-L108 coerces with Number(), so a text latitude becomes NaN and renders as "NaN, NaN" in the inbox detail line. Still a defect — a fabricated coordinate displayed as if measured — but a display defect, not a crash.
  • "Non-NCR findings record nothing" rated High as unwired — the behaviour is real (docs/apps/esg-field/screens/capture/CaptureFlow.tsx:231-L241) but it is a deliberate, stated gap: the screen tells the operator, in words, that nothing was recorded and why. That is a missing feature, not a silent defect. Re-rated as a gap.
  • Generic sync mismatch rated Critical — re-rated High; no endpoint is configured, so nothing is being lost today (§5).

What is genuinely working

  • NCR wire contract matches field-for-field: docs/apps/esg-field/lib/ncr/submit.ts:73-L90 → docs/app/api/ncrs/route.ts:38-L95 → the ncrs columns. No translation layer, no drift.
  • The device event log is a real append-only SQLite database with update/delete triggers (docs/apps/esg-field/lib/store/db.ts); a raised NCR survives restart.
  • BR-X5 holds where it matters: a receipt is written only on a 2xx this device observed. A timeout is unknown, never success. No screen claims delivery it did not see.
  • duplicate is returned and 200 on replay, so retry cannot mint a second ticket (the storage of the replay is the problem — §1 — not the classification).
  • received_at is the server's clock, not the device's.
  • Both backends bind parameters throughout; no submission field is interpolated into SQL.
  • The console inbox tells receiver-failure, empty and populated apart instead of collapsing them.
  • Photo evidence is honestly labelled as handset-only rather than implied uploaded.
  • The dynamic node:sqlite import in docs/app/lib/ncrStore.ts is the fix that lets the deployed Worker receive at all; ESG_NCR_DB is bound in wrangler.jsonc:13-19 with migrations/0001_ncrs.sql.

Suggested order of work

  1. §1 — insert-once semantics in both backends. Small, contained, and it is the one finding that corrupts accepted records.
  2. §4 — put a credential on /api/ncrs POST and /api/submissions GET, plus body validation (enums, ISO timestamps, GPS bounds, payload size).
  3. §3 — a terminal rejected receipt so a 400 stops re-sending and surfaces to a person.
  4. §2 — read-through log for the post-raise sweep.
  5. §6 — point analytics.ts / the register at received rows; the derivation already takes them.
  6. §5 — either give the inspection outbox a real receiver or state in the UI that it has none.

Raw codex output

Kept out of the repo. Full transcript (15,508 lines incl. its file reads): …/scratchpad/codex-submissions-audit.md in session 22f75e25; the report itself begins at line 15,133.


ADDENDUM — 2026-08-05 · what has since been fixed

Claude Opus 5 (Claude Code, session 0add9fc1). Every item below was implemented, typechecked and tested in this repository on 2026-08-05. Still nothing was executed against a live deployment: no D1 read, no endpoint probe, no device build. What IS new is that the properties are now asserted by tests that run — named per finding, so a regression names itself.

Verified here, and only this:

  • npx tsc --noEmit — console (tsconfig.json) and apps/esg-field — clean over every file touched here.
  • node --test tests/*.test.ts — 62 pass, 0 fail (17 before this work began).
  • npx jest in apps/esg-field — 150 of 151 pass, 14 suites. The one failure is lib/store/__tests__/durability.test.ts, which is NOT this work: another session added three location-bound event types to INSPECTION_EVENT_TYPES at 07:38 on 2026-08-05 without extending its own sampleDrafts() fixture, so the suite expects 14 drafts and gets 11.
  • npx eslint over every file changed here — clean. (app/ as a whole reports 4 errors and 3 warnings, all in files belonging to the other session: ConsoleShell.tsx, v2/views/director.tsx, compliance/page.tsx, components/siteMap.tsx.)
  • NOT verified: any behaviour on a handset, on Cloudflare, or against esg-ncr-db. Nothing was deployed, no migration was applied, no endpoint was probed.

Fixed

§1 · S1 — a retry can no longer rewrite or restamp an accepted record. Both backends are now INSERT-ONCE. app/lib/ncrStore.ts and app/lib/db.ts read the existing row, return {stored:false, duplicate:true} without writing, and use INSERT OR IGNORE for the first write so losing a race with a concurrent retry keeps the FIRST row rather than the last. A replay whose content DIFFERS from what was accepted is reported — ncrConflict() compares every field the device asserted (not payload, whose key order is not meaning, and not receivedAt, which is the server's own clock) — and POST /api/ncrs now answers {ok, id, stored, duplicate, conflict}. The stored row always wins. Covered by two specs in tests/persistence.regression.test.ts, including the forged-rewrite case an unauthenticated caller would attempt.

§2 · S2 — the post-raise sweep now sees the ticket that triggered it. useNcrLog keeps the events it has appended since the render it was built from and answers reads from snapshot + appended, reconciled on eventId so nothing folds twice. Deliberately NOT done by reaching for the store singleton: the adapter must stay drivable from a test that mocks lib/store. Second half of the same finding: deliverPending used to collapse onto an in-flight sweep and report "nothing attempted", so a raise landing mid-sweep waited for the next screen; it now runs one follow-up sweep after the one it waited for (bounded — the follow-up cannot itself follow up).

§3 · S4 — an answered refusal is terminal, recorded, and said. A rejected outcome writes a DeliveryRejection (status + the portal's own words), the ticket stops being swept, and Submissions shows "refused by the portal (HTTP n) — needs a look" in the issue colour instead of "sending". clearRejection(ncrId) puts one back in the queue when the far end is fixed. Four specs in the new apps/esg-field/lib/ncr/__tests__/delivery.test.ts.

§7 · S7 — the receipts file is written atomically. Same idiom as lib/signature: write a sibling temp file, delete, rename. The temp file is also the FALLBACK READ, so a kill between the delete and the rename loses nothing. The file is now versioned ({v:2, receipts, rejections}) and a v1 flat file is still read, so upgrading does not re-send everything. Three specs, one of which reproduces the truncated-JSON state the old in-place write produced.

§4 · S3 (PART ONE ONLY) — validation, not authentication. POST /api/ncrs now rejects a body over 256 KB (before parsing), a non-object body, any text field over 4,000 characters, a severity outside low|medium|high|critical, a raisedAt that is not a real ISO-8601 instant, a GPS that is not two finite numbers within ±90/±180, and a photoCount that is not a small whole number. All errors are returned at once, because the device now treats a refusal as terminal and the reason has to be actionable without a second round trip. An unstated severity is recorded as unspecified, NOT medium — a console must not colour a judgement no inspector made — and severityTone / severityLabel in app/lib/ncr.ts are total so an unmodelled value renders neutrally with its own word rather than as an empty badge.

§8 · the two-portal-policies defect (ours, not codex's). resolvePortalBaseUrl() in lib/ncr/api.ts now delegates to portalBaseUrl() in lib/ncr/submit.ts and returns null when nothing is configured; the three call sites answer {kind:"no-endpoint"}. A build without EXPO_PUBLIC_PORTAL_URL no longer reads production arrivals while delivering nowhere.

§8 · partial response validation. fetchPortalSubmissions now NORMALISES each arrivals row rather than filtering on two fields: receivedAt becomes number | null (never a substituted epoch), kind/site/detail/at are coerced, and a row with neither at nor receivedAt is dropped by SubmissionsTab rather than crashing it on new Date(NaN).toISOString().

Fixed in the second pass — 2026-08-05, later the same day

Claude Opus 5 (Claude Code, session 0add9fc1), after Pete asked for the three items below to be completed rather than left as decisions. Each was left open for a reason; each reason is answered here rather than ignored.

§4 · S3 (PART TWO) — the endpoints are authenticated. POST /api/ncrs, GET /api/ncrs, GET /api/ncrs/[id] and GET /api/submissions now require a device credential (Authorization: Bearer … against ESG_DEVICE_TOKENS — app/lib/deviceAuth.ts), compared in time independent of where a wrong token first differs. It fails closed: a deployment with no credentials configured refuses device traffic with a 503 naming the variable to set, because a control that switches itself off when unconfigured is not a control. The escape hatch is explicit and recorded in every response (ESG_ALLOW_ANONYMOUS_SUBMISSIONS).

The open question was "which mechanism". The answer is a bearer token because the client is a handset that works in a tunnel and delivers hours later: it cannot hold a short-lived session, and mTLS is not available to an Expo app without a native networking layer.

The read hole is closed by removing the endpoint, not by guarding it. The console's own register used to fetch("/api/submissions") and fetch("/api/ncrs/<id>") from the browser, which is why those routes had to stay open — and no header a browser sends can prove who is behind it, so "protecting" them with one would have been theatre. The Submissions page now reads the store in its own server render (app/lib/arrivals.ts) and hands the rows plus the raise events down as props. Nothing in the browser calls those routes any more.

On the device: the credential rides on every request (portalHeaders), and a refused credential is its own outcome — unauthorized, NOT rejected. That distinction is load-bearing: after the S4 fix a rejected ticket is terminal, so folding a 401 into it would have let one missing secret permanently kill delivery of every ticket on every handset. A credential failure stops the sweep, keeps every ticket, and says so on Submissions and in Diagnostics (which shows whether a credential is configured, never its value). Ops steps: docs/OPS-device-credential.md.

§5 · S5 — the outbox has a receiver, a real payload, and honest state. Three separate defects:

  • POST /api/submissions now exists and speaks the outbox's own envelope, so no device needs a new build to be received. Insert-once on the device's inspection id into delivered_inspections (D1 and local sqlite, migrations/0003), and a replay is answered with the same receipt — which is what makes the retry safe rather than merely tolerated. It honours Idempotency-Replayed, the proof lib/sync/upload.ts already looked for.
  • The queued payload was {closedOffAt, signatures[]} — no site, no summary, no finding count. It is now folded from the same event log the report is folded from, so what is delivered and what is printed cannot disagree. It carries siteName and templateId, NOT a siteId: an inspection event holds no site id, and putting the template id in a field of that name would be a fabrication that reads as fact at the far end.
  • The enqueue catch promised a re-queue nothing performed. reconcileOutbox() is that promise made real — any inspection with a signature in the log and no outbox row gets one, idempotently, on mount.
  • TaskFlow hardcoded {kind:"queued"} at render. It now derives all four states from the real row: saved (durable, not queued), queued, received (a receipt exists — persisted on the row, so a restart cannot downgrade it), not-received (with the reason). A synced row with no receipt reads "queued", because delivery observed is not a receipt issued.

§6 · S6 — the register and the roll-up read the same feed as the inbox. app/lib/ncrFeed.ts maps a received ticket onto a register row and chooses the source via ESG_CONSOLE_FEED: auto (default — live rows when this console holds any, else the sample), live, sample, mixed. Whatever is chosen is named on the surface, so a reader never has to guess whether a figure counts real tickets. That answers the objection that made this "Pete's call": the deck keeps its seven worked-example rows until a real ticket arrives, and the moment one does the page is about real tickets and says so.

A delivered ticket arrives as an open ticket with an empty history — no owner, no corrective action, no verification — because none of those has happened. syncedAt is the one field a live row knows better than a fixture: it is when this console observed the delivery. ncrSummary was the one derivation not already parameterised; it is now, with its default intact.

NOT fixed, and why

*(The first-pass list below is superseded for S3, S5 and S6 by the section above. What remains open after both passes is stated here.)*

  • HUMAN access to the console pages is still unauthenticated. The device routes are closed; the pages are not. There is no identity provider in this repository and no code change can supply one — it is Cloudflare Access in front of the origin, a dashboard change, and it has not been made. Anyone who can reach esg.cogneris.com can still read the Submissions page in a browser.
  • The device credential is per BUILD, not per device. Two handsets on one build share it and cannot be revoked independently. The seam for per-device enrolment is deviceToken().
  • NOTHING HAS BEEN RUN AGAINST A DEPLOYMENT. ESG_DEVICE_TOKENS is not set on the deployed console, so — by the fail-closed design — the deployed console will refuse device traffic until an operator sets it. migrations/0003 has not been applied to D1 either. Both are one command each in docs/OPS-device-credential.md and the migration header.
  • S8 residue — sign-off/enqueue atomicity is improved but not atomic (the recovery sweep closes the gap rather than removing it); the inspection-DB failure reported as "no inspections", "Raise another" inheriting the last classification, the dead {kind:"confirm"} stage, and three of the four uncalled API functions are untouched.
  • Other surfaces still read the fixture default — app/v2/** (director, manager, board, auditor, brief) and app/components/dashboard-widgets.tsx call the derivations with no argument. They are client components mid-edit in another session (E16); the Submissions register and the reporting dashboard, which are what the finding named, now read the feed.