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/REVIEW-codex-2026-08-06.md3,542 words

Deep code review — feat/rn-app-parity working tree

Date: 2026-08-06 Reviewer: Codex CLI 0.145.0 (codex exec, read-only sandbox, high reasoning), driven and verified by Claude Code (Opus 5, session e36ef25c). Scope: the uncommitted diff against HEAD (37 modified files, ~3,000 insertions) plus every untracked new source file. docs/*.md reviewed only as a claim ledger against the code. Tokens spent by the reviewing model: 729,244.


0. READ THIS FIRST — the tree moved under the review

Another Claude Code session was writing to this working tree while the review ran. Confirmed, not suspected:

  • apps/esg-field/lib/inspection/disciplines.ts grew from 210 to 265 lines at 16:31, mid-review.
  • apps/esg-field/lib/store/events.ts gained a DisciplineAssessed event type in the same window.
  • apps/esg-field/screens/inspect/DisciplineAssess.tsx did not exist when this review was scoped and is cited in the findings below — it was created during the run.
  • next build and other claude --output-format stream-json processes were live throughout.

Consequence: line numbers in findings that touch disciplines.ts, events.ts, DisciplineAssess.tsx and docs/WORKLIST.md may be stale by the time you read this. The findings themselves were verified against the file contents at the moment they were read. Everything else in the review is against a stable tree.

This also means the two test failures in §1 may be transient work-in-progress, not landed defects. They are reported as what the tree actually did, not as a verdict on anyone's intent.


1. Ground truth — what actually builds and passes

Measured directly, not inferred:

CheckResult
tsc --noEmit (console, repo root)clean
tsc --noEmit (apps/esg-field)clean
npm test (console, node:test)68/68 pass
npx jest (apps/esg-field)227/228, then 3 failures after the mid-review edits

This corrects an earlier standing note that apps/esg-field carried ~56 pre-existing tsc errors. It does not now.

1.1 lib/store/__tests__/durability.test.ts — FAILING

● persists events across a full restart (reopen sees committed rows) — FR-CAP-29
  Expected length: 17
  Received length: 16

INSPECTION_EVENT_TYPES gained DisciplineAssessed (events.ts:53); sampleDrafts() in durability.test.ts was not given a matching draft. The test exists precisely to prove every event type survives a close-and-reopen, so the new event type currently has no persistence coverage at all — and the suite is red rather than silently passing, which is the good failure mode.

Fix: add a DisciplineAssessed draft to sampleDrafts().

1.2 lib/inspection/__tests__/disciplines.test.ts — 2 FAILING

Expected pattern: /safety item/i
Received string:  "7 items planned here, none answered yet."

The safety lane's reason string was reworded mid-edit; two specs still assert the old wording (/safety item/i and /no safety event/i). The second pattern matters more than the first: the old string carried the honest admission *"none can be answered yet, because the app has no safety event to record one in."* That admission is gone from the new string, and a DisciplineAssessed event now exists — so the assertion is arguably correct to fail. Decide which is true and make the string and the spec agree.


2. Findings

Severity is Codex's, retained. [VERIFIED] marks findings this session independently re-checked against the source. Unmarked findings are Codex's, traced but not independently re-derived here.

A. Correctness bugs

A1 · CRITICAL · [VERIFIED] — screens/capture/NoteCapture.tsx:252, lib/audio/sherpaStreaming.ts:349 Releasing push-to-talk never stops the microphone. stop() calls finishNoteCapture(), which closes the WAV and runs Whisper but issues no stopRecording, no offData detach, no stream release, and no audio-session release. engineRef.current = null in the finally then discards the only handle that could have done it. A hot mic and a ducked audio session survive behind an idle UI. Fix: one atomic engine operation that stops mic → drains → releases session → finalizes and transcribes; hold the engine reference until cleanup completes.

A2 · HIGH · [VERIFIED] — NoteCapture.tsx:264 chimeClose() fires with the comment "AFTER the mic is released, so it cannot land in the audio" — but nothing has released the mic (see A1), and the call is not awaited. The closing tone can be recorded into the WAV and transcribed.

A3 · HIGH — NoteCapture.tsx:225,405,489 Unmounting during permission/model preparation can still start a mic after the screen is gone. Cleanup never clears heldRef, and engineRef is assigned only after startRecording(), so there is nothing to cancel. Fix: abort generation token; clear heldRef on unmount; retain the preparing engine immediately; re-check cancellation after every await.

A4 · HIGH — sherpaStreaming.ts:223,262 enqueue() launches an untracked async drain() while stopAndTranscribe() independently flushes, finishes, reads and releases the same native stream. A release during processAudioChunk() loses final frames or raises a native error that drain() converts to status text.

A5 · HIGH — SiteMapView.tsx:78,268, TaskFlow.tsx:1320 The field map always renders Ontario Line geometry for every project. Open an Eglinton inspection and you see Ontario Line streets while every Eglinton location reports "not on this plan."

A6 · HIGH — TaskFlow.tsx:1421, events.ts:283 Location-walk photographs discard locationId. The callback receives it; only section areaId and itemId are stored. Where a check applies at several places, the photo cannot say which one.

A7 · HIGH — TaskFlow.tsx:1841,1888,1939 Re-recording a legacy section can erase every previous deficiency. Committed answers make answeredIn === n, but commitFlagged() serializes only the empty current draft — pressing Record immediately writes an empty list and derives pass.

A8 · HIGH — TaskFlow.tsx:793,814, coverage.ts:178 Location-bound inspections still register the legacy spoken grammar. Saying "pass" appends AreaInspected, tipping the inspection to mixed, which the coverage fold deliberately refuses to call complete.

A9 · HIGH — TaskFlow.tsx:396,1233 Sign-off coverage counts only legacy AreaInspected against SECTIONS.length. A fully completed location walk presents at sign-off as 0/9.

A10 · HIGH · [VERIFIED] — LocationWalk.tsx:254 The note fold filters on e.type !== "NoteRecorded" and never checks aggregateId. A note from a different inspection that shares a location id appears in — and can be played back from — this walk. One-line fix: && e.aggregateId === inspectionId.

A11 · HIGH — NoteCapture.tsx:278,308 Multiple dictation turns append text and machine transcripts but overwrite the single audioUri. A saved two-turn note holds both turns' words and evidence for only the last.

A12 · HIGH — app/lib/inspectionStore.ts:170 D1 idempotency is check-then-insert. Two racing requests both miss the SELECT; the loser's INSERT OR IGNORE is ignored but it still returns stored: true with a freshly computed timestamp instead of the canonical row.

A13 · HIGH — app/inspections/page.tsx:56,91,128,189 Changing location neither resets nor revalidates category, and save() does not require a location even where a location register exists. A finding can be saved with no place, or with a category that no longer applies there.

A14 · MEDIUM — app/lib/workStages.ts:330,362 — delivered progress folds every observation including superseded corrections, and uses find() (the first) for stalled detection. A mistake corrected later in the same walk stays a regression signal.

A15 · MEDIUM — lib/inspection/scope.ts:106 — observed.get(id) ?? seeded treats an explicitly observed null stage as absent and resurrects the seed. Use observed.has(id).

A16 · MEDIUM — app/index.tsx:416 — flowHasWritten() checks only the shell's immutable flow.taskId, which stays null for a newly created aggregate, so leaving after durable writes offers the "nothing written / abandon" path.

A17 · MEDIUM — app/index.tsx:556 — spoken "close inspection" calls closeFlow() directly, bypassing the save/abandon confirmation the UI enforces.

A18 · MEDIUM — LocationWalk.tsx:424 — the collapsed site-wide card hardcodes 0/N even though siteAnswered is computed.

B. Contract mismatches and type-safety holes

B1 · HIGH — disciplines.ts:117,120 — the fold ignores frameworkId/frameworkVersion and accepts any response itemId. Stale-version or fabricated items count toward current coverage, producing summaries like "10 of 9 answered."

B2 · HIGH — data/disciplineRegister.ts:43, events.ts:169, DisciplineAssess.tsx:48 — the register says asset items are answered per registered thing and the event carries assetId, but the screen collapses each item to one row and its response type has no assetId. At East Harbour, two fuel-storage assets get one shared hs-7 verdict.

B3 · HIGH — disciplines.ts:178 — the development lane passes an empty asset-kind list while the assessment screen passes real kinds. pm-5 can be recorded at a monitoring asset yet is omitted from the lane's denominator.

B4 · MEDIUM — disciplines.ts:180 — with a stage observation and a PM assessment, the lane attributes by/at to the inspection creator and the stage timestamp, though the summary folds another assessor's answers.

B5 · HIGH · [VERIFIED] — tsconfig.json The console tsconfig.json does not extend tsconfig.base.json. exactOptionalPropertyTypes, strictBuiltinIteratorReturn and the rest of the base strictness are simply off for app/. app/inspections/page.tsx:193 passes string | undefined into audioUrl?: string with no TS2379. The clean console typecheck in §1 is weaker than it looks. This is the single highest-leverage fix in the review: one "extends" line restores the guarantee across the whole console.

B6 · HIGH · [VERIFIED] — apps/esg-field/data/corridorGeo.ts vs app/lib/corridorGeo.ts The device knows 10 Ontario Line zones; the console knows 7. Device-only: z-ol-lakeshore, z-ol-thorncliffe, z-ol-flemingdon. The same location is drawable on the handset and explicitly undrawn on the console.

B7 · HIGH · [VERIFIED, but knowingly accepted] — sitePlans.ts:886 vs data/sites.ts:127 AST-OL-WASH-3 is at z-ol-donvalley on the console and z-ol-thorncliffe on the device. This is documented as deliberate at sitePlans.ts:897 — *"moving an asset between control areas changes what a past inspection was about, and that is a register decision, not a tidy-up."* Treat this as a decision awaiting a register owner, not as a bug to fix quietly. Flemingdon's asset count (3 device / 1 console) is the same class of drift.

B8 · MEDIUM — events.ts:117, TaskFlow.tsx:1841 — ItemVerdict documents its array as exceptions, passing items omitted, but item-by-item recording writes every pass into it. Consumers cannot rely on the declared semantics.

B9 · MEDIUM — app/lib/inspectionStore.ts:107, app/inspections/[id]/page.tsx:96 — persisted JSON is cast to signature/progress shapes after only Array.isArray. Malformed elements yield duplicate/undefined React keys, bogus signer fields, NaN timestamps, and objects rendered as text.

B10 · LOW — TaskFlow.tsx:290,424 — selectedSiteId is accepted and ignored; task creation rebuilds the id by exact name match, so a renamed or duplicated label loses the binding.

C. Missing or weak error handling

C1 · HIGH — sherpaStreaming.ts:177,213 — failures after entering the record session only set listening = false; nothing stops the mic, detaches listeners, releases the stream, or releases the session. C2 · HIGH — NoteCapture.tsx:457,474 — the WAV recorder opens before startRecording(); if mic startup returns false or throws, the recorder is never finished or discarded. C3 · HIGH — sherpaStreaming.ts:439 — cancel() clears command capture but never resets capturingNote / noteRecorder / noteSamples, leaking the file handle with an unfinalized header. C4 · MEDIUM — TaskFlow.tsx:1100 — the discipline modal closes before recordAssessment() appends; if the append throws, every draft answer is lost with no way back. C5 · MEDIUM — DisciplineAssess.tsx:140,156 — deficient answers can be recorded with an empty note, contradicting the module's own comment that such evidence is unusable. C6 · MEDIUM — app/index.tsx:334 — loadTurns() has no rejection handler, and startWarmup() plus interrupted-recording recovery are chained behind an uncaught loadDiag(). One diagnostics read failure kills audio initialization. C7 · MEDIUM — TaskFlow.tsx:309 — outbox reconciliation failures are swallowed and the live cancellation flag does nothing; a signed inspection can be undeliverable with no state or diagnostic. C8 · MEDIUM — app.config.js:183, lib/sync/connectivity.ts:27 — app config supplies portalUrl but never syncUrl. A normal build with only the documented portal URL can raise NCRs but never deliver an inspection. C9 · MEDIUM — app/lib/arrivals.ts:50 — any DB import/query failure becomes an empty list; corruption and "nothing arrived" are indistinguishable. C10 · MEDIUM — app/inspections/page.tsx:108 — hydration checks neither res.ok nor the JSON shape; a 500 silently leaves stale UI. C11 · LOW (plausible) — lib/audio/warmup.ts:97 — fire-and-forget preloadChimes() inside a surrounding try; an async rejection escapes that catch. C12 · LOW (plausible) — lib/audio/pcmWav.ts:237,313 — an existing filename is opened without truncation, and recoverInterruptedTurns() rewrites any sufficiently large .wav with a zero data length without validating RIFF/WAVE/PCM headers first.

D. Test quality gaps

D1 · HIGH — disciplines.test.ts — no spec supplies a wrong framework/version, an unknown item, or an asset-scoped response, so B1/B2/B3 all pass unnoticed. D2 · HIGH — tests/registers.test.ts:134,461 — geometry is asserted only as a subset of the console register, and the file explicitly declines device/console asset reconciliation. B6 and B7 pass by design. That was a deliberate choice; it is now the reason the drift went unseen. D3 · MEDIUM — tests/persistence.regression.test.ts:114 — the "real concurrent inserts" test is not concurrent: each microtask runs the synchronous insertFinding() to completion before the next starts. It cannot catch the class of bug it is named for. D4 · MEDIUM — LocationWalk.test.tsx:271 — handcrafted objects cast via unknown as InspectionEvent[] bypass payload typing; cross-inspection note isolation (A10), playback cleanup, stage correction, and sign-off coverage are all untested. D5 · MEDIUM — nothing tests mic/session cleanup, stop/drain ordering, unmount-during-preparation, recorder cleanup on startup failure, or multi-turn audio retention — exactly where A1–A4 and A11 live. D6 · MEDIUM — no test issues simultaneous D1 put() calls for one id (A12). D7 · LOW — the clean console typecheck is misleading until B5 is fixed.

E. React / React Native

E1 · HIGH — SiteMapView.tsx:337,438 — every pan/zoom re-renders up to 3,803 SVG Path components and recreates the PanResponder (it depends on zoom and pan). Expect bad stutter on a handset. Memoize the static basemap; drive transforms through animated/native state; read gesture values from refs. E2 · MEDIUM — LocationWalk.tsx:302 — setOpen() is called during render on focusLocationId change. E3 · MEDIUM — app/components/planCanvas.tsx:857 — BasemapLayer mutates a module cache and starts fetch() during render; a failed request leaves an undefined as Basemap sentinel that permanently blocks retries, and the promise can setMap after unmount. E4 · MEDIUM (plausible) · [independently spotted] — lib/audio/notePlayer.ts:60 — concurrent playNote() calls race through the module globals current/onEnd. Separately: the module doc promises onFinished fires "when another note takes over", but playNote awaits stopNote(), which nulls onEnd without calling it — so the previous row keeps a stale "playing" mark forever. E5 · MEDIUM (plausible) — LocationWalk.tsx:278, SiteMapView.tsx:250 — neither playback consumer stops audio or guards callbacks on unmount; audio continues across navigation. E6 · MEDIUM — NoteCapture.tsx:620 — slide-to-lock sets only setLocked(true); lockedRef stays false until the next render, so an immediate onPressOut stops the turn the user just locked. E7 · LOW — TaskFlow.tsx:1818,2067 — one noteDraft shared across all legacy sections carries unsaved text between them. E8 · LOW — SiteMapView.tsx:647 — lanesAt() is called once per discipline; each call refolds coverage and rescans the event log. Call it once per selected location.

F. Honesty problems

This project holds itself to an unusually explicit honesty standard, so these are ranked as first-class defects rather than documentation nits.

F1 · HIGH · [VERIFIED] — WORKLIST.md:216, NoteCapture.tsx:252,327 N0-V claims a completed retained-audio voice flow. Stopping does not stop the mic (A1). It also claims the screen shows "Refined by…" — but setRefinedBy(...) at ~276 is followed by setRefinedBy(null) in the finally at ~327, so the provenance panel is cleared before it can ever be seen, and engine/model provenance is not retained on the saved note.

F2 · HIGH — WORKLIST.md:281, SiteMapView.tsx:750, CaptureFlow.tsx:165 — N4 claims asset selection binds both NoteRecorded.assetId and NcrRaised.assetId. The card offers only "Note"; the raise flow never receives or writes an asset id.

F3 · HIGH — WORKLIST.md:293,361,377 — N5/P2/P4 contradict the tree: the text says there is no safety framework, no safety event, no screen, and five specs. There is now a DisciplineAssessed event, a safety framework, a reachable DisciplineAssess screen, and more specs. *(Partly an artefact of §0 — the code moved past the worklist during this review.)*

F4 · HIGH — WORKLIST.md:315, sitePlans.ts:1003 — N6 says the three formerly unplotted places are "on the plan." Only the field geometry has them; the console still treats them as undrawn and stacks their assets on fallbacks. Qualify the claim per surface.

F5 · MEDIUM — WORKLIST.md:265, app/inspections/page.tsx:128 — N3 claims place-first entry narrowed to valid categories; A13 shows neither invariant is enforced at save.

F6 · MEDIUM — WORKLIST.md:239,262 — N2 appears twice with the same title, once complete and once unchecked.

F7 · MEDIUM — WORKLIST.md:432, TaskFlow.tsx:1007 — M7 says NoteRecorded has no producer; the note modal writes it. M4 says per-discipline assessment needs an event vocabulary; it exists.

F8 · MEDIUM — HomeTab.tsx:400 — every fixture project shows a green LIVE badge and "Updated just now" over static authored data.

F9 · MEDIUM — HomeTab.tsx:493 — the selected project's "NCR tickets" tile renders work.tasks, the device-wide count, as if it belonged to that project.

F10 · MEDIUM — TaskFlow.tsx:480 — the comment defers severity to a later classification pass; the event writes "medium" immediately and no later pass exists. An unset classification is being recorded as a real severity.

G. Simplification and duplication

G1 · MEDIUM — geometry and asset identity are hand-duplicated across console and field (corridorGeo.ts ×2, sites.ts / sitePlans.ts) and have already drifted (B6, B7). Extract one versioned registry and generate both projections from it. This is the root cause behind B6, B7, D2, F4 and A5 — five findings, one fix. G2 · LOW — app/components/siteMap.tsx:192,347 — the discipline filter applies only to the all-site list; zone and asset focus panels revert to unfiltered plotted. G3 · LOW — TaskFlow.tsx:270,1437 — onRaiseNcr is documented as the preferred host seam and is never called.


3. Recommendations, in the order I would do them

Do now — these are cheap and they unblock the rest

  1. Add "extends": "./tsconfig.base.json" to the console tsconfig.json (B5). One line. Every subsequent console typecheck gets the strictness the project believes it already has. Expect a batch of real errors to surface; that is the point.
  2. Fix the two red suites (§1.1, §1.2). A DisciplineAssessed sample draft, and a decision about whether the safety lane still admits it has no event to record into.
  3. && e.aggregateId === inspectionId in the LocationWalk note fold (A10). One line; it stops one inspection's evidence appearing inside another's.

Do before this branch is demoed

  1. Fix the microphone lifecycle (A1, A2, A3, C1, C2, C3). A hot mic behind an idle screen is the worst defect in the review — it is a privacy problem, a battery problem, and it will be visible on stage as a red status pill nobody can explain. Treat A1–A3 and C1–C3 as one piece of work: a single teardown() on the engine that every path (stop, cancel, unmount, startup failure) calls, with the note recorder finalized inside it.
  2. Project-scope the field map (A5). Ontario Line streets under an Eglinton inspection is the kind of thing that ends a demo.
  3. Fix sign-off coverage for location walks (A9). A completed walk reporting 0/9 at the signature screen invites the operator to distrust the whole record.
  4. Stop legacy re-record from erasing deficiencies (A7) and stop legacy voice commands corrupting location-bound walks (A8). Both silently destroy or downgrade real findings.

Do before anyone relies on the data

  1. One canonical geometry + asset registry, generated to both surfaces (G1 → B6, F4, A5, D2). Then change tests/registers.test.ts from a subset assertion to an equality assertion — the subset test is what let the drift through, and it will let the next one through too.
  2. Take AST-OL-WASH-3 and Flemingdon to whoever owns the register (B7). The code already says this is a register decision, not a code fix. Get the decision, then encode it.
  3. Runtime-validate persisted and delivered JSON (B9, C9, C10). The console currently trusts Array.isArray and renders whatever it finds.
  4. Make D1 delivery idempotency atomic (A12) and give it the interleaving test it lacks (D6).
  5. Resolve syncUrl at build time (C8). A build that can raise NCRs but never deliver an inspection will look like a network problem for a long time before anyone finds the config.

Do as a standing habit

  1. Reconcile docs/WORKLIST.md with the tree (F1–F7). Several entries now describe a past that the code has moved beyond, and at least one (N0-V) claims a feature that does not work. Given §0 this is partly a concurrency artefact — but the worklist is the file every future session starts from, and a worklist that overstates is worse than one that is merely behind.
  2. Label authored fixtures as authored (F8, F9, F10). LIVE, "Updated just now", and a default severity of "medium" are each a small untruth in a product whose entire argument is that it does not tell them.
  3. Close the test blind spots that hid these bugs (D1–D6). In priority order: an engine fake with observable lifecycle calls (D5), adversarial framework/version/item specs (D1), and a genuinely concurrent persistence test (D3).

4. What was NOT reviewed

  • docs/*.md prose, except as claims checked against code.
  • apps/esg-field/data/basemaps/*.json beyond a structural/finite-number scan.
  • Anything outside the working diff — committed history was not audited.
  • Runtime behaviour on a real device. No handset was involved. Every finding above is static analysis plus the local test and typecheck runs in §1.

*Review executed and verified 2026-08-06 by Claude Code session e36ef25c (Opus 5) using Codex CLI 0.145.0. Raw Codex output retained at the session scratchpad codex-review.out.*