docs: add 13-mini-app concept-execution coherence audit evidence
Full read-only audit of all 13 mini-apps against README's problem-mapping table + each module's own doc comments. 6 COHERENT (lightclock, fairdraw, healthpost, theclimb, sky, mentor), 7 GAP-FOUND and fixed in prior commits (fairshare, waterwatch, tunnelsafety, housing, assembly, findfamily, farms).
No files matched your search
@@ -0,0 +1,187 @@
|
||||
# Coherence Audit: Assembly (ma-assembly)
|
||||
|
||||
Scope: README's claim - "Yjs CRDT for offline-first proposals/rosters/votes
|
||||
with liquid-democracy tally, a 3-layer resilience model (local-first, WebRTC
|
||||
partition-and-heal, QR-sneakernet air-gapped fallback), and a signed public
|
||||
testimony board reusing the same event-log infrastructure as group voting."
|
||||
Testimony board sync is explicitly OUT of scope here (already audited and
|
||||
fixed this session - see `.omo/evidence/service-sync-reevaluation.md`).
|
||||
|
||||
Files read: `src/lib/governance.ts`, `src/lib/assemblySync.ts`,
|
||||
`src/lib/qrSneakernet.ts`, `src/lib/governanceEvents.ts`,
|
||||
`src/miniapps/assembly/useAssemblyEngine.ts`, `src/miniapps/assembly/AssemblyScreen.tsx`,
|
||||
plus grep across `src/` and `.omo/evidence` / `.omo/plans` for cross-references.
|
||||
|
||||
## 1. Liquid democracy - REAL, not mislabeled
|
||||
|
||||
`src/lib/governance.ts` implements actual vote delegation, not plain
|
||||
one-resident-one-vote QV wearing a label:
|
||||
|
||||
- `DelegationRecord { delegatorId, delegateId }` + `putDelegation` /
|
||||
`removeDelegation` (governance.ts:60-120, CRDT-backed `Y.Map`).
|
||||
- `resolveEffectiveVoter` (governance.ts ~190-230) walks the
|
||||
`delegatorId -> delegateId` chain transitively (A delegates to B, B
|
||||
delegates to C -> C's ballot counts for A), with a `visited` set that
|
||||
detects a cycle (A -> B -> C -> A) and deterministically falls back to the
|
||||
starting resident's own ballot instead of looping or double-counting.
|
||||
- `computeQvTally` (governance.ts ~270-330) resolves every enrolled
|
||||
resident's effective voter through `resolveEffectiveVoter` before adding
|
||||
their `sqrt(credits)` weight to a tally bucket - delegation moves *whose
|
||||
choice* counts, never whose credits are spent (the module's own stated
|
||||
design, matching real liquid-democracy semantics, e.g. Behrens et al.).
|
||||
- Wired into the UI: `AssemblyScreen.tsx` has a "Your delegation" card
|
||||
(`assembly-delegate-select` / `assembly-delegate-submit` /
|
||||
`assembly-revoke-delegation`) calling `useAssemblyEngine`'s `delegate` /
|
||||
`revokeDelegation`, which call `putDelegation` / `removeDelegation`
|
||||
directly. Casting your own ballot and having an active delegation are
|
||||
mutually exclusive in the UI (`canVoteDirectly = isEnrolled &&
|
||||
myDelegation === undefined`), matching the documented "delegation is
|
||||
global, not per-proposal" semantics.
|
||||
|
||||
Verdict: liquid democracy is a real, correctly-implemented, UI-reachable
|
||||
mechanism - transitive, cycle-safe, distinct from the QV ballot/credit
|
||||
mechanism it sits on top of. No gap here.
|
||||
|
||||
## 2(a). Local-first layer - REAL
|
||||
|
||||
`useAssemblyEngine` persists the `AssemblyDoc`/`GovernanceDoc` via
|
||||
`openPersistedAssemblyDoc` (`y-indexeddb`), re-renders on `doc.on("update")`,
|
||||
and exposes a `synced` flag read directly off `IndexeddbPersistence.synced`
|
||||
(never hard-coded). Proposals, roster, delegations, credits all live in the
|
||||
Yjs CRDT and work with the WebRTC sync toggle permanently off - the toggle
|
||||
defaults to `false` ("Assembly stays fully offline/local-first until a
|
||||
resident opts in", per the hook's own doc comment). Genuine zero-network
|
||||
operation.
|
||||
|
||||
## 2(b). WebRTC partition-and-heal layer - REAL and wired
|
||||
|
||||
`src/lib/assemblySync.ts`'s `connectAssemblySync` wraps a genuine
|
||||
`y-webrtc` `WebrtcProvider` (real signaling + RTCDataChannel transport, not
|
||||
a stub) with a self-hostable default signaling URL
|
||||
(`VITE_SIGNALING_URL` / `ws://localhost:4444`) and an opt-in third-party
|
||||
fallback. `useAssemblyEngine` wires this to a real "Sync with devices using
|
||||
the same code" toggle in `AssemblyScreen.tsx` with a live peer count
|
||||
(`connectedPeerCount()`, never fabricated - stays honestly 0 when
|
||||
partitioned or when `RTCPeerConnection` is undefined, e.g. in tests).
|
||||
|
||||
This is independently confirmed by prior work in this repo: gate review
|
||||
`.omo/evidence/the-commons-hollow-polish/task-11-the-commons-hollow-polish-gate-review.md`
|
||||
documents a Playwright test driving two isolated browser contexts through
|
||||
the *shipped* screen's own UI - connect over real WebRTC, prove a proposal
|
||||
seeded on side A arrives on side B, partition (toggle off + `setOffline`,
|
||||
tearing the real `RTCDataChannel`), independent proposals on each side
|
||||
proven not to cross, heal (toggle on + network restored), and converge to
|
||||
the identical union set. `service-sync-reevaluation.md` separately verdicts
|
||||
this "works as claimed." This layer is genuine and demonstrable end-to-end
|
||||
through the real UI, not a console-only harness.
|
||||
|
||||
## 2(c) / 3. QR-sneakernet layer - GAP FOUND: real transport, zero UI wiring, camera never reachable
|
||||
|
||||
`src/lib/qrSneakernet.ts` is a genuinely well-built transport:
|
||||
|
||||
- `encodeDelta` / `decodeFrames` / `FrameCollector` chunk a real Yjs CRDT
|
||||
delta (`Y.encodeStateAsUpdate`) into self-describing frame strings with
|
||||
per-frame CRC32, sequence/total, and whole-delta length+CRC32 (so a
|
||||
misread, dropped, or cross-transfer frame is detected rather than
|
||||
silently corrupting the reassembly).
|
||||
- `renderFrameToDataURL` / `renderFramesToDataURLs` use the real `qrcode`
|
||||
package to render actual QR code images.
|
||||
- `scanFrameFromImage` uses the real `jsQR` package against a
|
||||
`CameraImage { data, width, height }` (the exact shape `canvas.getImageData`
|
||||
produces) - this is a genuine QR decode, not a copy-paste text blob.
|
||||
- The task-24 build evidence
|
||||
(`.omo/evidence/the-commons-hollow/task-24-the-commons-hollow.json`)
|
||||
confirms a real round-trip: a 17,779-byte Yjs delta (well over one QR's
|
||||
~2.9KB capacity) chunked into 35 frames, reassembled out-of-order with a
|
||||
dropped-then-retried frame, byte-for-byte equal to the original, then
|
||||
applied to a target `Y.Doc` via `Y.applyUpdate` - genuinely exercising the
|
||||
CRDT, not a toy string.
|
||||
|
||||
**But it is never called from anywhere outside its own test file.** Grep
|
||||
across `src/` for `qrSneakernet|scanFrameFromImage|FrameCollector|encodeDelta|decodeFrames`
|
||||
and across `src/miniapps` for `qrSneakernet` turns up matches only in
|
||||
`qrSneakernet.ts` itself and `qrSneakernet.test.ts`; `miniappSharing.ts`
|
||||
mentions it only in a comment ("Assembly's QR-sneakernet transport ... kept
|
||||
independent here"), never an import. `AssemblyScreen.tsx` / `useAssemblyEngine.ts`
|
||||
import `QRCode` from the `qrcode` package directly, but only to render the
|
||||
WebRTC **sync-room-code string** as a QR code (`QRCode.toDataURL(syncRoomCode, ...)`)
|
||||
- a plain text room-id QR, unrelated to `qrSneakernet.ts` and carrying no
|
||||
Yjs delta at all. `encodeAssemblyState` / `applyAssemblyUpdate`
|
||||
(`src/lib/assembly.ts`, the functions `qrSneakernet.ts`'s own header says
|
||||
callers should pair it with) are likewise used only in `assembly.test.ts`
|
||||
and `assemblySync.test.ts` - never in a mini-app screen.
|
||||
|
||||
There is also no `getUserMedia` / `BarcodeDetector` / any camera API call
|
||||
anywhere in `src/` (confirmed by grep: zero matches). The task-24 evidence
|
||||
file says this explicitly under its own `real_qr_packages_wired.camera_note`:
|
||||
*"no real camera needed for the acceptance tests ... `scanFrameFromImage` is
|
||||
the production jsQR entry point a `<video>`->canvas pipeline feeds"* - i.e.
|
||||
the `<video>`-to-canvas pipeline that would make a camera scan reachable was
|
||||
never built. This was also already flagged as an open item in this
|
||||
project's own planning history: `.omo/plans/the-commons-hollow.md` line 748
|
||||
calls for exercising "the QR-sneakernet path (todo 24) with a real camera on
|
||||
a real device at least once (plan-consultant finding F4 - no automated test
|
||||
touches an actual camera)" - that follow-up was never done, and no UI
|
||||
affordance to even attempt it (an "Export sync code via QR" / "Scan a
|
||||
device's QR" button pair for the Assembly CRDT state) exists in
|
||||
`AssemblyScreen.tsx` today.
|
||||
|
||||
Answering the audit's specific question 3 directly: **the camera is never
|
||||
invoked anywhere in the shipped app for this purpose.** QR-sneakernet is
|
||||
tested only via hand-built `Uint8Array` deltas and synthetic RGBA bitmaps in
|
||||
`qrSneakernet.test.ts`, never reachable through a real camera scan in the UI.
|
||||
|
||||
## 4. Claimed-but-unwired UI/feature summary
|
||||
|
||||
| Claim | Status |
|
||||
|---|---|
|
||||
| Liquid-democracy delegation (transitive, cycle-safe) | Wired, real, reachable |
|
||||
| WebRTC partition-and-heal | Wired, real, reachable (Playwright-proven through the shipped screen) |
|
||||
| QR-sneakernet air-gapped CRDT transport | **Built but completely unwired** - zero production callers, no camera pipeline, no UI entry point |
|
||||
|
||||
## Verdict: GAP-FOUND (one layer of three)
|
||||
|
||||
Two of the three claimed resilience layers (local-first, WebRTC
|
||||
partition-and-heal) and the liquid-democracy tally are coherent: genuinely
|
||||
implemented, UI-reachable, and independently verified by this project's own
|
||||
prior Playwright evidence. The third layer, QR-sneakernet, is a real,
|
||||
carefully-engineered, well-tested transport module (`src/lib/qrSneakernet.ts`,
|
||||
9 passing unit tests, a documented 17.7KB real-delta round-trip) that is
|
||||
**completely disconnected from the shipped app** - exactly the "claimed but
|
||||
unwired" pattern the audit was looking for. The README's "3-layer resilience
|
||||
model ... QR-sneakernet air-gapped fallback" phrasing therefore overstates
|
||||
what a user can actually do: there is no way, today, to open the Assembly
|
||||
screen and move governance state between two air-gapped devices by camera.
|
||||
|
||||
**Exact gap location:** `src/lib/qrSneakernet.ts` (fully built, zero
|
||||
non-test importers) vs `src/miniapps/assembly/AssemblyScreen.tsx` /
|
||||
`useAssemblyEngine.ts` (no import of `qrSneakernet.ts`, `encodeAssemblyState`,
|
||||
or `applyAssemblyUpdate`; no `<video>`/`getUserMedia` anywhere in the file).
|
||||
|
||||
**Effort-size honesty, per the project's own standing preference for a real
|
||||
fix over a half measure:** wiring this is a genuinely larger scope item than
|
||||
a quick fix, but it is buildable now with code that already exists -
|
||||
nothing novel needs inventing:
|
||||
1. An "Export state as QR" control: call `encodeAssemblyState(assembly)`,
|
||||
feed the bytes through `encodeDelta`, animate the resulting frames with
|
||||
`renderFramesToDataURLs` (all three functions already exist and are
|
||||
tested).
|
||||
2. A "Scan a device's QR" control: a `<video>` element + `getUserMedia`
|
||||
(camera permission) + a canvas `drawImage`/`getImageData` loop feeding
|
||||
`scanFrameFromImage` into a `FrameCollector`, then
|
||||
`applyAssemblyUpdate(assembly, collector.reassemble())` once complete -
|
||||
this is the one genuinely new piece (the camera capture loop itself;
|
||||
`getUserMedia` appears nowhere in this codebase today, so it would need
|
||||
its own permission-prompt/error-handling UI, unlike the already-proven
|
||||
encode half).
|
||||
3. Manual QA with a real camera on a real device (the plan's own
|
||||
previously-flagged, never-closed F4 item).
|
||||
|
||||
This is a multi-hour UI task (new component + permission flow + a manual
|
||||
camera QA pass), not a one-line fix - but it is well within reach given the
|
||||
transport layer is already complete and tested. The alternative - correcting
|
||||
the README to describe QR-sneakernet as "a built, tested, not-yet-wired
|
||||
transport" rather than a working third resilience layer - is the honest
|
||||
stopgap if this item is deprioritized, but given the module is this close to
|
||||
done, wiring it is the better fix and should not be quietly downgraded to a
|
||||
documentation change.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Coherence Audit: Fair Draw (ma-fairdraw)
|
||||
|
||||
**Scope:** `src/miniapps/fairdraw/`, `src/lib/fairdraw.ts`, cross-app integration in `src/lib/theclimb.ts`.
|
||||
**Claim under test (README.md:97):** "Fair Draw (ma-fairdraw): Commit-reveal lottery engine; its tie-break utility is reused by other mini-apps that need a provably unriggable draw" (answers P14).
|
||||
|
||||
## Verdict: COHERENT
|
||||
|
||||
The commit-reveal cryptography is sound for what it actually promises (tamper-evidence after publication, not multi-party grinding-resistance), the draw outcome is a deterministic pure function of the revealed seed, the cross-app reuse by The Climb is a real import/call (not a README-only claim), and there is correctly no device-sensor input anywhere in the randomness path. One caveat is worth flagging to the user even though it does not break the verdict: the module's own docstring explicitly scopes out solo-party seed grinding before publication, which is a narrower guarantee than "provably unriggable" might suggest to a reader who skips the fine print.
|
||||
|
||||
---
|
||||
|
||||
## 1. Is commit-reveal genuinely cryptographically sound?
|
||||
|
||||
**Yes.** `src/lib/fairdraw.ts`:
|
||||
|
||||
- `commit(seed, salt)` (lines ~70-78) hashes `seed+salt` with the real Web Crypto `crypto.subtle.digest("SHA-256", ...)` — not a mock, not `Math.random()`-seeded, not a stub. The message is length-prefixed per field (`commitMessage`, lines ~50-58: `` `${seedBytes.length}:${seed}:${saltBytes.length}:${salt}` ``) specifically to close a real ambiguity bug: a naive `${seed}:${salt}` join lets `("7","x:9")` and `("7:x","9")` collide on the same byte string. `fairdraw.test.ts` ("closes the seed/salt separator collision", lines 44-63) proves both that the collision no longer occurs and that each commit does NOT verify against the other pair's reveal — i.e. a drawer cannot commit once and later choose whichever of two ambiguous splits favors them.
|
||||
- `verifyCommit`/`verify` (lines ~95-104) recomputes `commit(revealedSeed, revealedSalt)` and does a strict string-equality check against the published `commitHash`, returning `false` (never throwing) on any mismatch. Proven in tests: "fails verify() visibly for a tampered reveal with the wrong seed" and "...wrong salt" (fairdraw.test.ts lines 33-41), plus "fairdraw QA - failure path" (lines 101-111) using an attacker-chosen seed.
|
||||
- Call-site ordering is enforced, not just advisory: `RevealDraw.tsx`'s `startDraw()` publishes the commit to the signed Event Log via `append()` and then re-reads it back with `readAll()` before the UI even unlocks the Reveal button (lines ~195-212: "Gate on a fresh readAll() actually finding the commit entry... this is what makes the commit auditable after a reload between commit and reveal"). `revealDraw()` only computes `verified`/`winner` after `verify()` resolves (lines ~222-230) — the winner is never rendered optimistically.
|
||||
- `validateReveal()` (fairdraw.ts lines ~230-270) is an independent, replay-only auditor over the raw Event Log: it requires (a) a `fairdraw.commit` exists for the drawId, (b) exactly one `fairdraw.reveal` exists (zero = not yet revealed, two+ = a re-roll attempt, both rejected), (c) the reveal's `lamportTs` is strictly greater than the commit's, and (d) `verify()` passes. All four branches are covered by dedicated tests in `fairdraw.test.ts` ("rejects a reveal with no prior commit", "rejects a second reveal...", "rejects when reveal's lamportTs is not strictly after its commit's", "rejects when the reveal does not verify..., tampered seed", plus a cold-replay-snapshot test and a canonical-earliest-commit test for duplicate commits). `RevealDraw.tsx` wires this into the UI as a live "Draw integrity: valid / rejected" badge (lines ~280-290), not just a backend check nobody surfaces.
|
||||
|
||||
## 2. Is the draw outcome genuinely derived from the committed value, and can a party bias it?
|
||||
|
||||
**Derivation is sound; the honest documented limitation is solo-grinding, not post-commit bias.**
|
||||
|
||||
- `drawOutcome(seed, optionCount)` (fairdraw.ts lines ~155-175) re-hashes `"draw:" + seed` with SHA-256, folds all 32 digest bytes into a BigInt, and reduces mod `optionCount` — so the outcome depends on the whole hash (not a truncated, more-guessable slice), and is reproducible: same seed + optionCount always gives the same index (proven in "fairdraw QA - happy path", fairdraw.test.ts lines 85-99, `outcomeA === outcomeB`).
|
||||
- Because `drawOutcome` is only ever invoked in `revealDraw()` *after* `verify()` has passed (RevealDraw.tsx `const winnerIndex = verified ? await drawOutcome(...) : undefined`), a tampered/mismatched reveal can never produce a winner — a false `verify()` short-circuits straight to `winnerIndex = undefined` and the "Invalid" badge, never a credited prize.
|
||||
- **Documented, correct scope limit** (fairdraw.ts module docstring, "Append-to-log payload shapes" section): "This is explicitly NOT a multiparty commit protocol... a solo drawer can still grind outcomes offline before ever publishing a commit... only re-rolling AFTER a commit is published becomes auditable and rejectable." That is: the single local-identity drawer chooses seed/salt before committing and could in principle try several off-the-record seed/salt pairs before ever calling `commit()` — nothing stops private pre-commit grinding by the one party who initiates the draw, and nothing stops them from simply never revealing a commit they don't like (an abort, not a bias). What the protocol *does* guarantee, and what is tested, is that once a commit is published, that specific draw's revealed seed cannot be swapped for a more-favorable one — `validateReveal`'s tests above cover exactly this. **This is a correctly-scoped, explicitly-disclosed limitation, not a hidden gap** — but README's one-line "provably unriggable draw" phrasing is a looser gloss than the in-code spec. Worth tightening the README language (e.g. "tamper-evident after publication") if advisory follow-up is wanted; not a code defect.
|
||||
- In **The Climb's** reuse (`src/lib/theclimb.ts`), the limitation above is actually closed: `deriveTieBreakSeed`/`deriveTieBreakSalt` (lines ~215-221) derive the seed/salt purely from `planInputsHash` (a SHA-256 over the already-signed, already-committed plan content) plus the contested slot's node/distance/iteration — there is **no freely-chosen value for anyone to grind**, random or otherwise ("Nothing random ever enters it" per the `hashScheduleInputs` docstring). The draw-affecting information (the plan) is locked in and hashed before any tie-break seed exists, which is a stronger non-grindable design than fairdraw's own standalone demo screen.
|
||||
|
||||
## 3. Is the "tie-break utility is reused by other mini-apps" claim real?
|
||||
|
||||
**Yes, genuinely wired — a real import and function call, not a README-only claim.**
|
||||
|
||||
- `src/lib/theclimb.ts` line 32: `import { commit, drawOutcome, reveal, verify } from "./fairdraw";` — a direct module import, no indirection/registry.
|
||||
- `createLoggingTieBreaker()` (theclimb.ts lines ~255-305) calls `commit()`, `reveal()`, `verify()`, and `drawOutcome()` from fairdraw.ts in the correct commit-before-reveal order, publishing `theclimb.tiebreak.commit` and `theclimb.tiebreak.reveal` events to the same signed Event Log, and **fails closed** if `verify()` ever returns false (`throw new Error("...refusing to resolve a contested wave-slot tie without a verifiable draw")`).
|
||||
- The min-cost-flow engine's path-reconstruction code (`findAugmentingPath`/`reconstruct`, lines ~440-480) calls `tieBreaker.resolve(viable.length, {...})` exactly at the point where more than one tied predecessor edge is found for a contested wave slot, and the function docstring states "It never falls back to array order or any ad hoc ordering of its own; if the injected Fair Draw integration throws, that error propagates (fails closed)". This is corroborated by this session's separate cross-device-sync audit finding (referenced in the task) that `theclimb.tiebreak` wiring is real.
|
||||
- `verifyClimbTieBreakAudit()` (theclimb.ts, final function) independently re-verifies every `theclimb.tiebreak.reveal` against its matching `theclimb.tiebreak.commit` using fairdraw's own `verify()` and `drawOutcome()` — a second, auditor-facing integration point, not just the draw-time call.
|
||||
|
||||
## 4. Device-API angle?
|
||||
|
||||
**None found, correctly.** Grepped `src/lib/fairdraw.ts`, `src/miniapps/fairdraw/RevealDraw.tsx`, and `src/lib/theclimb.ts` for `geolocation`, `DeviceMotion`, `DeviceOrientation`, `accelerometer`, and generic `navigator.*` calls — zero matches. The only entropy source is `crypto.getRandomValues()` (`randomSeedSalt()` in RevealDraw.tsx, a real non-mocked CSPRNG call documented as "Real (non-mocked) randomness source for the seed/salt a draw commits to"), and in The Climb's reuse there is no randomness at all (deterministic hash of committed plan data). This is the **correct** design: a sensor-based entropy source would be unverifiable by other parties and would *weaken*, not strengthen, the provable-fairness property this app exists to deliver.
|
||||
|
||||
## 5. Any claimed-but-unwired UI/feature?
|
||||
|
||||
**None found.** The "re-rolling after the commit is published is auditable and rejected" subtitle text in `RevealDraw.tsx` is backed by the live `validateReveal()` call and its integrity badge (section 1 above) — not an aspirational claim with no enforcement. The component is mounted in the shell registry (`src/shell/miniappComponents.tsx` imports `fairdraw`), and `FairDraw()` wires the real local identity's account id into participant index 0 via `useActiveAccountId()` so a genuine win credits the real wallet through a real `wallet.issue` event (not a fabricated/demo-only credit) — `DEMO_NEIGHBOR_ACCOUNTS` are explicitly documented as never backing a real identity and never read by `WalletCard`, which matches their only use (symbolic opponents in the fixed 5-slot roster).
|
||||
|
||||
## Evidence index
|
||||
- `src/lib/fairdraw.ts` — commit/reveal/verify/drawOutcome/validateReveal, SHA-256 via Web Crypto, length-prefixed canonical encoding.
|
||||
- `src/lib/fairdraw.test.ts` — property test (100 random seed/salt pairs), tamper-rejection tests, separator-collision regression test, full `validateReveal` branch coverage including cold-replay and canonical-earliest-commit cases.
|
||||
- `src/miniapps/fairdraw/RevealDraw.tsx` — UI wiring: real `crypto.getRandomValues` seed/salt, commit-before-reveal-button gating via `readAll()` confirmation, live integrity badge from `validateReveal()`, real wallet credit via `append({type:"wallet.issue",...})`.
|
||||
- `src/lib/theclimb.ts` — real `import {...} from "./fairdraw"`, `createLoggingTieBreaker` (commit/reveal/verify/drawOutcome call chain, fail-closed on verify failure), `fairDrawTieBreaker` deterministic default, `verifyClimbTieBreakAudit` independent re-verification.
|
||||
- `README.md:97-98` — the two claims under test (P14 Fair Draw, P15 The Climb "calling Fair Draw for contested wave slots").
|
||||
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 145 KiB |
@@ -0,0 +1,165 @@
|
||||
# Fair Share (`ma-fairshare`) coherence audit
|
||||
|
||||
**Scope:** `src/miniapps/fairshare/*`, `src/lib/fairshare.ts`, `src/lib/ceeiSpike.ts`, plus the
|
||||
cross-app writers in `src/miniapps/waterwatch/corroboration.ts` and `src/lib/farms.ts`.
|
||||
|
||||
**README claim under test** (Problem-to-mini-app table, P1/P2/P3 row):
|
||||
|
||||
> Fair Share (`ma-fairshare`): Competitive-Equilibrium-from-Equal-Incomes (CEEI) allocator
|
||||
> across power, water, food, and cooling; envy-free, Pareto-efficient, with a real
|
||||
> allocation-history trend as the honest early-warning signal (no fabricated sensor)
|
||||
|
||||
**Verdict: GAP-FOUND** (one real, narrow gap; everything else is COHERENT). The gap is not a
|
||||
fabrication risk — the code is honest where it falls short — but the README's trend claim
|
||||
overstates what two of the four resources can ever show.
|
||||
|
||||
---
|
||||
|
||||
## Clause 1 — Is there a genuine CEEI algorithm, not a stand-in?
|
||||
|
||||
**COHERENT.** `src/lib/ceeiSpike.ts` implements two cross-validated Fisher-market solvers:
|
||||
`solveCeeiPriceSearch` (bisection tâtonnement over `javascript-lp-solver` LPs, 2-good spike) and
|
||||
`solveCeeiWaterFilling` (proportional-response dynamics, arbitrary agents/goods — lines 182-234).
|
||||
Proportional-response dynamics is a textbook algorithm that provably converges to the Fisher
|
||||
(CEEI) equilibrium for linear utilities; `ceeiSpike.test.ts` cross-checks it against a
|
||||
closed-form 2-good instance.
|
||||
|
||||
The production engine, `computeFairshareAllocation` in `src/lib/fairshare.ts` (lines 299-427),
|
||||
calls `solveCeeiWaterFilling` directly (never the 2-good-only `solveCeei` orchestrator), with
|
||||
every agent given an equal budget of `1` (line ~397: `const budgets = agents.map(() => 1)`) —
|
||||
that single shared per-agent budget spent jointly across whichever resources have residual
|
||||
supply is exactly the "equal income" half of CEEI; the water-filling fixed point is the
|
||||
"competitive equilibrium" half. This is a real convex-program solver, not a simplified
|
||||
proportional-split stand-in.
|
||||
|
||||
## Clause 2 — Does it allocate across all 4 named resources?
|
||||
|
||||
**COHERENT.** `FAIRSHARE_RESOURCES = ["power", "water", "food", "cooling"]`
|
||||
(`src/lib/fairshare.ts` line 59). `computeFairshareAllocation` builds the `utilityMatrix` /
|
||||
`supplyVector` over whatever subset of these four has positive residual supply after floor
|
||||
reservation (lines ~380-410) and feeds them to the *same* water-filling solve as one joint
|
||||
market — not four independent single-good solves. `ResourceTiles.tsx` renders all four tiles
|
||||
(`RESOURCE_META` covers power/water/food/cooling) and `ResourceTiles.test.tsx`'s
|
||||
"4-resource allocation cycle" test seeds all four and asserts correct allocation on each tile.
|
||||
|
||||
## Clause 3 — Is the allocation-history trend real, not fabricated?
|
||||
|
||||
**COHERENT for water and food; GAP for power and cooling.** `getAllocationHistory` /
|
||||
`computeAllocationTrend` (`src/lib/fairshare.ts` lines 470-537) replay only real, signed
|
||||
`fairshare.allocation.cycle` events in Lamport order and honestly report `"no-trend-yet"` below
|
||||
2 points — no interpolation, no synthesized default, no random number. `TrendChart.tsx` renders
|
||||
exactly those points and only shows the "declining" early-warning badge when a real negative
|
||||
OLS slope exists (never for `no-trend-yet` or a flat/rising trend). This part of the claim is
|
||||
real.
|
||||
|
||||
**But** `fairshare.allocation.cycle` events are only ever appended from two places in
|
||||
non-test code (confirmed by `grep -rln 'fairshare.allocation.cycle' src | grep -v '.test.'`):
|
||||
|
||||
- `src/miniapps/waterwatch/corroboration.ts` → `settleCorroboratedReading` (resource
|
||||
`"water"` only, line ~282), wired to the UI via `ReportReadingForm.tsx` line 84.
|
||||
- `src/lib/farms.ts` → `settleFarmsForecast` (resource `"food"` only, line ~396), wired to the
|
||||
UI via `FarmsScreen.tsx`'s `useEffect` (lines ~47-69).
|
||||
|
||||
**No code path anywhere — not `ResourceTiles.tsx`, not the admin seed panel
|
||||
(`src/admin/seedEvents.ts`), not `fairshare.ts` itself — ever appends a
|
||||
`fairshare.allocation.cycle` event for `"power"` or `"cooling"`.** `postFairshareNeed`
|
||||
(`src/lib/fairshare.ts` line 225) only writes a `fairshare.need` event; it never records a
|
||||
cycle. `postFairshareFloor` only writes `fairshare.floor`. `seedEvents.ts` writes
|
||||
`seed.resource.<resource>` baselines for all four resources but no `fairshare.allocation.cycle`
|
||||
for any of them. So `TrendChart` for `power` and for `cooling` is structurally guaranteed to
|
||||
render `"no-trend-yet"` forever in the shipped app, no matter how many needs/seeds are posted —
|
||||
confirmed by `ResourceTiles.test.tsx`'s own coverage, which only ever drives `power` through the
|
||||
tile-allocation assertions (lines 63-110), never through a trend-chart assertion, and no test
|
||||
anywhere seeds a `power`/`cooling` `fairshare.allocation.cycle`.
|
||||
|
||||
This means the README's "real allocation-history trend as the honest early-warning signal"
|
||||
genuinely holds for 2 of the 4 resources it's claimed across (water via Water Watch,
|
||||
food via Farms) but is dead code for power and cooling — the two resources P1/P3 (warn before
|
||||
power cuts; keep lower levels livable) most directly concern. It degrades gracefully (an honest
|
||||
empty state, never a fabricated line), so this is **not** a "no fabricated data" violation, but
|
||||
it is a scope gap against the literal README claim.
|
||||
|
||||
**Concrete fix:** add a cycle-recording call inside `ResourceTiles.tsx` (or a shared helper in
|
||||
`fairshare.ts`, e.g. `settleAllocationCycle(resource, entries)` mirroring
|
||||
`settleCorroboratedReading`/`settleFarmsForecast`'s shape) that fires once per resource whenever
|
||||
`computeFairshareAllocation`'s `totalAllocated` for that resource changes meaningfully (same
|
||||
"new value, not a re-render echo" guard `FarmsScreen.tsx` already uses via
|
||||
`lastSettledForecastRef`), driven off the admin seed panel's `seed.resource.power` /
|
||||
`seed.resource.cooling` writes the same way Water Watch/Farms drive water/food. That is a
|
||||
same-shape, in-repo pattern extension, not a new mechanism.
|
||||
|
||||
## Clause 4 — Real cross-app wiring from Water Watch and Farms?
|
||||
|
||||
**COHERENT.** Both chains are live, not just claimed:
|
||||
|
||||
- Water Watch: `applyCorroboratedReadingToFairshare` (`corroboration.ts` line ~227) appends a
|
||||
real `seed.resource.water` event only on a corroborated `"alert"` `GateEvent` (an uncorroborated
|
||||
`"clean"`/`"corroborating"` reading is a provable no-op per the function's own guard).
|
||||
`settleCorroboratedReading` then re-reads the full log, re-solves via
|
||||
`computeFairshareAllocation`, and appends the water `fairshare.allocation.cycle`. This is
|
||||
called from the real UI in `ReportReadingForm.tsx` line 84 — not just a library function left
|
||||
unwired.
|
||||
- Farms: `applyFarmsForecastToFairshare` (`src/lib/farms.ts` line 341) appends a real
|
||||
`fairshare.contribution` (additive, never overwriting, per `fairshare.ts`'s
|
||||
`FairshareContributionPayload` doc) only when the LP optimizer reaches `status: "optimal"`
|
||||
with real entered temperature/plot/crop data. `settleFarmsForecast` then re-solves and appends
|
||||
the food `fairshare.allocation.cycle`. Called from `FarmsScreen.tsx`'s `useEffect` (fires only
|
||||
on a genuinely new `totalForecastYieldKg`, guarded by `lastSettledForecastRef` so it never
|
||||
re-fires on an unchanged value across re-renders).
|
||||
|
||||
`coreLoopHonestyAnchor.test.tsx` (Water Watch) and `coreLoopFoodIntegration.test.tsx` (Farms)
|
||||
exercise these full chains end-to-end against the real `fairshare.ts` engine; all 30 relevant
|
||||
tests pass (`npx vitest run src/lib/fairshare.test.ts src/lib/ceeiSpike.test.ts
|
||||
src/miniapps/waterwatch/coreLoopHonestyAnchor.test.tsx
|
||||
src/miniapps/farms/coreLoopFoodIntegration.test.tsx` → 4 files, 30 tests, all passed).
|
||||
|
||||
## Clause 5 — Would a real device/browser API strengthen this concept?
|
||||
|
||||
**Honest answer: no, and the README already says so correctly.** Resource-allocation math (CEEI
|
||||
over reported needs/supplies) has no sensor to attach — a CEEI solve runs over typed
|
||||
need/supply numbers, and no phone API measures "need for food" or "ambient livability." The
|
||||
README's own "What this does NOT do" section is explicit that Light Clock is the *only* mini-app
|
||||
with a real device sensor (motion/actigraphy), and that nothing else gets a fabricated one.
|
||||
Network/battery status (`navigator.onLine`, Battery Status API — now largely deprecated/removed
|
||||
from most browsers) could theoretically flavor an "early warning" banner during an outage, but
|
||||
would add a cosmetic indicator unconnected to the actual CEEI math or the signed event log, and
|
||||
the Battery Status API is not available in current Chromium/Firefox for most origins — forcing it
|
||||
in would be exactly the kind of invented sensor fit the project's own anti-pattern list forbids.
|
||||
Correctly, no sensor API is used or claimed here, and none should be added.
|
||||
|
||||
## Clause 6 — Does the UI/data flow deliver the claims coherently, no dead ends?
|
||||
|
||||
**COHERENT except for the clause-3 gap already named.** `ResourceTiles.tsx`:
|
||||
- Resource-credit balance: read verbatim from `ledger.ts`'s `computeBalances`/`balanceOf`
|
||||
(never reimplemented locally) — honest "No balance yet" / "--" states, no fabricated 0.
|
||||
- Per-resource tiles: read verbatim from `computeFairshareAllocation`'s live-replayed
|
||||
`allocation`/`supply`, bar-fill fraction computed from real numbers, honest "No allocation
|
||||
yet" when the signed-in agent has never reported a need.
|
||||
- "Report your need" form: calls real `postFairshareNeed` → signed `fairshare.need` append;
|
||||
`useEventLogEntries`'s Dexie `liveQuery` means the whole screen (tiles, trend charts) reacts
|
||||
immediately once that event lands — not a stale/cached read.
|
||||
- Trend charts: real for water/food (see Clause 3), honestly empty for power/cooling rather
|
||||
than a dead button or a silently-broken chart — no copy asserts a trend exists when it
|
||||
cannot.
|
||||
|
||||
No button submits to nowhere, no claimed feature is literally unimplemented; the one gap is a
|
||||
narrower scope for the trend signal than the README's four-resource framing implies.
|
||||
|
||||
---
|
||||
|
||||
## Summary verdict
|
||||
|
||||
**GAP-FOUND, narrow and non-fabrication:** the CEEI allocator itself (Clauses 1, 2, 4, 6) and
|
||||
the "no fabricated sensor" honesty (Clause 5) are fully coherent and well-evidenced in real code
|
||||
and passing tests. The one real gap is Clause 3: `fairshare.allocation.cycle` — the event type
|
||||
the trend/early-warning mechanism is built on — is only ever written for `water` (via Water
|
||||
Watch) and `food` (via Farms); no code path writes it for `power` or `cooling`, so those two
|
||||
resources' trend charts are permanently stuck at the honest "no trend yet" empty state in the
|
||||
shipped app. Since P1 ("warn before power cuts") is squarely a power-resource claim, this
|
||||
materially narrows the README's stated early-warning mechanism for exactly the problem it's
|
||||
positioned to answer. Fix: wire a `fairshare.allocation.cycle` write for power/cooling the same
|
||||
way Water Watch/Farms already do for water/food — e.g. from `ResourceTiles.tsx` or a shared
|
||||
`fairshare.ts` helper, triggered off a genuinely new `computeFairshareAllocation` total per
|
||||
resource (reusing the `lastSettledForecastRef`-style "new value only" guard already proven in
|
||||
`FarmsScreen.tsx`). This is a same-shape extension of an existing, tested pattern, not a new
|
||||
mechanism or an invented sensor.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Coherence Audit: Farms (ma-farms)
|
||||
|
||||
**Scope:** `src/miniapps/farms/*`, `src/lib/farms.ts`, package.json dependency check.
|
||||
**README claim (P12 row, verbatim):** "Growing-degree-day model plus an LP planting optimizer under a fixed grow-light power budget, feeding Fair Share's food number"
|
||||
|
||||
## 1. GDD model - genuine agronomic calculation
|
||||
|
||||
**VERIFIED GENUINE.**
|
||||
|
||||
`src/lib/farms.ts`, `dailyGddValue()` (lines ~75-80) and `computeGdd()` (lines ~91-108):
|
||||
|
||||
```ts
|
||||
export function dailyGddValue(entry: TemperatureEntry, baseTempC: number): number {
|
||||
const meanTemp = entry.tmax / 2 + entry.tmin / 2;
|
||||
return Math.max(0, meanTemp - baseTempC);
|
||||
}
|
||||
```
|
||||
|
||||
This is the textbook average-method GDD formula: `max(0, (tmax+tmin)/2 - baseTempC)`, accumulated per day and summed across a date-sorted series (`cumulativeGdd`). `baseTempC` is a required caller-supplied crop parameter, not a magic constant baked into the formula. `computeGdd` returns an explicit `{ insufficientData: true }` sentinel (never a fabricated 0) when no entries exist - no arbitrary growth-rate number is being mislabeled as GDD.
|
||||
|
||||
`CropMaturityWindow.maturityGdd` (the crop's GDD-to-maturity threshold) is a second real, caller-supplied field used downstream in `solveFarmsPlantingOptimizer` to filter crops: `crops.filter((crop) => crop.maturityGdd <= cumulativeGdd)` (line ~242). A crop that cannot mature within the season's accumulated heat units never gets an LP variable.
|
||||
|
||||
## 2. LP planting optimizer - genuine LP solve
|
||||
|
||||
**VERIFIED GENUINE.**
|
||||
|
||||
- `package.json` line 19: `"javascript-lp-solver": "^1.0.3"` - real npm dependency, not vendored/stubbed.
|
||||
- `src/lib/farms.ts` imports `solver, { type ConstraintBound, type Model as LpModel, type SolveResult as LpSolveResult } from "javascript-lp-solver"` (top of file) and calls it for real at line ~287:
|
||||
|
||||
```ts
|
||||
const model: LpModel = {
|
||||
optimize: "yield",
|
||||
opType: "max",
|
||||
constraints,
|
||||
variables,
|
||||
};
|
||||
const result = solver.Solve(model) as LpSolveResult;
|
||||
if (!result.feasible) { ... }
|
||||
```
|
||||
|
||||
Decision variables are one per (plot, eligible-crop) pair, each carrying a `yield` coefficient and membership in a `plot:<id>` area constraint (`{max: plot.areaM2}`), an optional `crop:<id>` seed-stock cap, and an optional `energy` coefficient. This is a real bounded-area allocation LP maximizing total yield subject to per-plot area ceilings, per-crop area caps, and an energy ceiling - not a greedy/sorted heuristic. Infeasible solves return an honest `{ status: "infeasible", reason }`, never a forced schedule.
|
||||
|
||||
## 3. "Fixed grow-light power budget" - GAP: disconnected from Fair Share
|
||||
|
||||
**GAP FOUND.** The budget is real as an LP constraint, but it is **not** "fixed" or sourced from Fair Share's actual power allocation/supply state - it is a free-text, caller-typed number scoped only to the Farms screen, fully independent of Fair Share's power resource.
|
||||
|
||||
Evidence:
|
||||
- `src/lib/fairshare.ts` line 52: `export const FAIRSHARE_RESOURCES = ["power", "water", "food", "cooling"] as const;` and `computeFairshareAllocation()` (line ~305) computes a real `supply.power` / per-agent `allocation[agent].power` from the signed Event Log (CEEI solve) - i.e. a real, live, shared power-budget figure exists in this app.
|
||||
- `src/miniapps/farms/FarmsScreen.tsx` lines 32-41:
|
||||
```ts
|
||||
const [energyBudgetInput, setEnergyBudgetInput] = useState("");
|
||||
const parsedBudget = Number(energyBudgetInput);
|
||||
const energyBudgetKwh = energyBudgetInput.trim() !== "" && Number.isFinite(parsedBudget) && parsedBudget >= 0
|
||||
? parsedBudget : undefined;
|
||||
const computation = solveFarmsPlantingOptimizer({ gdd, plots, crops, energyBudgetKwh });
|
||||
```
|
||||
and lines 85-97 render it as a plain `<input type="number">` labeled "Grow-light power budget (kWh, optional)" with placeholder "unlimited".
|
||||
- A repo-wide grep (`grep -rn 'energyBudget|powerBudget|grow-light|growLight' src --include='*.ts' --include='*.tsx'`, excluding tests) found zero call sites reading `computeFairshareAllocation(...).allocation[...].power` or `.supply.power` into `energyBudgetKwh`. Farms calls `computeFairshareAllocation` only once, inside `settleFarmsForecast` (farms.ts line ~383), and only to recompute the *food* allocation cycle after crediting the harvest - it never reads power out of that same allocation result.
|
||||
|
||||
So "fixed" in the README reads as "the constraint is fixed/respected by the solver" (true, mechanically), but the plain-English implication that the budget comes from the shelter's real, shared grow-light power allocation (as managed by Fair Share) is false: a grower can type any number, including one that has no relationship to what Fair Share actually allocated them for power this cycle, or leave it blank for "unlimited" (no constraint at all).
|
||||
|
||||
**Fix:** In `FarmsScreen.tsx`, replace the free-text `energyBudgetInput` state with a value read from `computeFairshareAllocation(await readAll()).allocation[selfAccountId].power` (mirroring how `settleFarmsForecast` already pulls a fresh allocation after crediting food), and drop the manual number input (or keep it only as a read-only display of the resolved Fair Share figure). This is a UI/wiring fix only - `solveFarmsPlantingOptimizer`'s `energyBudgetKwh` parameter and its LP constraint logic do not need to change.
|
||||
|
||||
## 4. Cross-app write to Fair Share's food number
|
||||
|
||||
**VERIFIED GENUINE.**
|
||||
|
||||
`src/lib/farms.ts`, `applyFarmsForecastToFairshare()` (line ~368):
|
||||
|
||||
```ts
|
||||
export async function applyFarmsForecastToFairshare(
|
||||
computation: FarmsPlantingComputation,
|
||||
appendFn: typeof append = append,
|
||||
): Promise<StoredEventLogEntry | undefined> {
|
||||
if (computation.insufficientData || computation.status !== "optimal") return undefined;
|
||||
return appendFn({
|
||||
type: "fairshare.contribution",
|
||||
resource: "food",
|
||||
value: computation.totalForecastYieldKg,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
This calls the real signed-event `append()` from `src/lib/eventlog.ts` with a `fairshare.contribution` payload (the type this session's earlier audit confirmed is relay-allowlisted under "fairshare"). `settleFarmsForecast()` (line ~400) chains this with a `readAll()` -> `computeFairshareAllocation()` re-solve and appends a `fairshare.allocation.cycle` event recording the new food allocation - a real replay-driven write, not a hand-computed/fabricated number. Wired to the UI in `FarmsScreen.tsx`'s `useEffect` (fires once per genuinely new `totalForecastYieldKg`, guarded by `lastSettledForecastRef` against re-firing on unchanged re-renders), with best-effort `trySyncWithBackend()` afterward.
|
||||
|
||||
## 5. Device-API angle / simulated-data honesty
|
||||
|
||||
**CONFIRMED: no device sensor, and this is correct per the README's own rule - not a violation.**
|
||||
|
||||
Farms has no device-API angle, and the implementation does not pretend otherwise - there's no fake "soil sensor" or "chamber thermometer" API call anywhere in `src/miniapps/farms/`. Temperature input is 100% resident-entered through `TemperatureEntryForm.tsx`'s manual `{date, tmin, tmax}` form (plain `<input type="date">` / `<input type="number">` fields, `onAddEntry` pushed straight into component state, no pre-seeded or randomly-generated values). README's own rule (lines 185-190) requires "every reading comes from a real resident report through the UI" (sensor exception carved out only for Light Clock's device motion sensor) - a human manually typing today's measured min/max chamber temperature into a form satisfies that rule exactly; it is the same class of real-resident-input as every other mini-app's manual reporting flows (e.g. Water Watch's `ReportReadingForm`), not a fabricated/simulated stand-in. `computeGdd` additionally refuses to produce a number at all (`insufficientData: true`) until a resident has actually entered at least one reading, closing off the "fabricated 0" failure mode.
|
||||
|
||||
## 6. Claimed-but-unwired UI/feature
|
||||
|
||||
None found beyond the power-budget gap in item 3. Checked:
|
||||
- `PlantingInputForm.tsx` (plot/crop entry) feeds `plots`/`crops` state directly into `solveFarmsPlantingOptimizer` - wired.
|
||||
- `ScheduleGrid.tsx` renders `computation.schedule` - wired to the real LP result.
|
||||
- `ForecastPanel.tsx` renders `totalForecastYieldKg`, `cumulativeGdd`, `totalEnergyKwh` vs `energyBudgetKwh` - all real computed fields, no placeholder/static values.
|
||||
- `coreLoopFoodIntegration.test.tsx` exercises the full Farms -> Fair Share food-credit path end to end and explicitly asserts the credit never touches power/water/cooling supply - consistent with the code read above.
|
||||
|
||||
## Verdict
|
||||
|
||||
**GAP-FOUND** (one item; everything else COHERENT).
|
||||
|
||||
- GDD model (#1): COHERENT - genuine average-method formula with a real crop base temperature and real maturity thresholds.
|
||||
- LP optimizer (#2): COHERENT - genuine `javascript-lp-solver` LP, real dependency, real `.Solve()` call, real constraints.
|
||||
- Grow-light power budget (#3): **GAP** - `src/miniapps/farms/FarmsScreen.tsx:32-41` (free-text `energyBudgetInput` state) is fully disconnected from Fair Share's real power supply/allocation (`src/lib/fairshare.ts`'s `computeFairshareAllocation().allocation[agent].power`), despite the README calling it "a fixed grow-light power budget" implying it is the shelter's real shared power constraint. Fix: source `energyBudgetKwh` from a fresh `computeFairshareAllocation(await readAll())` read for the active account instead of a manually typed number.
|
||||
- Fair Share food write (#4): COHERENT - real signed `fairshare.contribution` event via `applyFarmsForecastToFairshare`/`settleFarmsForecast`.
|
||||
- Device-API/simulated-data honesty (#5): COHERENT - no device sensor claimed; all temperature input is honest resident manual entry, consistent with README's own data-integrity rule.
|
||||
- UI wiring (#6): COHERENT aside from the #3 gap - no other unwired claims found.
|
||||
@@ -0,0 +1,249 @@
|
||||
# Find Family (ma-findfamily) - coherence audit
|
||||
|
||||
**Scope:** `src/miniapps/findfamily/` (`SearchScreen.tsx`, `directory.ts`,
|
||||
`findFamilySync.ts`, their `.test` files) + `src/lib/findfamily.ts`
|
||||
(the PSI engine; there is no `src/lib/findFamilySync.ts` - the cross-device
|
||||
transport lives at `src/miniapps/findfamily/findFamilySync.ts`).
|
||||
|
||||
**Stated concept (README):** "Private-set-intersection search so neither the
|
||||
relay nor the other party learns who searched unless there's a real match."
|
||||
|
||||
## Verdict: GAP-FOUND (one confirmed, central gap; everything else COHERENT)
|
||||
|
||||
The PSI cryptography is real and the cross-device transport is real. The
|
||||
confirmed, pre-existing finding from `.omo/evidence/service-sync-reevaluation.md`
|
||||
still holds exactly as stated: **the directory is a hardcoded seed fixture
|
||||
with no resident-facing write path.** This is the central gap for this
|
||||
app's stated purpose.
|
||||
|
||||
---
|
||||
|
||||
## 1. Is the PSI cryptography genuinely implemented?
|
||||
|
||||
**COHERENT.** `src/lib/findfamily.ts` is a real two-party Diffie-Hellman PSI
|
||||
protocol over the ristretto255 prime-order group (`@noble/curves/ed25519.js`
|
||||
export), not a plaintext string match:
|
||||
|
||||
- `hashNameToPoint` equivalent: `nameDigest()` (SHA-256 of a normalized,
|
||||
domain-separated name) -> `pointFromDigest()` maps the digest to a group
|
||||
element via `Point.BASE.multiply(scalar)` (lines ~95-104). Discrete-log
|
||||
hardness means the point alone reveals nothing about the name.
|
||||
- Searcher blinding: `prepareSearch()` (lines ~218-230) multiplies the query
|
||||
point by a fresh CSPRNG scalar (`randomScalar()`, rejection-sampled mod
|
||||
group order) and only ever returns the blinded point plus a
|
||||
session that stays on-device (`blindingFactor`, `queryDigest`).
|
||||
- Directory-side double-blinding: `respondToSearch()` (lines ~240-273)
|
||||
multiplies the incoming blinded query by its own fresh scalar, blinds
|
||||
every directory entry's point with that same scalar, and seals each
|
||||
entry's id under an AES-GCM key HKDF-derived from that entry's own name
|
||||
digest (`deriveEntryKey`/`encryptId`, lines ~113-150) - so the directory
|
||||
never ships a plaintext id, and a searcher can only open the id ciphertext
|
||||
for the one entry whose point matched (same key derivation on both sides).
|
||||
Roster size is additionally padded to a multiple of 8 with indistinguishable
|
||||
dummy entries (lines ~276-291) and shuffled (`shuffleInPlace`), to blur
|
||||
even approximate directory size from the response.
|
||||
- Searcher-side match + decrypt: `finalizeSearch()` (lines ~352-369)
|
||||
un-blinds each returned point with its own `blindingFactor` and compares
|
||||
it against the doubly-blinded query via `candidate.equals(target)`; only
|
||||
on a match does it call `decryptId()` with its own `queryDigest` - every
|
||||
non-matching entry (real or dummy) stays opaque ciphertext forever.
|
||||
|
||||
This is architecturally correct DH-PSI: a plaintext name never crosses the
|
||||
`DirectoryChannel` boundary in either direction, in any code path including
|
||||
the WebRTC transport (`findFamilySync.ts` only ever moves
|
||||
`SearchRequest`/`SearchResponse` shapes: hex group elements + AEAD
|
||||
ciphertexts). `src/lib/findfamily.test.ts` and
|
||||
`src/miniapps/findfamily/findFamilySync.test.ts` include adversarial cases
|
||||
(a hostile peer injecting malformed points/garbage ciphertext) confirming
|
||||
the wire boundary is validated (`isParseablePoint`/`isValidSearchRequest`/
|
||||
`isValidSearchResponse` in `findFamilySync.ts`) before it ever reaches the
|
||||
PSI math.
|
||||
|
||||
## 2. Is there a real "register yourself into the directory" flow?
|
||||
|
||||
**GAP-FOUND - this is the confirmed, central gap.** The prior audit's
|
||||
caveat is still accurate and I traced it to the exact code:
|
||||
|
||||
- `src/miniapps/findfamily/directory.ts:17-24` defines `SEED_DIRECTORY` as a
|
||||
`const` array literal of 4 fixture entries (`Ana Ramirez`, `Mateo Ramirez`,
|
||||
`Jane Doe`, `Tomas Alvarez`). There is no function in this file, or
|
||||
anywhere under `src/miniapps/findfamily/` or `src/lib/findfamily.ts`, that
|
||||
appends, mutates, or otherwise grows this array.
|
||||
- `SearchScreen.tsx:60` wires `SEED_DIRECTORY` as the sole default
|
||||
`directoryChannel` source (`createLocalDirectoryChannel(SEED_DIRECTORY)`),
|
||||
and `SearchScreen.tsx:104` passes the *same* `SEED_DIRECTORY` constant into
|
||||
`connectDirectorySync(nearbyCode, SEED_DIRECTORY)` for the "nearby device"
|
||||
WebRTC path too - so even cross-device search answers requests only out of
|
||||
the hardcoded seed, never out of anything a resident entered.
|
||||
`findDirectoryEntryById(SEED_DIRECTORY, matchId)` (`SearchScreen.tsx:145`)
|
||||
confirms the same fixture is also what resolves a match's display name.
|
||||
- There is no "Add myself" / "Register a missing family member" form, button,
|
||||
or route anywhere in the Find Family screen, no `directory.add()`-style
|
||||
export, and no Event Log payload type for it: a grep of `src/lib/eventlog.ts`
|
||||
and every mini-app's payload literals turns up `wallet.issue`,
|
||||
`wallet.transfer`, `fairshare.contribution`, `fairshare.floor`,
|
||||
`fairshare.need`, `housing.assignment`, `housing.preference`, etc., but
|
||||
nothing named `findfamily.*`. The project's own established convention
|
||||
(one signed Event Log payload type per mini-app write, named
|
||||
`<app>.<action>`) is simply never instantiated for Find Family.
|
||||
- `directory.ts`'s own doc comment acknowledges the design intentionally
|
||||
keeps names out of the replicated Event Log ("storing resident names
|
||||
there would hand every peer the exact plaintext roster the PSI protocol
|
||||
exists to avoid exposing") and gestures at "synced once out-of-band, by
|
||||
the sneakernet/QR transport the design doc describes" - but no such
|
||||
sneakernet/QR import or write path actually exists in this codebase: a
|
||||
repo-wide grep for `qr|QR|camera|BarcodeDetector|getUserMedia` under
|
||||
`src/miniapps/findfamily/` returns nothing; QR code generation/scanning
|
||||
exists only in Assembly (`AssemblyScreen.tsx` imports `qrcode` to render a
|
||||
sync *room code*, not a contact-registration token) and the generic
|
||||
mini-app install-sharing flow - neither is wired to Find Family.
|
||||
|
||||
**Why this is the central finding:** the stated purpose is "reconnect
|
||||
families" (P8). A PSI search is only meaningful if the person being
|
||||
searched for was able to get themselves (or get added by someone else) into
|
||||
the searchable set. As shipped, the directory is permanently frozen to 4
|
||||
demo names; no resident can ever be found who isn't one of those 4
|
||||
hardcoded fixtures, no matter how real or correct the cryptography
|
||||
protecting the search is. The mechanism the UI performs (a real,
|
||||
privacy-preserving search) is sound; the data it searches over is not
|
||||
resident-controlled, so "reconnect families" cannot actually happen for any
|
||||
real person in this build.
|
||||
|
||||
**Concrete, scoped fix** (same pattern the project already uses elsewhere -
|
||||
this fits the stated non-local-write constraint directly, since the privacy
|
||||
property only requires that *names not be synced automatically/silently
|
||||
across the signed Event Log to every peer*, not that an append path cannot
|
||||
exist for a resident's own voluntary registration of themselves):
|
||||
|
||||
1. Add an Event Log payload type `findfamily.register` (shape:
|
||||
`{ type: "findfamily.register"; id: string; name: string }`) alongside
|
||||
the existing `wallet.*`/`fairshare.*`/`housing.*` payloads in
|
||||
`src/lib/eventlog.ts`'s payload union, written through the same
|
||||
`append()` used by every other mini-app. The resident's own device signs
|
||||
and appends it locally — a deliberate, resident-initiated write, exactly
|
||||
matching how `fairshare.need`/`housing.preference` already work (a
|
||||
resident opts in to being visible for that mini-app's purpose).
|
||||
2. Add a small form to `SearchScreen.tsx` ("Register yourself or a missing
|
||||
family member") that calls `sdk.eventlog.append` (or the shell's
|
||||
`eventlog.append` directly, same as other mini-apps) with that payload.
|
||||
3. On mount, read the resident's *own* replicated Event Log (`readAll()`,
|
||||
already the sanctioned local read path) and filter for
|
||||
`findfamily.register` entries, merging them into the local
|
||||
`DirectoryEntry[]` passed to `createLocalDirectoryChannel()` /
|
||||
`connectDirectorySync()` alongside `SEED_DIRECTORY` — i.e. the search
|
||||
index becomes `[...SEED_DIRECTORY, ...registeredEntries]`, read fresh
|
||||
every time exactly like `ledger.ts`'s replay-only balances.
|
||||
4. Document precisely why this does not reintroduce the plaintext-roster
|
||||
leak the current `directory.ts` comment warns about: `findfamily.register`
|
||||
entries sync like every other signed event (that is standard, already-
|
||||
accepted behavior for `wallet.*`/`fairshare.*`/`housing.*` payloads, none
|
||||
of which are kept secret from peers either) - the privacy property this
|
||||
mini-app actually promises and delivers is narrower and already true
|
||||
today: *a search query's plaintext name never leaves the searcher's
|
||||
device*, not that the directory's membership itself is secret. Being
|
||||
"findable" necessarily requires the resident to have made themselves
|
||||
findable somewhere non-secret; PSI protects the *searcher*, not the
|
||||
*registrant's* anonymity (nobody claims the opposite in the README). This
|
||||
reframing should be the one line added to the README claim alongside the
|
||||
fix, since the current wording ("neither the relay nor the other party
|
||||
learns who searched") is accurate as far as it goes but omits that there
|
||||
is currently no one to search for beyond 4 fixtures.
|
||||
|
||||
## 3. Does the WebRTC search channel really work as P2P, or is it only mocked?
|
||||
|
||||
**COHERENT, with an honest disclosed caveat already in the code.**
|
||||
`findFamilySync.ts` wires a real `WebrtcProvider` (from `y-webrtc`, the same
|
||||
dependency and signaling-server configuration `assemblySync.ts` already uses
|
||||
for Assembly's CRDT sync - `DEFAULT_SIGNALING_SERVERS` is imported directly
|
||||
from that module) to a throwaway `Y.Doc` used purely as a request/response
|
||||
relay (`REQUEST_MAP_NAME`/`RESPONSE_MAP_NAME`). This is a genuine
|
||||
browser-to-browser RTCDataChannel transport, not a simulated one, when run
|
||||
in a real browser:
|
||||
|
||||
- `hasRealtimeDirectorySyncTransport()` (lines ~59-61) gates on
|
||||
`typeof RTCPeerConnection !== "undefined"` - true only in a real browser.
|
||||
- `SearchScreen.tsx`'s "Search nearby devices" toggle is off by default
|
||||
(`nearbySearchEnabled` starts `false`), mirroring Assembly's own
|
||||
`hasRealtimeTransport()` pattern, and in the vitest/happy-dom test
|
||||
environment this guard correctly reports `false` (no `RTCPeerConnection`
|
||||
global exists there), so the toggle in tests is exercised honestly as a
|
||||
no-op rather than fabricating peer connections.
|
||||
- The only place a WebRTC connection is *simulated* is
|
||||
`findFamilySync.test.ts`, which explicitly `vi.mock("y-webrtc", ...)`s a
|
||||
deterministic in-memory `FakeWebrtcProvider` (lines 12-88) that two test
|
||||
instances wire to each other's `room.webrtcConns` map - this is a disclosed
|
||||
test double for a transport that cannot run in Node, exactly analogous to
|
||||
how `assemblySync.test.ts` already tests Assembly's own WebRTC sync. It is
|
||||
not a mislabeled mock standing in for production code; production
|
||||
`SearchScreen.tsx` never imports or references the mock.
|
||||
|
||||
So: the search channel is real production WebRTC code exercised with a
|
||||
disclosed, standard test double in automated tests (same pattern as
|
||||
Assembly, already an accepted convention in this codebase) - not "only ever
|
||||
exercised same-device" in the deceptive sense the brief asked me to rule
|
||||
out. It is, however, same-device (same hardcoded directory) in the sense of
|
||||
finding #2 above: even a real P2P connection to a real second device only
|
||||
ever searches that *other* device's copy of the same frozen `SEED_DIRECTORY`
|
||||
constant, since neither side can register new entries into what it answers
|
||||
with.
|
||||
|
||||
## 4. Could the camera (QR) sensibly exchange a "find me" contact token?
|
||||
|
||||
**Real and sensible addition, but currently unwired - do not force it in
|
||||
as a replacement for finding #2's fix.** Two residents who are together
|
||||
right now and want to register each other for when they're later separated
|
||||
is a legitimate, in-scope scenario this app does not currently serve at
|
||||
all, and the project already has every piece needed:
|
||||
|
||||
- `qrcode` is already a dependency, already used for exactly a "share a
|
||||
short opaque code to establish a channel" purpose in
|
||||
`AssemblyScreen.tsx:2,56,188-189` (renders a QR of the sync room code).
|
||||
- The generic mini-app install/share flow (`ShareInstallQr.tsx`, referenced
|
||||
in `useAssemblyEngine.ts`'s comments) already establishes the "scan to
|
||||
receive a short code, then act on it" UX pattern for this app.
|
||||
- A natural, low-risk mechanism: resident A renders a QR encoding their own
|
||||
`DirectoryEntry` (`{ id, name }` - or just `name`, since `id` can be
|
||||
generated locally) the same way Assembly renders its room-code QR;
|
||||
resident B scans it (any of the project's existing camera-scan affordances,
|
||||
or even a manual paste of the short code for an offline/no-camera case)
|
||||
and calls the `findfamily.register` append from finding #2 locally for
|
||||
that name, so A appears in B's own future PSI directory index (and B in
|
||||
A's, if A reciprocally registers B). This is strictly an *in-person,
|
||||
consensual, do-it-yourself* QR exchange - categorically different from
|
||||
(and does not conflict with) the PSI search's actual threat model, which
|
||||
is about a *stranger searching the relay/directory holder* without
|
||||
leaking the query.
|
||||
- This is not forced: it solves a real, stated sub-problem (together-now,
|
||||
register-for-later) that the written brief itself names, with components
|
||||
the codebase already has proven out elsewhere. It should be scoped as an
|
||||
*additional* convenience entry point into the same `findfamily.register`
|
||||
payload from finding #2, not a required precondition for it - the basic
|
||||
text-entry "register yourself" form is the higher-priority, simpler fix
|
||||
and should land first; QR-assisted registration is a reasonable follow-on.
|
||||
|
||||
## 5. Any claimed-but-unwired UI/feature?
|
||||
|
||||
None found beyond finding #2. Specifically checked and found genuinely
|
||||
wired, not just claimed:
|
||||
- The plaintext-never-leaves-device disclaimer (`PLAINTEXT_DISCLAIMER`,
|
||||
`SearchScreen.tsx:17-18`) renders in every result state
|
||||
(`data-testid="findfamily-disclaimer"` outside the conditional blocks) -
|
||||
true in all branches, not just the happy path.
|
||||
- The "nearby devices" peer-count status
|
||||
(`findfamily-nearby-peer-count`) reflects `connectedPeerCount()` live via
|
||||
the provider's `"peers"`/`"synced"` event listeners - not a fabricated
|
||||
"connected" state.
|
||||
- Error path (`result.status === "error"`) is distinct from "no match" and
|
||||
only fires on a real channel failure (e.g. WebRTC timeout), so a resident
|
||||
is never told "no match" when the search didn't actually complete - this
|
||||
matches the project's "no fabricated data" rule.
|
||||
|
||||
## Summary
|
||||
|
||||
| # | Question | Verdict |
|
||||
|---|---|---|
|
||||
| 1 | Real PSI crypto, not plaintext match | COHERENT - genuine ristretto255 DH-PSI, `src/lib/findfamily.ts` |
|
||||
| 2 | Real resident "register yourself" write path | **GAP-FOUND** - `SEED_DIRECTORY` (`directory.ts:17-24`) is the only directory source anywhere, no append path, no `findfamily.*` Event Log payload type exists |
|
||||
| 3 | Real WebRTC P2P, not only mocked | COHERENT - real `y-webrtc`/`RTCPeerConnection` wiring, standard disclosed test double (same pattern as Assembly) |
|
||||
| 4 | QR "find me" token exchange feasibility | Real, sensible, currently unwired - good follow-on to #2's fix, not a substitute for it |
|
||||
| 5 | Claimed-but-unwired UI | None found beyond #2 |
|
||||
@@ -0,0 +1,86 @@
|
||||
# Health Post Coherence Audit (READ-ONLY, advisory)
|
||||
|
||||
Date: 2026-11-20
|
||||
Scope: `src/lib/healthpost.ts`, `src/lib/healthpostTally.ts`, `src/miniapps/healthpost/*`
|
||||
Explicitly out of scope (fixed already this session): the cross-device corroboration gate / pseudonym-signing fix (see commit "feat(sync): domain-separated pseudonym signing for mood pulses and symptom reports" and `.omo/evidence/service-sync-reevaluation.md`).
|
||||
|
||||
Stated concept (README.md, Problem-to-mini-app mapping table, row P9/P10):
|
||||
> "Health Post (ma-healthpost): WHO-IMCI protocol-guided triage chat backed by real crowd symptom self-reports aggregated into a dispatch-facing tally"
|
||||
|
||||
## Verdict: COHERENT (with one naming nit, not a gap)
|
||||
|
||||
The IMCI engine is a genuine, faithful, deliberately-scoped subset of the real WHO-IMCI chart, not an ad-hoc checklist loosely inspired by it. The "chat" label oversells the UI's interaction model slightly (it is a progressively-revealed single-page form, not a sequential one-question-at-a-time conversation) but this is a naming/UX nuance, not a functional gap — no finding here rises to GAP-FOUND severity. No claimed-but-unwired feature was found. A photo-attachment capability is absent but was never claimed by the README or any UI copy; it is a legitimate, honestly-scoped future enhancement, not a defect.
|
||||
|
||||
---
|
||||
|
||||
## 1. WHO-IMCI protocol fidelity
|
||||
|
||||
**File:** `src/lib/healthpost.ts`
|
||||
|
||||
### What real WHO-IMCI requires (for comparison)
|
||||
The published WHO IMCI chart booklet ("Assess and Classify the Sick Child Age 2 Months up to 5 Years") structures assessment as:
|
||||
- **Age banding**: young infant (birth–2 months, separate chart) vs. 2 months–5 years (the chart this code targets).
|
||||
- **General danger signs** (ask + look): not able to drink/breastfeed, vomits everything, convulsions (history or current), lethargic/unconscious. Any one → urgent referral regardless of other findings.
|
||||
- **Main symptom assessment, each with its own classification table**: cough/difficult breathing (fast-breathing age-banded cutoffs, chest indrawing, stridor), diarrhoea (dehydration 2-of-4 sign tables for "severe" vs "some", plus independent persistent-diarrhoea and dysentery rows), fever (danger signs/stiff neck → very severe febrile disease; measles rash+one of cough/coryza/red eyes; otherwise assess for malaria/measles), plus (not implemented here) ear problem and malnutrition/anaemia assessment.
|
||||
- Classification uses a traffic-light severity convention (pink=urgent referral, yellow=treat, green=home care) per domain, with dehydration's "sunken eyes" legitimately counting in both the severe and some-dehydration columns at once.
|
||||
|
||||
### What the code actually does
|
||||
`classifyExam` in `src/lib/healthpost.ts` implements, with heavy real citations to the WHO chart booklet and in-service training module in its doc comments:
|
||||
1. **Age range enforcement**: throws `AgeOutOfSupportedRangeError` outside 2–59 whole months, explicitly refusing to guess against the young-infant protocol it doesn't implement (lines ~130-136, ~234-240).
|
||||
2. **General danger signs** exactly as published: `unableToDrinkOrBreastfeed`, `vomitsEverything`, `hasHadConvulsions`, `lethargicOrUnconscious` → any one triggers "VERY SEVERE DISEASE" urgent referral, reused (not re-asked) across downstream domains — matching how a single real exam reuses one look/ask (line ~70-75 doc, `triggeredDangerSigns` ~line 318).
|
||||
3. **Cough/difficult breathing** (`classifyCough`, ~line 340): any danger sign OR chest indrawing OR stridor-when-calm → severe pneumonia/very severe disease (urgent referral); else fast breathing at the correct age-banded cutoffs (≥50/min for 2–<12mo, ≥40/min for 12–59mo, `fastBreathingThreshold`) → pneumonia (needs treatment); else → no pneumonia/cough or cold (home care). This matches the real chart's age-banded fast-breathing cutoffs precisely.
|
||||
4. **Dehydration** (`classifyDehydration`, ~line 369): severe-dehydration 2-of-4 {lethargic/unconscious, sunken eyes, not able to drink/drinking poorly, skin pinch very slow} and some-dehydration 2-of-4 {restless/irritable, sunken eyes, drinks eagerly/thirsty, skin pinch slow} — correctly implements the real two-column table including "sunken eyes" legitimately counting toward both columns simultaneously (explicitly called out in the module doc comment).
|
||||
5. **Persistent diarrhoea / dysentery** (`classifyPersistentDiarrhea`, `classifyDysentery`, ~line 402-430): independent rows evaluated alongside (not instead of) dehydration — duration ≥14 days with/without concurrent dehydration, and blood-in-stool — matching the chart's parallel classification rows.
|
||||
6. **Fever** (`classifyFever`, ~line 460): danger sign or stiff neck → very severe febrile disease; else generalized rash + cough/runny nose/red eyes → measles; else → fever, assess for malaria/measles. Crucially, a febrile child is **never** classified home care (explicitly documented and enforced — "malaria and measles cannot be excluded by eye" at a no-lab health post), which is a real and important IMCI safety property, correctly preserved.
|
||||
7. **Honest incompleteness signaling**: if no implemented domain fires, the result is `overallUrgency: "not_assessed"` with an explicit "assessment incomplete" label — never defaulted to a false-reassuring "home care" (`pickOverall`, ~line 505-525). The module doc comment is explicit that this engine implements only a subset of full IMCI (ear problems and malnutrition/anaemia assessment are explicitly out of scope, not silently dropped).
|
||||
8. **No silent defaulting on incomplete/invalid input**: `MissingExamFieldError` and `InvalidExamFieldError` (NaN/Infinity/negative numeric guards) are thrown rather than falling through to the least-urgent branch — this was clearly a deliberately-hardened invariant (see the `InvalidExamFieldError` doc comment describing the exact `NaN < 14` / `NaN >= 50` silent-fallthrough bug class it prevents).
|
||||
|
||||
**Assessment**: This is a genuine, correctly-structured subset of real WHO-IMCI, not an ad-hoc checklist "inspired by" it. The danger-sign gate, age-banded fast-breathing thresholds, two-column dehydration sign-counting (including the sunken-eyes dual-count nuance), independent persistent-diarrhoea/dysentery rows, and the "fever is never home care" rule are all specific, correct IMCI mechanics that a loose approximation would very likely get wrong or omit. The engine is honest about its own incompleteness (ear/malnutrition domains not implemented, young-infant chart not implemented, "not_assessed" never silently becomes "home care"). This is the strongest-evidenced part of the mini-app.
|
||||
|
||||
**Minor, non-blocking observation**: real IMCI's full "Assess and Classify" table also covers ear problem and nutritional/anaemia status; this module implements danger signs + cough + diarrhoea + fever only. That is disclosed, not hidden (module doc comment, `not_assessed` terminal state), so it is a scoping choice rather than a misrepresentation — not a coherence gap.
|
||||
|
||||
## 2. Is the "triage chat" genuinely conversational, or a flat form?
|
||||
|
||||
**File:** `src/miniapps/healthpost/TriageChat.tsx`
|
||||
|
||||
It is **functionally a single-page progressively-revealed form styled with chat bubbles**, not a sequential one-question-at-a-time conversation:
|
||||
- The component's `return` (lines ~280-440) renders every top-level question (age, danger signs, cough y/n, diarrhea y/n, fever y/n) simultaneously on one scrollable page; it does not advance through discrete "turns" or collapse answered questions into a message history.
|
||||
- It *does* exhibit real conditional branching: the cough detail block (breaths/min, chest indrawing, stridor) only renders when `hasCoughOrDifficultBreathing` is true (line ~346), the diarrhea detail block only when `hasDiarrhea` is true (line ~366), and the fever detail block only when `hasFever` is true (line ~409) — this is the IMCI-correct behavior (don't ask cough follow-ups for a child without cough), implemented via conditional JSX rather than a chat-state machine.
|
||||
- `BotBubble` (line ~202) is a styling wrapper around each question prompt, giving a chat-like visual (bubbles), but there's no accumulating transcript, no "typing" reveal, no inability to see/change earlier answers while later ones are visible — the user can scroll and edit any visible field at any time, which is form behavior.
|
||||
- `toggleFieldReady` (line ~84) gates the single "Classify" submit button on all currently-relevant fields being filled, i.e. validation of a form, not chat-turn advancement.
|
||||
|
||||
**Assessment**: The label "WHO-IMCI triage chat" (heading text at line ~284, and the README's "triage chat" phrase) overstates the interaction model. What's implemented is a conditionally-revealing form with chat-bubble styling and IMCI-correct question gating (the right follow-up fields appear based on prior yes/no answers) — which is the clinically important part and is done correctly — but it is not a conversational UI in the sense of one question per turn with a growing message history. This is a UX/naming nuance worth flagging, not a functional defect: the gating logic that matters (asking cough follow-ups only if cough is present, etc.) is present and correct. I do not rate this GAP-FOUND because nothing is broken or misleading about the *triage result* — only the chrome ("chat") slightly oversells the form's interactivity style.
|
||||
|
||||
## 3. Camera/photo-attachment angle for referrals
|
||||
|
||||
**Files checked:** `src/miniapps/healthpost/TriageChat.tsx`, `ReferralQueue.tsx`, `healthpostEvents.ts`, `api/blob/*`
|
||||
|
||||
- No camera (`getUserMedia`) or file input exists anywhere in `src/miniapps/healthpost/*`. Confirmed via grep across the directory and `tunnelsafety` (for comparison) — zero matches.
|
||||
- `api/blob/index.ts` (POST, mints an id) and `api/blob/[id].ts` (GET by id) implement a generic, already-working persistent blob store (`putBlob`/`getBlob` from `../_lib/blobStore.ts`), with a `BlobTooLargeError`/`MAX_BLOB_SIZE_BYTES` guard.
|
||||
- That blob store is **not currently used for any photo/media evidence anywhere in `src/`**. The only `src/` references to "blob" are in `InstallMiniappScreen.tsx`, `miniappUpload.ts`, `miniappSharing.ts` (mini-app package installation/sharing, a completely different use of the same generic endpoint) and one unrelated comment in `TestimonyBoard.tsx` ("the JSON blob `importTestimonyStatement`..." — just the word, not the API). So there is no existing in-app precedent of "attach a photo, get a blob id, reference it in a signed event" to simply extend into Health Post — it would be new wiring end-to-end (upload UI → blob POST → store blob id in `ReferralPayload` → render in `ReferralQueue`), reusing only the already-built generic blob HTTP endpoints.
|
||||
- **Is it a real, honest, valuable addition?** Yes, if scoped correctly: a photo *attached to a referral for the receiving clinician's own eyes* (e.g. a photo of a rash, a child's general appearance, or a readable thermometer) is clinically honest — it's raw visual evidence handed to a human clinician making their own judgment, structurally identical to a clinician glancing at the actual referred child, and categorically different from (and would not need to guard against) any AI-diagnosis-from-photo feature, which is correctly absent and should stay absent. It would slot naturally into `ReferralPayload` (adding an optional `photoBlobId: string` field, uploaded via `api/blob` before `postReferral` appends the event) and `ReferralQueue.tsx` (an `<img src="/api/blob/{id}">` for the clinician). This is a real, scoped, non-fabricated enhancement.
|
||||
- **Is it in scope for this audit's fix list?** No — it's an absent *feature*, not a *defect*. Nothing in the README, UI copy, or code claims photo capability exists. Per the audit's own framing ("investigate... whether adding one... would be a real, honest, valuable addition, or whether that's over-scoping"): I assess it as a legitimate roadmap item worth doing, not a coherence gap to fix now, since no promise is broken by its absence.
|
||||
|
||||
## 4. Claimed-but-unwired UI/feature check
|
||||
|
||||
Checked: `src/shell/miniappRegistry.ts` (tile label/icon only, no feature claims beyond "Health Post"), `README.md`'s P9/P10 row, and every component in `src/miniapps/healthpost/`.
|
||||
|
||||
- `README.md` claims: "WHO-IMCI protocol-guided triage chat" (implemented — see §1/§2) + "backed by real crowd symptom self-reports aggregated into a dispatch-facing tally" (implemented — `healthpostTally.ts` + `SymptomTallyDashboard.tsx`, cross-device-corroboration-gated as already fixed this session).
|
||||
- `TRIAGE_DISCLAIMER_TEXT` ("This is an informational WHO-IMCI triage aid, not medical advice...") is rendered in the result card (`triage-disclaimer` testid) — present and honest, not a dead string.
|
||||
- `NOT_ASSESSED_COPY` ("Not fully assessed...") is rendered for the `not_assessed` terminal state — present and honest, not a dead string.
|
||||
- Referral flow: "Send to clinician" button only appears for `urgent_referral`/`needs_treatment` results (`REFERRAL_ELIGIBLE_URGENCY`), calls real `postReferral` which signs+appends a `healthpost.referral` event; `ReferralQueue.tsx` reconstructs the open-referral list purely from replayed event-log entries via `extractReferrals`, with a working "Mark handled" → `resolveReferral` → separate `healthpost.referral.resolve` event, append-only as required. This is fully wired, not a stub.
|
||||
- `REPORTING_DELAY_CAVEAT` from `healthpostTally.ts` — confirmed rendered by `SymptomTallyDashboard.tsx` (not independently re-verified line-by-line in this audit beyond the first 50 lines read, but the import and intended usage are present; no other call site in the codebase).
|
||||
- No dead/unreferenced exports, no TODO/stub markers, no UI element without a backing handler were found in `TriageChat.tsx`, `HealthPostScreen.tsx`, or `ReferralQueue.tsx`.
|
||||
|
||||
**Assessment**: No claimed-but-unwired feature found. Everything the README and in-UI copy claim is backed by real, working code.
|
||||
|
||||
## Summary table
|
||||
|
||||
| Question | Finding |
|
||||
|---|---|
|
||||
| Real WHO-IMCI or ad-hoc checklist? | Real, faithfully-scoped subset (danger signs, cough/pneumonia, diarrhoea/dehydration/persistent/dysentery, fever) with correct age-banded thresholds, correct 2-of-4 dehydration tables, correct "fever never home care" rule, and honest "not fully assessed" (not false-reassuring) incompleteness signaling. Ear/malnutrition domains and young-infant chart explicitly out of scope and disclosed. |
|
||||
| Genuinely conversational chat, or flat form? | Progressively-revealed single-page form with chat-bubble styling and IMCI-correct conditional question gating; not a sequential turn-by-turn chat. Naming overstates the interaction model slightly — not a functional defect. |
|
||||
| Camera/photo angle? | Absent, not claimed, not currently backed by any in-app precedent (blob store exists but is unused for media anywhere in the app). A legitimate, honestly-scoped future enhancement (photo for clinician's own eyes, no AI diagnosis) — correctly out of today's scope. |
|
||||
| Claimed-but-unwired features? | None found. |
|
||||
|
||||
**Overall verdict: COHERENT.** No GAP-FOUND items. The one naming nuance (chat vs. form) does not warrant a fix mandate on its own since the underlying triage logic and question-gating are both correct and complete for what they claim.
|
||||
@@ -0,0 +1,166 @@
|
||||
# Housing (ma-housing) coherence audit
|
||||
|
||||
READ-ONLY advisory audit. No edits made.
|
||||
|
||||
**Scope read:** `src/miniapps/housing/FloorPlanScreen.tsx` (+ `.test.tsx`, `.module.css`),
|
||||
`src/lib/housing.ts`, `src/lib/housing.test.ts`, `src/admin/seedEvents.ts`
|
||||
(`HOLLOW_DEMO_HOUSING_SLOTS`/`buildDemoHousingCycleInput`), plus repo-wide
|
||||
case-insensitive greps for `medical`, `accessib`, `cohesion`, `family`,
|
||||
`wheelchair`, `triage`, `urgency`.
|
||||
|
||||
## 1. Genuine constraint-based assignment algorithm?
|
||||
|
||||
**Yes — genuine, not FCFS/random.** `solveHousingAssignment`
|
||||
(`src/lib/housing.ts:398-489`) builds a real binary-variable MILP via the
|
||||
`javascript-lp-solver` package: one `assign[resident, slot]` binary variable
|
||||
per eligible (resident, slot) pair, one `equal: 1` constraint per resident
|
||||
(exactly one slot), one `max: capacity` constraint per slot
|
||||
(`housing.ts:447-452`), objective `maximize sum(score * (1 + debtWeight * debt))`
|
||||
(`housing.ts:456-466`), solved by `solver.Solve(model)` (`housing.ts:471`).
|
||||
Infeasible instances (capacity shortfall, or a resident with zero eligible
|
||||
slots) are reported as `status: "infeasible"` with a reason — never
|
||||
silently dropped or force-fit (`housing.ts:421-445`, confirmed by
|
||||
`housing.test.ts` tests at offset ~120-145: "reports a resident with zero
|
||||
eligible slots as infeasible" and "...total capacity..."). This is a real
|
||||
constrained optimizer, correctly structured.
|
||||
|
||||
## 2. Fairness-debt ledger: genuinely carried across cycles via Event Log replay?
|
||||
|
||||
**Yes — genuinely replayed, not reset/fabricated.** `computeFairnessDebtLedger`
|
||||
(`housing.ts:594-601`) folds every real `housing.assignment` event from
|
||||
`readAll()`/`extractHousingCycles` (`housing.ts:565-579`, using the shared
|
||||
`sortForReplay` deterministic order) and overwrites per-resident debt in
|
||||
replay order, landing on the latest recorded value — same "replay the log,
|
||||
never store the result separately" shape as `ledger.computeBalances`.
|
||||
`recordHousingAssignmentCycle` (`housing.ts:626-676`) reads this ledger
|
||||
fresh from `readAll()` before each solve (unless a test injects
|
||||
`priorEntries`), solves with it, and signs+appends the `updatedFairnessDebt`
|
||||
via the real `append()` path — the only way the ledger changes. Debt
|
||||
accumulates (`priorDebt + shortfall`) when a resident doesn't get their best
|
||||
eligible slot, and resets to 0 when they do (`housing.ts:483-487`). This is
|
||||
genuinely stateful across cycles, not per-run fabrication.
|
||||
(The already-disclosed ECONOMY.md finding that synced `fairnessDebt` values
|
||||
aren't finiteness-validated is a known limitation, not re-reported here.)
|
||||
|
||||
## 3 & 4. "Medical proximity" and "accessibility" constraints: real inputs or vestigial?
|
||||
|
||||
**GAP-FOUND: both named constraints are vestigial — present only in prose, not wired into the solver's cost function or eligibility in any real code path.**
|
||||
|
||||
Evidence:
|
||||
- `HousingSlot` (`housing.ts:45-48`) has exactly two fields: `id`, `capacity`.
|
||||
No accessibility/step-free flag, no medical-proximity field.
|
||||
- `HousingPreference` (`housing.ts:55-59`) has exactly three fields:
|
||||
`residentId`, `slotId`, `score`. No resident attribute (mobility need,
|
||||
medical urgency, family-group id) exists anywhere in the data model.
|
||||
- The doc comment on `solveHousingAssignment` (`housing.ts:16-29`) asserts
|
||||
hard constraints are "expressed by simply omitting an ineligible
|
||||
resident/slot pair from `preferences`" for "step-free access, family
|
||||
cohesion, medical proximity, etc." — this describes a *mechanism the
|
||||
solver would honor if fed such an omission*, but no caller in the
|
||||
repository ever constructs such an omission for these reasons:
|
||||
- `buildRankedCyclePreferences` (`housing.ts:394-429`), the only
|
||||
production preference-builder used by `FloorPlanScreen.tsx`'s
|
||||
"Run assignment cycle" button (`FloorPlanScreen.tsx:261-300`),
|
||||
explicitly keeps "every resident... eligible for every discovered
|
||||
slot" (`housing.ts:396-397`) — differentiation comes solely from each
|
||||
resident's self-submitted free-choice slot *ranking* (`SlotPreferenceForm`,
|
||||
`FloorPlanScreen.tsx:143-215`), i.e. ordinary preference, not medical/
|
||||
accessibility/family need.
|
||||
- `buildDemoHousingCycleInput` (`src/admin/seedEvents.ts:280-310+`), the
|
||||
admin demo fixture, likewise gives every demo resident a full ranking
|
||||
over every slot (no omitted pairs) — purely to create a contested-slot
|
||||
fairness-debt rotation, unrelated to accessibility/medical/family.
|
||||
- Repo-wide grep for `medical`, `accessib`, `cohesion`, `family cohesion`,
|
||||
`wheelchair`, `triage`, `urgency` (case-insensitive, all of `src/`)
|
||||
returns **zero** hits in Housing code outside two prose strings in
|
||||
`housing.ts` (the doc comment at line 24 and the infeasibility-reason
|
||||
template string at line 480, which only *fires* when the generic
|
||||
"zero eligible slots" condition described in #3/#4 is met by some
|
||||
*other* cause — nothing ever sets that condition for medical/
|
||||
accessibility/family reasons).
|
||||
- `housing.test.ts`'s one "wheelchair user" mention (near line 149) is
|
||||
only an illustrative code comment on a generic `solveHousingAssignment`
|
||||
unit test (a resident given zero preference-list entries) — it is not
|
||||
a real resident attribute, and nothing upstream of that call ever
|
||||
derives "zero eligible slots" from an actual mobility/medical/family
|
||||
signal.
|
||||
- No link exists to Health Post's triage data: grep of `src/miniapps/housing/`
|
||||
and `src/lib/housing.ts` for any import from `healthpost`/`triage`
|
||||
returns nothing; `TriageChat.tsx`'s one "medical" hit is an unrelated
|
||||
disclaimer string in a different mini-app.
|
||||
|
||||
**Net effect:** the solver mechanism (omit a pair -> hard-exclude) is real
|
||||
and *could* carry these constraints, but today Housing has no resident
|
||||
attribute and no UI control for accessibility need, medical urgency, or
|
||||
family-group membership, and no production code path ever populates such
|
||||
an omission. The README's "accessibility, family cohesion, medical
|
||||
proximity" constraint list describes capability the architecture supports
|
||||
in principle but that the shipped feature does not actually exercise —
|
||||
every real cycle (resident-run or admin demo) differentiates residents
|
||||
by ordinary ranked preference only.
|
||||
|
||||
**Concrete fix (not applied — advisory):** either (a) narrow the README/
|
||||
doc-comment claim to what is actually implemented ("eligibility hard
|
||||
constraints are structurally supported via preference-list omission;
|
||||
today only general preference ranking populates them"), or (b) add the
|
||||
missing data: a per-resident attribute (e.g. `requiresStepFree: boolean`,
|
||||
or a `medicalUrgency`/`familyGroupId` field) captured in a form parallel to
|
||||
`SlotPreferenceForm`, a per-slot attribute (e.g. `stepFree: boolean`,
|
||||
`distanceToMedicalMeters: number`), and a real eligibility filter in
|
||||
`buildRankedCyclePreferences` (or a new preference-builder) that omits a
|
||||
(resident, slot) pair when the slot fails the resident's accessibility/
|
||||
medical-proximity requirement, and groups family members' preferences so
|
||||
cohesion is rewarded/enforced. Until one of these lands, "accessibility"
|
||||
and "medical proximity" should not be presented as live constraints.
|
||||
|
||||
## 5. Device-API angle?
|
||||
|
||||
**Confirmed none, genuinely.** Housing is a pure allocation/optimization
|
||||
problem over self-reported text/number form inputs (space id, location
|
||||
label, capacity, idle-hours/day, slot ranking) and a signed Event Log
|
||||
replay — there is no sensor-observable quantity (GPS, accelerometer,
|
||||
camera, etc.) that would honestly inform room-slot assignment, idle-space
|
||||
capacity, or fairness debt. `FloorPlanScreen.tsx` contains no
|
||||
`navigator.*`/geolocation/sensor API usage, confirmed by reading the full
|
||||
file. This is a correct "no device-API role" case, not an unexamined
|
||||
assumption.
|
||||
|
||||
## 6. Claimed-but-unwired UI/feature?
|
||||
|
||||
No additional instance beyond the #3/#4 gap above. Everything else in
|
||||
`FloorPlanScreen.tsx` is wired to real engine output:
|
||||
- "Your room slot" / "Fit score" / cycle number read from
|
||||
`findLatestResidentCycle` over `extractHousingCycles(entries)` — real
|
||||
replay, not a placeholder (`FloorPlanScreen.tsx:218-243`).
|
||||
- "Why you got this slot" (`explainAssignment`, `FloorPlanScreen.tsx:249-265`)
|
||||
is built entirely from real `view.assignment.score`/`priorDebt`/
|
||||
`currentDebt` numbers — no hardcoded/placeholder string branch.
|
||||
- "Report an idle space" and "Rank your preferred slots" forms both
|
||||
validate-then-sign-then-append through real `reportIdleSpace`/
|
||||
`recordSlotPreference` (`housing.ts`), with honest error states on
|
||||
failure (`submitStatus === "error"` branches use the actual thrown
|
||||
message, not a generic "submitted" claim).
|
||||
- "Run assignment cycle" button genuinely re-reads the log
|
||||
(`await readAll()`), rebuilds slots/preferences fresh, and calls the
|
||||
real `recordHousingAssignmentCycle` (`FloorPlanScreen.tsx:270-301`) —
|
||||
not a mocked/no-op click handler.
|
||||
|
||||
## Verdict
|
||||
|
||||
**GAP-FOUND** (one specific, real gap — not the already-disclosed
|
||||
ECONOMY.md finiteness issue). The MILP assignment engine and the
|
||||
fairness-debt ledger are both genuine, correctly implemented, and
|
||||
genuinely replay-persisted (#1, #2: COHERENT). The device-API question is
|
||||
correctly "none" (#5: COHERENT). But the two named hard constraints that
|
||||
give the mini-app its headline identity — "accessibility" and "medical
|
||||
proximity" — are vestigial: the solver's eligibility-omission mechanism
|
||||
that would enforce them exists and works, but zero bytes of the actual
|
||||
resident/slot data model or any production preference-builder (resident-run
|
||||
cycle or admin demo fixture) ever populate it for those reasons. Every real
|
||||
cycle today differentiates residents purely by self-reported slot ranking.
|
||||
Exact locations: `src/lib/housing.ts:45-59` (missing fields),
|
||||
`src/lib/housing.ts:394-429` `buildRankedCyclePreferences` (keeps everyone
|
||||
eligible for every slot), `src/admin/seedEvents.ts:280-310+`
|
||||
`buildDemoHousingCycleInput` (same). Fix: add the missing resident/slot
|
||||
attributes and a real eligibility filter (outlined above), or correct the
|
||||
README/doc-comment claim to match what ships.
|
||||
@@ -0,0 +1,162 @@
|
||||
# Light Clock (ma-lightclock) coherence audit
|
||||
|
||||
**Scope:** `src/miniapps/lightclock/` (LightClockScreen.tsx, ManualLogForm.tsx + their
|
||||
`.module.css`/`.test.tsx`), `src/lib/lightclockSensors.ts`, `src/lib/lightclock.ts`,
|
||||
`src/lib/lightclockAllocatorIsolation.test.ts`, `src/lib/sync.ts`.
|
||||
|
||||
**Stated concept (README):** "Circadian phase-response model from a manual sleep/wake log
|
||||
or device actigraphy (rest/activity from the motion sensor); it never claims to measure
|
||||
light (the Hollow has none); a personal wellness tracker only, never wired to ration
|
||||
anything."
|
||||
|
||||
## Verdict: COHERENT
|
||||
|
||||
All six audit points check out; no gap found. This is the most honestly-engineered sensor
|
||||
integration in the app's mini-app set.
|
||||
|
||||
## Evidence per point
|
||||
|
||||
### 1. Actigraphy derivation is a real computation, not fabricated
|
||||
|
||||
`src/lib/lightclockSensors.ts`:
|
||||
- `motionSampleMagnitude()` (L~85) computes `|a| = sqrt(x^2+y^2+z^2)` from a real
|
||||
`DeviceMotionEvent`'s `acceleration`/`accelerationIncludingGravity` vectors
|
||||
(`vectorMagnitude()`, L~61-66) - standard accelerometer-magnitude actigraphy, the same
|
||||
primitive used by published actigraphy algorithms (e.g. Cole-Kripke/Sadeh use banded
|
||||
magnitude counts; this is the raw-magnitude building block). It **throws** rather than
|
||||
substituting a fabricated zero when neither field has data (L~91-97), so callers must
|
||||
skip the sample.
|
||||
- `classifyActigraphy()` (L~148-153) is a deterministic threshold vs. a documented
|
||||
rest-baseline calibration (`DEFAULT_GRAVITY_EXCLUDED_CALIBRATION` rest=0,
|
||||
`DEFAULT_GRAVITY_INCLUSIVE_CALIBRATION` rest=9.80665 i.e. standard gravity,
|
||||
`movementThreshold=4`) - no `Math.random()` anywhere in the file (confirmed by reading
|
||||
it in full).
|
||||
- `subscribeToActigraphy()` (L~226-256) wires this to the real `window.addEventListener("devicemotion", ...)` browser event, coalescing to one epoch per minute
|
||||
(`epochMs` default 60000) so a 60Hz stream becomes a manageable persisted log - not a
|
||||
per-sample fire-hose.
|
||||
- `lightclockSensors.test.ts` (L102: "delivers real, timestamped actigraphy samples (not
|
||||
fabricated) through the devicemotion event") exercises this path with synthetic
|
||||
DeviceMotionEvents, confirming classification behavior end-to-end.
|
||||
|
||||
Conclusion: genuine accelerometer-magnitude actigraphy, not a dressed-up random number.
|
||||
|
||||
### 2. Real circadian phase-response model, not a lookup table
|
||||
|
||||
`src/lib/lightclock.ts` is a verbatim pure-function port of the published **Hannay19**
|
||||
macroscopic circadian model (Hannay, Booth & Forger 2019, J Biol Rhythms 34(6):658-671,
|
||||
DOI 10.1177/0748730419878298), citing the real `circadian` PyPI/GitHub package
|
||||
(`Arcascope/circadian`, `models.py` class `Hannay19`) as source for its equations and the
|
||||
default parameter/initial-condition values (`fixtures/hannay19-model-spec.md`, not
|
||||
re-derived per the file's own docstring).
|
||||
- `hannay19Derivative()` (L~104-125) implements the actual 3-variable ODE (amplitude R,
|
||||
phase Psi, light-adaptation n) with the Hill-type saturating light-drive term
|
||||
`lightDrive()` (L~80-90) and the full A1/A2 amplitude+phase coupling terms.
|
||||
- `rk4Step()` (L~133-146) is a real explicit RK4 numerical integrator, not a static
|
||||
table — `simulateHannay19()` (L~233-281) iterates it across the actual exposure time
|
||||
series up to `MAX_SIMULATION_STEPS` (bounded, not faked).
|
||||
- `estimateDlmoHours()` (L~286-304) detects true DLMO (dim-light-melatonin-onset) phase
|
||||
crossings by interpolating the unwrapped Psi trajectory, and `recommendLightTiming()`
|
||||
(L~340-353) turns that into phase-response-curve-consistent advice (seek/avoid light
|
||||
windows around projected CBTmin) — this is a genuine PRC-based model output, not a
|
||||
trivial if/else table.
|
||||
- `hasSufficientCircadianWindow()`/`MIN_CIRCADIAN_WINDOW_HOURS` (= `tau` ≈ 23.84h)
|
||||
explicitly forces an honest "insufficient-data" state rather than ever presenting the
|
||||
untouched seed state as a computed result — a real honesty safeguard baked into the
|
||||
model boundary, not just the UI.
|
||||
|
||||
Conclusion: a real, cited, numerically-integrated PRC model, not a mislabeled lookup
|
||||
table.
|
||||
|
||||
### 3. UI offers both paths; iOS DeviceMotionEvent permission correctly handled
|
||||
|
||||
`LightClockScreen.tsx`:
|
||||
- Initial state (`dataSource === null`) shows an "Enable motion sensor" button
|
||||
(`lightclock-enable-sensor`) whose `onClick` calls `handleEnableSensor()` ->
|
||||
`startLightClockDataSource()` synchronously from the click handler (gesture preserved).
|
||||
- `startLightClockDataSource()` (`lightclockSensors.ts` L~372-386) calls
|
||||
`requestMotionPermission()` first; if it does not resolve `"granted"`, it returns
|
||||
`{ kind: "manual-entry" }` with **no exception thrown and no silent lock-out** — the UI
|
||||
then renders `<ManualLogForm>` automatically (`dataSource?.kind === "manual-entry"`
|
||||
branch, L~175-181 of LightClockScreen.tsx).
|
||||
- `requestMotionPermission()` (`lightclockSensors.ts` L~300-315) correctly branches on
|
||||
the iOS 13+ contract: checks for `DeviceMotionEvent.requestPermission` as a function
|
||||
and `await`s it (the required explicit user-gesture-triggered permission prompt),
|
||||
mapping its `"granted"`/`"denied"` result 1:1, catching a thrown rejection as
|
||||
`"denied"` rather than crashing. Non-iOS platforms that expose `devicemotion` without a
|
||||
separate permission step resolve `"granted"` directly; no `window`/no
|
||||
`DeviceMotionEvent` at all resolves `"unavailable"`.
|
||||
- Both outcomes are reachable in the UI: sensor path renders
|
||||
`lightclock-sensor-active` + a "Stop recording" control; manual path renders the full
|
||||
`ManualLogForm` (hours / awake-asleep state / optional self-reported lux, with
|
||||
validation and an entry list) feeding `buildExposureFromManualLog()`.
|
||||
- `permissionError` state (L~160-163) surfaces "Couldn't request sensor permission - try
|
||||
the manual log instead" if `startLightClockDataSource` itself throws (defensive, since
|
||||
it's documented to resolve rather than throw) — belt-and-braces, not a broken path.
|
||||
|
||||
Conclusion: both paths are real, wired, and reachable; the iOS permission gesture
|
||||
requirement is correctly handled (synchronous click -> immediate `requestPermission()`
|
||||
call, no intervening `await` before the gesture-consuming call), with denial routing
|
||||
cleanly to the manual-log fallback rather than a dead end.
|
||||
|
||||
### 4. No light-sensing claim anywhere
|
||||
|
||||
Project-wide grep across `src/` for `light level|brightness sensor|lux (measur|detect|
|
||||
sens)|ambient light sensor|AmbientLightSensor` returned **zero matches**. The only "lux"
|
||||
usage is `lightclockSensors.ts`'s `ACTIVE_INFERRED_LUX`/`REST_INFERRED_LUX` constants and
|
||||
the `ManualLogForm`'s **optional, user-typed** "Lux estimate" field — both explicitly
|
||||
documented and labeled as a modeling input/user self-report, never a device measurement.
|
||||
`lightclockSensors.ts`'s module docstring states this invariant outright: "does NOT claim
|
||||
to measure light - there is none to measure... never a fabricated light reading." The
|
||||
UI's own prompt copy repeats it verbatim: "It never claims to measure light - The Hollow
|
||||
has none" (`LightClockScreen.tsx` L~146).
|
||||
|
||||
Conclusion: no stray light-sensing claim found; the honesty boundary is stated in three
|
||||
independent places (lib docstring, UI copy, this audit's own grep) and all agree.
|
||||
|
||||
### 5. Genuinely never wired to ration anything
|
||||
|
||||
Two independent enforcement mechanisms, not just a comment:
|
||||
- `src/lib/lightclockAllocatorIsolation.test.ts` is a **static import-graph reachability
|
||||
test** that walks the entire `src/` import graph and asserts, in both directions, that
|
||||
neither `lib/fairshare.ts` nor `lib/ceeiSpike.ts` (Fair Share's allocator roots) can
|
||||
reach `lib/lightclock.ts` or `miniapps/lightclock/LightClockScreen.tsx`, and vice versa.
|
||||
This is a build-enforced guarantee, re-checked on every test run, not just documentation.
|
||||
- `src/lib/sync.ts` (L~50-51) explicitly excludes `lightclock.*` from its sync-push
|
||||
allowlist: "`lightclock.*` stays strictly local and NEVER pushed (purely personal, no
|
||||
community claim at all - see README's 'never wired to ration anything')." `sync.test.ts`
|
||||
(L~122, L~140) asserts a `lightclock.actigraphy` event is appended locally but its type
|
||||
never appears in `pushedTypes`.
|
||||
- Project-wide grep of `src/miniapps/fairshare` for `lightclock|Hannay|ACTIGRAPHY_EVENT_TYPE`
|
||||
returned zero matches; a broader `src/`-wide grep for the same terms surfaced only the
|
||||
lightclock module's own files, its tests, the isolation test, and `sync.ts`'s exclusion
|
||||
comment — no resource-allocation file touches it.
|
||||
|
||||
Conclusion: not merely "never wired" by omission — actively enforced by a dedicated
|
||||
static-analysis test plus an explicit sync-layer exclusion, both exercised by the test
|
||||
suite.
|
||||
|
||||
### 6. Claimed-but-unwired UI/feature check
|
||||
|
||||
None found. Every control in `LightClockScreen.tsx`/`ManualLogForm.tsx` is backed by a
|
||||
real function: "Enable motion sensor" -> `startLightClockDataSource` ->
|
||||
`requestMotionPermission`/`subscribeToActigraphy`; "Stop recording" -> `handle.stop()`
|
||||
(removes the real `devicemotion` listener); manual "Add entry"/"Compute status" ->
|
||||
`buildExposureFromManualLog` -> `simulateHannay19`; actigraphy persistence ->
|
||||
`toActigraphyEvent`/`append()` to the signed Event Log, reloaded on mount via
|
||||
`readAll()` + `actigraphySamplesFromEvents()` so a multi-day log survives reloads. The
|
||||
"local-only" disclaimer (`LOCAL_ONLY_DISCLAIMER`) matches `sync.ts`'s actual exclusion
|
||||
behavior (point 5). No dead buttons, no TODO-stub computations, no "coming soon" state
|
||||
inside this mini-app.
|
||||
|
||||
## Summary
|
||||
|
||||
Light Clock is the one mini-app in this codebase whose sensor claim survives full
|
||||
scrutiny: the actigraphy math is real accelerometer-magnitude processing with documented,
|
||||
non-fabricated rest/active classification; the "phase-response model" is an actual cited,
|
||||
numerically-integrated circadian ODE (Hannay19) with real DLMO-crossing detection, not a
|
||||
lookup table; both the sensor and manual-log paths are genuinely wired in the UI with
|
||||
correct iOS DeviceMotionEvent permission handling; there is no stray light-measurement
|
||||
claim anywhere in the code or copy; and the "never wired to ration anything" boundary is
|
||||
enforced by both a dedicated static import-graph test and an explicit sync-layer
|
||||
allowlist exclusion, each backed by its own test. No gap found against the README's
|
||||
stated concept.
|
||||
@@ -0,0 +1,163 @@
|
||||
# Coherence Audit: Mentor mini-app (ma-mentor)
|
||||
|
||||
**Scope:** `src/miniapps/mentor/` (`MentorScreen.tsx`, `mentorEvents.ts`) + supporting lib
|
||||
(`src/lib/mentor.ts`, `src/lib/mentorSchedule.ts`, `src/lib/mentorMatching.ts`).
|
||||
|
||||
**Claim audited (README.md:99, verbatim):**
|
||||
> Mentor (ma-mentor): Skill-criticality-ranked knowledge feed with FSRS spaced-repetition
|
||||
> scheduling, so trade knowledge survives a generation
|
||||
|
||||
**Verdict: COHERENT.** Every clause of the claim maps to real, exercised code. 51/51 tests pass
|
||||
across the four mentor test files (`mentor.test.ts`, `mentorSchedule.test.ts`,
|
||||
`mentorMatching.test.ts`, `MentorScreen.test.tsx`), the mini-app is registered in
|
||||
`miniappRegistry.ts:40` and mounted (not a "Coming soon" placeholder) in
|
||||
`miniappComponents.tsx:19,50`, and both relay-allowlisted payload types are genuinely produced
|
||||
and consumed end-to-end.
|
||||
|
||||
---
|
||||
|
||||
## 1. Is "skill-criticality-ranked" a genuine ranking?
|
||||
|
||||
**Genuine.** `src/lib/mentor.ts` builds a real dependency graph (`SkillGraph`/`SkillNode`) and
|
||||
computes two distinct centrality metrics:
|
||||
|
||||
- `computeDependentsCounts` (mentor.ts:112-125) - direct in-degree (used by `mentorMatching.ts`'s
|
||||
scoring, not by the feed ranking).
|
||||
- `computeTransitiveDependentsCounts` (mentor.ts:146-168) - transitive closure over the
|
||||
dependency graph via DFS with a visited set (cycle-safe). This is the actual centrality metric
|
||||
feeding criticality.
|
||||
|
||||
`computeSkillCriticality` (mentor.ts:203-224) pairs `computeTransitiveDependentsCounts` with a
|
||||
real holder count pulled from `SkillHolderDataSource` (sourced from real `seed.skillHolder` Event
|
||||
Log entries via `buildSkillHolderDataSource`, mentor.ts:84-96) and flags `atRisk` only when both
|
||||
`dependentsCount >= minDependentsForAtRisk` and `holderCount <= maxHoldersForAtRisk` against fixed,
|
||||
undisclaimed thresholds (`DEFAULT_SKILL_CRITICALITY_THRESHOLDS`, mentor.ts:188-191). A skill with
|
||||
no holder data gets `insufficientData: true` and is never force-ranked - no fabricated zero.
|
||||
|
||||
`rankAtRiskSkills` (mentor.ts:226-241) then **sorts** the at-risk set deterministically:
|
||||
dependents-count descending (primary), holder-count ascending (tie-break), skill id (final
|
||||
tie-break). `MentorScreen.tsx` renders the feed by iterating `atRiskSkills` in exactly this order
|
||||
(`atRiskSkills.map(...)`, MentorScreen.tsx:~140) - the feed's visual order **is** the ranking
|
||||
output, not a separate/decorative list. This is a real ranking, not unordered/chronological
|
||||
"marketing copy."
|
||||
|
||||
## 2. Is the FSRS integration genuine?
|
||||
|
||||
**Genuine.** `src/lib/mentorSchedule.ts` imports `DefaultScheduler`, `Rating`, `Grade` from the
|
||||
real `ts-fsrs@6.0.0` dependency (confirmed in `package.json:25`, not vendored/stubbed). Verified
|
||||
against `node_modules/ts-fsrs/dist/index.d.mts`:
|
||||
- `DefaultScheduler<Version>(options?) => Promise<DefaultScheduler<Version>>` - matches the code's
|
||||
`await DefaultScheduler<"FSRS-7">()` (mentorSchedule.ts:108-111), including the async
|
||||
initialization (cached in a module-level promise, not re-created per call).
|
||||
- `scheduler.newCard({ now })` and `scheduler.review({ card, grade, now }).card` are real ts-fsrs
|
||||
scheduler methods (confirmed against the `DefaultSchedulerCardInput`/`review` types in the same
|
||||
`.d.mts`), not invented method names.
|
||||
|
||||
`computeSkillSchedule` (mentorSchedule.ts:118-136) replays a learner's **actual** chronologically
|
||||
sorted review history through the real scheduler via `reduce`, carrying the FSRS card state
|
||||
forward review-by-review (`scheduler.review({ card, grade: entry.rating, now: entry.reviewedAt
|
||||
}).card`) rather than computing a one-shot interval from the latest rating alone. `nextReviewAt`
|
||||
is ts-fsrs's own `card.dueAt` output of the final replay. A skill/learner pair with no history
|
||||
gets `insufficientData: true`, never a synthesized default schedule.
|
||||
|
||||
## 3. Does a real review outcome feed back into FSRS scheduling?
|
||||
|
||||
**Genuine, closed loop, verified by passing tests.** The resident's tap in `MentorScreen.tsx`
|
||||
(`handleRate` -> `postSkillReview`, MentorScreen.tsx:~105-112) calls
|
||||
`mentorEvents.ts:postSkillReview` (lines 44-57), which builds a `mentor.skillReview` payload
|
||||
(`{type, skillId, learnerId, rating, reviewedAt: new Date().toISOString()}`) and calls the real
|
||||
`append()` from `src/lib/eventlog.ts` - the sole signing write path (per AGENTS.md), so the review
|
||||
is a genuine Ed25519-signed Event Log entry, not a component-local state update.
|
||||
|
||||
On next render, `useEventLogEntries()` picks up the new entry, `buildSkillReviewHistorySource`
|
||||
(mentorSchedule.ts:85-97) folds all `mentor.skillReview` entries (including the new one) back into
|
||||
per-(skillId, learnerId) history, and the `useEffect` in `MentorScreen.tsx` (lines ~92-101)
|
||||
recomputes `scheduleAtRiskSkillReviews` -> `computeSkillSchedule`, which re-replays the full
|
||||
(now-longer) history through `ts-fsrs` and produces a new `nextReviewAt` shown in the "Next review
|
||||
due" row. This is adaptive re-scheduling, not a one-time static ordering: `mentor.test.ts` /
|
||||
`mentorSchedule.test.ts` exercise multi-review sequences and assert the schedule output changes
|
||||
with added review history (51/51 tests pass, confirmed by running
|
||||
`vitest run src/lib/mentor.test.ts src/lib/mentorSchedule.test.ts src/lib/mentorMatching.test.ts
|
||||
src/miniapps/mentor/MentorScreen.test.tsx`).
|
||||
|
||||
## 4. Are `mentor.skillReview` and `mentor.match` genuinely used for cross-device matching?
|
||||
|
||||
**Genuine, not unused payload types.** Both strings are present in the backend relay allowlist
|
||||
(`src/lib/sync.ts:123-124`), with a comment explicitly naming the cross-device apprentice<->mentor
|
||||
matching use case. Both are produced by real writers and consumed by real readers:
|
||||
|
||||
- `mentor.skillReview`: written by `postSkillReview` (mentorEvents.ts:44-57); read by
|
||||
`buildMentorProfilesFromReviews` and `buildApprenticeNeedsFromReviews` in
|
||||
`mentorMatching.ts:106-142` to build real mentor-skill profiles (an account becomes a mentor
|
||||
candidate for a skill once their latest review of it is `Rating.Good` or better - ts-fsrs's own
|
||||
proficiency bar, mentorMatching.ts:62-66) and real apprentice needs (latest review `Again`/`Hard`
|
||||
on an at-risk skill).
|
||||
- `mentorMatching.ts:matchApprenticesToMentors` (lines 196-220) scores every real mentor against
|
||||
every real need, reusing `computeDependentsCounts` from `mentor.ts` so covering a
|
||||
higher-centrality skill scores higher, with a deterministic `"no-match"` outcome when no mentor
|
||||
covers a need (never a crash or arbitrary pick).
|
||||
- `mentor.match`: written by `postMentorMatch` (mentorEvents.ts:105-121) only when a resident taps
|
||||
"Confirm match" on a *proposed* match in the UI (MentorScreen.tsx: `handleConfirmMatch`); read
|
||||
back by `buildConfirmedMentorMatches` (mentorEvents.ts:127-141) so a cold reload shows the
|
||||
confirmed state instead of re-proposing. Both writers call `trySyncWithBackend()` immediately
|
||||
after `append()` (best-effort, fire-and-forget, matching the documented
|
||||
local-write-never-blocks-on-network contract), which is the cross-device delivery path the
|
||||
allowlist entries exist for.
|
||||
|
||||
This is a real, closed apprentice<->mentor matching feature, not dead payload types.
|
||||
|
||||
## 5. Device-API angle (camera for a "show the skill" clip)?
|
||||
|
||||
**Not present, and correctly not forced.** Searched `src/miniapps/mentor/` and the mentor lib
|
||||
files for `camera`, `photo`, `blob`, `clip` - zero matches. No blob-store (`api/blob/*`) wiring
|
||||
exists in the Mentor feature at all. The idea (mentor attaches a photo/clip of a physical skill
|
||||
being performed, stored via the blob store, attached to a knowledge-feed card) is a plausible
|
||||
*future* enhancement but is not implemented, not half-wired, and not falsely claimed anywhere in
|
||||
the README or code comments - the stated concept ("skill-criticality-ranked knowledge feed with
|
||||
FSRS spaced-repetition scheduling") makes no camera/media claim, so there is no gap to report
|
||||
here. Flagging as a genuine opportunity, not a defect: a `blob.ref` field on `mentor.skillReview`
|
||||
or a companion `mentor.skillDemo` payload referencing an `api/blob/*` object would let a mentor
|
||||
attach a short how-to clip to an at-risk skill's feed card, which would meaningfully strengthen
|
||||
the "trade knowledge survives a generation" goal (a video/photo of a physical technique conveys
|
||||
what prose review ratings cannot). This is a suggestion for future work, not something the current
|
||||
README claim promises.
|
||||
|
||||
## 6. Claimed-but-unwired UI/feature?
|
||||
|
||||
**None found.** Checked every interactive element in `MentorScreen.tsx` against its backing logic:
|
||||
|
||||
| UI element | Backing logic | Wired? |
|
||||
|---|---|---|
|
||||
| Knowledge feed list, ordered | `rankAtRiskSkills` output, rendered in order | Yes |
|
||||
| "X depend on this" badge | `skill.dependentsCount` (transitive closure) | Yes |
|
||||
| "Known holders" value | real `holderCount` from seed data | Yes |
|
||||
| "Next review due" | `ts-fsrs` `nextReviewAt`, recomputed on new entries | Yes |
|
||||
| Again/Hard/Good/Easy rate buttons | `postSkillReview` -> signed Event Log append | Yes |
|
||||
| Apprentice match cards | `matchApprenticesToMentors` output | Yes |
|
||||
| "Confirm match" button | `postMentorMatch` -> signed Event Log append | Yes |
|
||||
| Confirmed-match display | `buildConfirmedMentorMatches` replay | Yes |
|
||||
| Empty states (`mentor-feed-empty`, `mentor-match-empty`) | real empty-array guards, not fake placeholders | Yes |
|
||||
|
||||
Mini-app registration (`miniappRegistry.ts:40`) and route mounting
|
||||
(`miniappComponents.tsx:19,50`) are both real - `mentor` is not a stub rendered by the generic
|
||||
"Coming soon" placeholder.
|
||||
|
||||
---
|
||||
|
||||
## Evidence trail
|
||||
|
||||
- `src/lib/mentor.ts` (criticality engine, read in full)
|
||||
- `src/lib/mentorSchedule.ts` (FSRS integration, read in full)
|
||||
- `src/lib/mentorMatching.ts` (apprentice/mentor matching, read in full)
|
||||
- `src/miniapps/mentor/MentorScreen.tsx` (UI, read in full)
|
||||
- `src/miniapps/mentor/mentorEvents.ts` (Event Log adapter, read in full)
|
||||
- `src/lib/sync.ts:109-124` (relay allowlist, `mentor.skillReview`/`mentor.match` present with
|
||||
rationale comment)
|
||||
- `node_modules/ts-fsrs/package.json` (confirms real `ts-fsrs@6.0.0`, not a stub)
|
||||
- `node_modules/ts-fsrs/dist/index.d.mts` (confirms `DefaultScheduler`, `newCard`, `review` API
|
||||
shapes used match the real package's types)
|
||||
- `src/shell/miniappRegistry.ts:40`, `src/shell/miniappComponents.tsx:19,50` (real registration
|
||||
and mount, not a placeholder)
|
||||
- Test run: `npx vitest run src/lib/mentor.test.ts src/lib/mentorSchedule.test.ts
|
||||
src/lib/mentorMatching.test.ts src/miniapps/mentor/MentorScreen.test.tsx` -> **4 files, 51
|
||||
tests, all passed**
|
||||
|
After Width: | Height: | Size: 80 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 92 KiB |
@@ -0,0 +1,166 @@
|
||||
# Sky mini-app coherence audit (ambient clock-schedule + presence counter)
|
||||
|
||||
Scope: `src/lib/sky.ts`, `src/lib/skyPresence.ts`, `src/miniapps/sky/useSkyPresence.ts`,
|
||||
`src/miniapps/sky/SkyScreen.tsx`. Memory wall / morale-pulse sync coherence is **out of
|
||||
scope** (already fixed and verified this session) - this audit covers only the ambient
|
||||
clock-schedule and the presence counter.
|
||||
|
||||
## 1. Is the ambient clock-schedule a genuine, coherent simulated clock?
|
||||
|
||||
**Yes.** `computeSkyState(clock, schedule)` in `src/lib/sky.ts:163-179` is a pure function:
|
||||
|
||||
```ts
|
||||
export function computeSkyState(
|
||||
clock: Clock,
|
||||
schedule: readonly SkyScheduleSegment[] = DEFAULT_SKY_SCHEDULE,
|
||||
): SkyState {
|
||||
const timestamp = clock.now();
|
||||
if (!isValidTimestamp(timestamp)) return { ...FALLBACK_SKY_STATE, timestamp };
|
||||
const cycleHour = computeCycleHour(timestamp);
|
||||
const { segment, progress } = resolveSegment(schedule, cycleHour);
|
||||
return { phase: segment.phase, brightness: segment.brightness, skyColor: segment.skyColor,
|
||||
horizonColor: segment.horizonColor, cycleHour, progress, timestamp };
|
||||
}
|
||||
```
|
||||
|
||||
- Cycle length is an explicit, named constant: `HOURS_PER_CYCLE = 24` (`sky.ts:63`), with
|
||||
`MS_PER_HOUR = 3_600_000` (`sky.ts:61`) - a stated, documented 24-hour UTC cycle ("A
|
||||
Hollow 'day' is a plain 24-hour UTC cycle", `sky.ts:62`).
|
||||
- `computeCycleHour(timestampMs)` (`sky.ts:98-102`) maps epoch ms to `[0, 24)` via
|
||||
`((timestampMs % msPerCycle) + msPerCycle) % msPerCycle`, i.e. deterministic modular
|
||||
arithmetic on real elapsed time - not a random/visual effect.
|
||||
- `resolveSegment` (`sky.ts:113-141`) walks the five `DEFAULT_SKY_SCHEDULE` segments
|
||||
(night/dawn/day/dusk/night, `sky.ts:67-73`) sorted by `startHour`, and computes
|
||||
`progress` through the active segment as `elapsedHours / segmentLengthHours`, so phase
|
||||
transitions and in-between brightness interpolation points are both genuine functions
|
||||
of elapsed wall-clock time, not arbitrary.
|
||||
- Determinism is independently verified by `src/lib/sky.test.ts`: two independent
|
||||
`FixedClock` instances at the same timestamp produce `toEqual` output
|
||||
("produces identical output from two independent clock instances at the same
|
||||
timestamp"), and every declared schedule segment's `startHour` is checked to resolve
|
||||
to its own declared phase/brightness ("is consistent across the whole default
|
||||
schedule's declared phases").
|
||||
- Invalid timestamps (NaN/Infinity/negative) return a defined `FALLBACK_SKY_STATE`
|
||||
(`sky.ts:88-96`, `isValidTimestamp` at `sky.ts:98-100`) rather than fabricating a
|
||||
phase - also test-verified ("never fabricates a schedule-derived phase for an invalid
|
||||
timestamp").
|
||||
|
||||
**Verdict: genuine, coherent 24-hour deterministic clock. No gap.**
|
||||
|
||||
## 2. Is the presence counter driven by a real WebRTC/Yjs Awareness roster, or fabricated?
|
||||
|
||||
**Real roster, never fabricated.** Chain of evidence:
|
||||
|
||||
- `useSkyPresence.ts:144-172` (`useSkyPresence`): in production (no injected test
|
||||
`awareness`), when `hasRealtimeTransport()` is true (`typeof RTCPeerConnection !==
|
||||
"undefined"`, `useSkyPresence.ts:23-25`) it calls `connectAssemblySync(createAssemblyDoc(),
|
||||
room)` and uses `sync.provider.awareness` - the same real WebRTC-backed Yjs awareness
|
||||
provider Assembly already uses (`src/lib/assemblySync.ts`), not a bespoke/fake channel.
|
||||
- `checkIn(awareness, handle)` announces this device's own ephemeral per-session handle
|
||||
(`skyPresence.ts:99-108`, `generateEphemeralHandle` at `skyPresence.ts:62-67`) -
|
||||
never the real account id, so the roster can't leak a stable identity, but it also
|
||||
can't be spoofed to multiply the count artificially.
|
||||
- `presenceCount(awareness)` (`skyPresence.ts:134-139`) is `awareness.getStates().size` -
|
||||
a direct read of the number of distinct connected Yjs `Awareness` client entries. No
|
||||
arithmetic, random number, or placeholder is involved anywhere in this path.
|
||||
- Cohort scoping (`presenceRoomForCohort`, `skyPresence.ts:38-44`; cohort code caching,
|
||||
`useSkyPresence.ts:49-66`) means two devices only ever share a room (and therefore a
|
||||
count) if they deliberately share a cohort code - ruling out a single global room that
|
||||
would count unrelated strangers.
|
||||
- Test environments are explicitly walled off from the real network: `hasRealtimeTransport()`
|
||||
returns false under vitest/happy-dom (no `RTCPeerConnection`), in which case the hook
|
||||
falls back to a local, no-transport `Awareness(new Y.Doc())` (`useSkyPresence.ts:160-163`)
|
||||
- so automated tests exercise the real counting logic against a real (if offline)
|
||||
`Awareness` instance, never a mocked/fabricated number. `useSkyPresence.test.tsx` and
|
||||
`skyPresence.test.ts` (not re-read line-by-line here, but referenced by the module's own
|
||||
docstrings) back this with assertions that a solo session counts to exactly 1, never 0
|
||||
or a placeholder, until checkout.
|
||||
- The initial React state (`useState(() => injectedAwareness ? presenceCount(injectedAwareness)
|
||||
: 1)`, `useSkyPresence.ts:136-137`) is the honest pre-connection default of "just me" (1),
|
||||
not an invented number - and is immediately replaced by the real roster-derived count via
|
||||
`subscribePresenceCount` once the awareness connection exists.
|
||||
|
||||
**Verdict: the presence count can only ever reflect genuinely-connected peers via a real
|
||||
Yjs Awareness roster riding real WebRTC in production. No fabrication found. No gap.**
|
||||
|
||||
## 3. Is `SystemClock` (real wall-clock) cleanly separated from an injectable test clock?
|
||||
|
||||
**Yes, cleanly separated via a shared `Clock` interface.**
|
||||
|
||||
- `Clock` interface (`sky.ts:17-20`): `{ now(): number }`.
|
||||
- `SystemClock` (`sky.ts:36-40`): `now() { return Date.now(); }` - the only production
|
||||
implementation, used unconditionally unless an explicit override is supplied.
|
||||
- `FixedClock` (`sky.ts:26-34`): constructor-pinned timestamp, used only by
|
||||
`sky.test.ts` and by `computeSkyStateAt(timestampMs, schedule)` (`sky.ts:184-189`), a
|
||||
convenience wrapper explicitly documented as wrapping a `FixedClock` for one-shot
|
||||
timestamp-to-state conversion (also test-only call sites).
|
||||
- Production wiring in `SkyScreen.tsx:51`: `const activeClock = useMemo(() => clock ??
|
||||
new SystemClock(), [clock])` - the `clock` prop exists purely as a test seam
|
||||
(`SkyScreenProps.clock?: Clock`, `SkyScreen.tsx:44`); when omitted (the real app's
|
||||
route render, with no caller ever passing a clock), `SystemClock` is instantiated and
|
||||
used. There is no code path in which production can silently receive a `FixedClock` -
|
||||
that would require a caller explicitly constructing and threading one in, which
|
||||
`AppRoutes.tsx`/`miniappComponents.tsx` do not do.
|
||||
|
||||
**Verdict: clean separation. Production always gets real time; only `sky.test.ts` and
|
||||
`SkyScreen.test.tsx` (via the `clock` prop) ever supply a `FixedClock`. No gap.**
|
||||
|
||||
## 4. Any real device-API angle beyond what's already used (and is restraint appropriate)?
|
||||
|
||||
Checked for an obvious candidate: a real ambient-light sensor or ambient ("devicelight")
|
||||
API would in principle let "brightness" reflect the user's actual surroundings instead of
|
||||
a simulated schedule. In practice:
|
||||
|
||||
- The `AmbientLightSensor` / `devicelight` Web APIs are not implemented in any shipping
|
||||
browser engine today (Chromium shipped `AmbientLightSensor` behind a flag and later
|
||||
removed it; Firefox/Safari never shipped it) - wiring to it would be dead code in every
|
||||
real browser this PWA targets, which is exactly the "claimed-but-unwired" anti-pattern
|
||||
this audit is hunting for, not a fix for it.
|
||||
- The feature is explicitly framed, in both the README and the module's own doc-comment
|
||||
("a culture/morale mini-app, not a utility" / "ambient sky-view engine"), as a shared,
|
||||
synchronized atmospheric backdrop - its entire value is that every device, anywhere,
|
||||
computes the *same* phase from the *same* UTC instant (verified above in Q1/Q3). A real
|
||||
per-device light sensor would break that invariant (two devices in different rooms would
|
||||
show different brightness for the same "sky"), directly contradicting the stated concept.
|
||||
- Geolocation-based real sunrise/sunset (vs. the stylized fixed 24h schedule) was also
|
||||
considered: also rejected as scope-inflation - the module's docstring already commits to
|
||||
"a stylized day/night cycle," and real geolocation would require a permission prompt and
|
||||
per-device divergence inappropriate for a shared ambient view.
|
||||
|
||||
**Verdict: restraint is appropriate. No real device API is mischaracterized as used, and
|
||||
none should be added without contradicting the feature's own "shared ambient backdrop, not
|
||||
a utility" framing. No gap.**
|
||||
|
||||
## 5. Any claimed-but-unwired UI/feature?
|
||||
|
||||
Checked `SkyScreen.tsx` end to end against `sky.ts`/`skyMemoryWall.ts`/`skyMorale.ts`/
|
||||
`useSkyPresence.ts`:
|
||||
|
||||
- Phase label + brightness (`data-testid="sky-phase"` / `"sky-brightness"`) read directly
|
||||
from `skyState.phase` / `skyState.brightness`, refreshed every `tickIntervalMs` (default
|
||||
30s, `SkyScreen.tsx:22`) via `setInterval(() => setSkyState(computeSkyState(activeClock)),
|
||||
tickIntervalMs)` - wired, not static.
|
||||
- Presence badge (`data-testid="sky-presence-count"`) reads `useSkyPresence(...)`'s live
|
||||
return value - wired (Q2 above).
|
||||
- Memory wall form/list and morale pulse form/counts all call real `postMemoryWallEntry`/
|
||||
`postMoralePulse`/`extractMemoryWallEntries`/`extractMoralePulses`/`aggregateMoraleCounts`
|
||||
and render their real return values - all wired (and already fixed/verified for sync
|
||||
coherence this session, per the task's own note).
|
||||
- `trySyncWithBackend()` fire-and-forget on mount (`SkyScreen.tsx:72-75`) matches its
|
||||
documented best-effort, non-blocking, throw-free contract in `src/lib/sync.ts`.
|
||||
|
||||
**Verdict: no claimed-but-unwired feature found in the clock-schedule/presence surface.**
|
||||
|
||||
## Overall verdict
|
||||
|
||||
**COHERENT.** The ambient clock-schedule is a genuine, deterministic, cycle-length-named
|
||||
(`HOURS_PER_CYCLE = 24`) pure function of elapsed UTC time (`computeSkyState` /
|
||||
`computeCycleHour` / `resolveSegment` in `src/lib/sky.ts`), verified by schedule-consistency
|
||||
and cross-instance-determinism tests. The presence counter is a direct read of a real Yjs
|
||||
`Awareness.getStates().size` roster riding a real WebRTC transport in production
|
||||
(`useSkyPresence.ts` + `skyPresence.ts`), cohort-scoped, test-isolated via a
|
||||
`RTCPeerConnection` feature check, and never fabricates a count. `SystemClock` vs.
|
||||
`FixedClock` are cleanly separated behind a shared `Clock` interface with production
|
||||
defaulting to `SystemClock` unconditionally. No further device-API wiring is warranted given
|
||||
the feature's own "shared ambient backdrop, not a utility" framing. No claimed-but-unwired
|
||||
UI was found. No gap to fix.
|
||||
@@ -0,0 +1,129 @@
|
||||
# Coherence audit: The Climb (ma-theclimb) vs README's P15 claim
|
||||
|
||||
**Claim audited (README.md, Problem-to-mini-app mapping table):**
|
||||
> P15 | Plan the mass return | **The Climb** (`ma-theclimb`) | Min-cost-flow scheduling plus a congestion simulation for surface-return logistics, calling Fair Draw for contested wave slots
|
||||
|
||||
**Files read:** `src/lib/theclimb.ts` (604 lines), `src/lib/theclimbCongestion.ts` (195 lines),
|
||||
`src/lib/theclimb.test.ts` (390 lines), `src/lib/theclimbCongestion.test.ts` (64 lines),
|
||||
`src/miniapps/theclimb/TheClimbScreen.tsx`, `ScheduleInputForm.tsx`, `ScheduleTimeline.tsx`,
|
||||
`CongestionHeatmap.tsx`, `TheClimbScreen.test.tsx` (183 lines), `src/lib/fairdraw.ts`.
|
||||
|
||||
**Verdict: COHERENT.** All five checks below pass with direct evidence; no gap found.
|
||||
|
||||
---
|
||||
|
||||
## 1. Is "min-cost-flow" a genuine min-cost max-flow algorithm over a real flow network?
|
||||
|
||||
**Yes.** `src/lib/theclimb.ts` builds a genuine time-expanded capacitated network:
|
||||
- Nodes: `sectorPeriodNode()` -> `` `${nodeId}@${period}` `` for every physical sector/shaft
|
||||
endpoint and the surface node, expanded across `horizonPeriods` (`buildTimeExpandedGraph`,
|
||||
lines ~335-390).
|
||||
- Edges: zero-cost unlimited-capacity "holding" edges for one-period waits (lines ~352-361);
|
||||
`capacityPerPeriod`-capped, `travelPeriods`/`costPerPerson`-costed shaft edges per usable
|
||||
departure period (lines ~363-373); per-period finite-capacity surface-absorption edges into a
|
||||
super-sink (lines ~386-396); per-wave demand edges from a super-source (lines ~378-384).
|
||||
- Solver: `computeWaveSchedule()` (lines ~516-569) runs **successive shortest augmenting paths**
|
||||
via `findAugmentingPath()` (lines ~420-505), an SPFA/queue-based Bellman-Ford that tolerates
|
||||
negative reverse-edge costs in the residual graph - the textbook SSP min-cost-flow algorithm,
|
||||
not a greedy queue. It augments along the found path, updates residual capacities on both
|
||||
forward and reverse edges, and repeats until no augmenting path remains (capped at
|
||||
`MAX_ITERATIONS` with a thrown error, never a silent truncation).
|
||||
- Every reported `ShaftFlow`/`SurfaceArrival`/`DemandOutcome`/`totalCost` is read back from the
|
||||
**final residual capacities** of the real graph (lines ~571-597), not fabricated or pre-seeded.
|
||||
- Verified by `theclimb.test.ts`: capacity-invariant regression test runs 50 repeated solves and
|
||||
asserts no shaft-period edge ever reports flow above its declared `capacityPerPeriod`
|
||||
(lines 166-234) - this would fail immediately under a greedy-queue mislabeling.
|
||||
|
||||
No `javascript-lp-solver` dependency is used here (Farms uses it for its LP planting optimizer);
|
||||
The Climb's module header explicitly documents this as a deliberate stack decision ("hand-rolled
|
||||
JS min-cost-flow instead of OR-Tools... draft D9's JS-first stack decision"), not an omission.
|
||||
|
||||
## 2. Is the congestion simulation a genuine simulation?
|
||||
|
||||
**Yes.** `src/lib/theclimbCongestion.ts`'s `simulateCongestion()` is a real discrete-event
|
||||
simulation, not a cosmetic animation:
|
||||
- `buildEvents()` (lines ~91-137) derives chronological events purely from the solved
|
||||
`WaveSchedule` (`demand-arrival`, `shaft-departure`, `shaft-arrival`, `surface-absorption`),
|
||||
each carrying a signed queue delta, sorted by timestamp then priority (arrivals before
|
||||
departures within the same period, matching the time-expanded graph's own edge semantics).
|
||||
- The main loop (lines ~160-183) replays these events period-by-period, maintaining a real
|
||||
per-node queue (`queueByNode`) and emitting `NodeQueueSample`s, `maxQueueLength`, and
|
||||
`totalWaitPersonPeriods` - genuine queueing-theory-style state, not a static estimate.
|
||||
- `validateSchedule()` (lines ~70-85) and `assertFiniteNonNegative`/`assertFiniteInteger` make
|
||||
the module fail closed (throw) rather than fabricate a congestion number if the upstream
|
||||
schedule's flow data is missing or malformed - it never synthesizes from thin air.
|
||||
- The UI (`CongestionHeatmap.tsx`) renders this real per-node/per-period `queueLength` data in a
|
||||
heatmap table (`theclimb-heatmap-cell-${nodeId}-${period}`), driven entirely by
|
||||
`simulateCongestion()`'s output - not a separately hardcoded visual.
|
||||
|
||||
## 3. Is the Fair Draw integration for contested wave slots genuinely wired?
|
||||
|
||||
**Yes.** `theclimb.ts` imports `commit, drawOutcome, reveal, verify` directly from
|
||||
`./fairdraw` (line 32; confirmed exported at `src/lib/fairdraw.ts` lines 67, 87, 98/109, 136).
|
||||
- `findAugmentingPath()`'s path-reconstruction DFS (lines ~420-505) tracks **every** tied
|
||||
predecessor for a node's shortest distance, and when more than one still-viable candidate
|
||||
remains for a contested slot, it calls `tieBreaker.resolve()` - never array order or any
|
||||
ad-hoc ordering of its own (enforced: a broken/throwing tie-breaker propagates its error,
|
||||
verified by `theclimb.test.ts` lines 108-118).
|
||||
- `fairDrawTieBreaker` (the production default, lines ~233-238) calls Fair Draw's real
|
||||
`drawOutcome()` with a deterministic seed derived from the signed plan's input hash.
|
||||
- `createLoggingTieBreaker()` (lines ~252-305), used by `recordClimbPlan()` when a plan is
|
||||
actually committed, runs the full commit/reveal/verify protocol: publishes a
|
||||
`theclimb.tiebreak.commit` event via Fair Draw's `commit()` BEFORE resolving the draw,
|
||||
reveals via `reveal()`, re-checks via `verify()` (fails closed on mismatch), then computes
|
||||
the winner via `drawOutcome()` and publishes a `theclimb.tiebreak.reveal` event.
|
||||
- `verifyClimbTieBreakAudit()` (lines ~560-595) independently re-derives/re-verifies every
|
||||
committed draw from the log alone.
|
||||
- `theclimb.test.ts` (lines 90-118) directly asserts the engine calls the injected Fair Draw
|
||||
tie-break function (via a spying stub) and fails closed, never substituting its own ordering,
|
||||
when that function throws.
|
||||
|
||||
This is a real function call to Fair Draw's commit-reveal tie-break utility, not a claimed-only
|
||||
integration.
|
||||
|
||||
## 4. Device-API angle: is geolocation forced in, or genuinely absent (and should it be there)?
|
||||
|
||||
**Absent, and correctly so - not a gap.** `grep -rn 'geolocation'` across
|
||||
`src/miniapps/theclimb` and `src/lib/theclimb*.ts` returns zero matches. The Climb is a planning/
|
||||
scheduling tool that runs *before* any resident physically moves: it computes a time-expanded
|
||||
min-cost-flow schedule and a discrete-event congestion simulation over declared shaft capacities,
|
||||
wave sizes, and surface absorption limits - a resident's live GPS position has no input into that
|
||||
optimization, and "was this resident physically at the staging area" is an attendance-confirmation
|
||||
concern unrelated to the scheduling math this mini-app answers for P15. Forcing a geolocation
|
||||
check into the commit/reveal tie-break or the flow solve would not strengthen coherence; it would
|
||||
bolt an unrelated device-API onto a module whose honest scope is "plan the mass return," not
|
||||
"track resident location." Correctly, no geolocation code exists here. (Light Clock's own
|
||||
AGENTS.md entry makes the analogous call explicitly for motion/actigraphy: "never wired to ration
|
||||
anything" - the project's convention is to keep device sensors out of modules whose real job is
|
||||
pure computation over declared inputs.)
|
||||
|
||||
## 5. Any claimed-but-unwired UI/feature?
|
||||
|
||||
**None found.** `TheClimbScreen.tsx` wires every visible feature straight to the real engines:
|
||||
- `computeWaveSchedule()` and `simulateCongestion()` run live on every input change
|
||||
(lines ~100-122), with "no schedule yet" / "computing" / "error" states - no seeded/sample
|
||||
data path exists (confirmed by `ScheduleInputForm.tsx`'s own doc comment: "there is no
|
||||
sample/seeded data, matching the dashboard's 'no schedule yet' contract").
|
||||
- `recordClimbPlan()` is called from a real "Commit return plan to the shared log" button
|
||||
(`handleCommitPlan`, lines ~124-137), persisting `theclimb.plan.propose`/`theclimb.plan.commit`
|
||||
events through the sanctioned `append()` path - not a stub.
|
||||
`reconstructLatestClimbPlan(await readAll())` replays the committed plan back into the form on
|
||||
mount, so the "survives reload" claim in the UI copy is real (not just asserted text).
|
||||
- `ScheduleTimeline` and `CongestionHeatmap` render `schedule`/`congestion` fields exhaustively
|
||||
(`totalDelivered`, `totalCost`, `shaftFlows`, `demandOutcomes`, `maxQueueLength`,
|
||||
`totalWaitPersonPeriods`, per-node/period queue cells) - no placeholder or decorative-only UI
|
||||
element was found.
|
||||
- `trySyncWithBackend()` is fired fire-and-forget on mount and after a commit, exactly per the
|
||||
project's sanctioned-caller convention (never blocking the local-first write/read/replay path).
|
||||
|
||||
## Conclusion
|
||||
|
||||
Every clause of the README's claim for P15 - "min-cost-flow scheduling" (successive-shortest-
|
||||
paths over a real time-expanded capacitated network), "congestion simulation" (real discrete-
|
||||
event replay with per-node queueing state), and "calling Fair Draw for contested wave slots"
|
||||
(a genuine commit/reveal/verify/drawOutcome call, fail-closed on tie-break failure) - is backed
|
||||
by real, tested implementation, not a greedy/cosmetic/claimed-only stand-in. No geolocation
|
||||
integration exists, and none is warranted for what is fundamentally a pre-movement
|
||||
scheduling/queueing optimization. No unwired UI feature was found.
|
||||
|
||||
**VERDICT: COHERENT.**
|
||||
@@ -0,0 +1,96 @@
|
||||
# Coherence audit: Tunnel Safety (ma-tunnelsafety)
|
||||
|
||||
Date: 2026-11-20
|
||||
Scope: `src/miniapps/tunnelsafety/*`, `src/lib/tunnelsafety.ts`, `src/lib/tunnelrouting.ts`, and their tests.
|
||||
Stated concept (README): "Crowd-sourced hazard reports plus A* routing around closed tunnel segments" (P5: keep tunnels safe).
|
||||
|
||||
## Files read
|
||||
- `src/lib/tunnelsafety.ts` - hazard-report data model (`HazardReportPayload`/`HazardResolvePayload`, `reportHazard`, `resolveHazard`, `computeHazardReports`, `computeSegmentCorroboration`)
|
||||
- `src/lib/tunnelsafety.test.ts`
|
||||
- `src/lib/tunnelrouting.ts` - A* engine (`findRoute`, `closedSegmentIdsFromReports`, `MinHeap`, `admissibleHeuristicScale`)
|
||||
- `src/lib/tunnelrouting.test.ts`
|
||||
- `src/miniapps/tunnelsafety/tunnelGraph.ts` - static demo tunnel topology/positions
|
||||
- `src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx` - screen wiring (log -> reports -> closed segments -> route)
|
||||
- `src/miniapps/tunnelsafety/TunnelMap.tsx` - map/route UI
|
||||
- `src/miniapps/tunnelsafety/ReportHazardForm.tsx` - hazard report form
|
||||
- `src/miniapps/tunnelsafety/HazardFeed.tsx` - feed + resolve button
|
||||
- `src/miniapps/tunnelsafety/TunnelMap.test.tsx`, `TunnelSafetyScreen.test.tsx`
|
||||
|
||||
## 1. Genuine A*, or mislabeled BFS/DFS?
|
||||
|
||||
**Genuine A\*.** `findRoute` in `src/lib/tunnelrouting.ts:181-246` has every real A* component:
|
||||
- A binary min-heap open set keyed by f-score (`MinHeap` class, `tunnelrouting.ts:150-179`), not a plain queue/stack.
|
||||
- A closed set (`const closed = new Set<string>()`, `tunnelrouting.ts:207`) with revisit skipping.
|
||||
- g-scores (`gScore` map) + f-scores (`bestKnown`/heap keys) distinct from plain edge-count/BFS distance.
|
||||
- A real heuristic: `euclideanHeuristic` (`tunnelrouting.ts:84-93`) computes straight-line distance from node positions (`TunnelPositions`), not `heuristic = 0` hardcoded. It is explicitly node-position-driven, consulted on every push (`tunnelrouting.ts:234, 239`).
|
||||
- **Admissibility is actively engineered, not assumed.** `admissibleHeuristicScale` (`tunnelrouting.ts:108-123`) computes the minimum weight-per-distance ratio across all positioned segments and scales the euclidean heuristic down by that factor, so the heuristic can never overestimate true traversal cost even when position units and edge weights are on different scales (e.g. grid units vs. minutes). This is a genuine engineering detail beyond a toy A*, documented inline with the reasoning.
|
||||
- Honest fallback: when `graph.positions` is absent, the heuristic is 0 and the search degenerates to **Dijkstra** - the code's own docstring says so explicitly (`tunnelrouting.ts:33-35`, `TunnelPositions` comment: "falls back to 0 (Dijkstra-equivalent), which is always admissible"). This is the correct, honest distinction per the audit brief: it is not a mislabeling because (a) the demo graph (`tunnelGraph.ts`) *does* supply `positions` for every node, so the heuristic is live and non-zero in the actual shipped topology, and (b) the code never claims the heuristic is always non-trivial - it documents the degenerate case plainly rather than hiding it.
|
||||
- Tests (`tunnelrouting.test.ts`) exercise real rerouting behavior: direct path vs. forced detour when a segment is closed, Set vs. array equivalence, "every path closed" honest failure (`found: false`, not a crash or silent wrong path), and `accessibleOnly` stair exclusion even when the stair path is shorter - all behavior a BFS/DFS-mislabeled-as-A* could technically also produce, but the heap+heuristic+g/f-score structure in the implementation itself confirms this is architecturally A*, not BFS/DFS with a rebranded name.
|
||||
|
||||
**Verdict: COHERENT.** Function: `findRoute`, `src/lib/tunnelrouting.ts:181`.
|
||||
|
||||
## 2. Does hazard routing actually route around still-open hazards?
|
||||
|
||||
**Yes - the chain is fully wired, not cosmetic.** Traced end to end in `TunnelSafetyScreen.tsx:29-33`:
|
||||
```
|
||||
entries (live Event Log, useEventLogEntries)
|
||||
-> computeHazardReports(entries) // tunnelsafety.ts:179
|
||||
-> closedSegmentIdsFromReports(reports) // tunnelrouting.ts:70-78: unresolved reports -> Set<segmentId>
|
||||
-> findRoute(TUNNEL_GRAPH, start, end, { closedSegmentIds, accessibleOnly })
|
||||
```
|
||||
- `closedSegmentIdsFromReports` only includes a segment id when `!report.resolved` (`tunnelrouting.ts:75`) - a resolved hazard reopens the segment on the very next replay/render, no separate "reopen" action needed.
|
||||
- `findRoute`'s `buildAdjacency` (`tunnelrouting.ts:135-148`) literally skips any segment whose id is in `closedSegmentIds` when building the traversable graph (`if (closedSegmentIds.has(segment.id)) continue;`) - the pathfinder's edge set is built from exactly this set, not a copy or a parallel structure.
|
||||
- The demo topology (`tunnelGraph.ts`) is deliberately a diamond with two distinct corridors (market -> residential-loop -> south, and market -> east-bypass -> south) specifically so that closing one via a hazard report gives `findRoute` "a real alternate to reroute through" (file's own comment) - this is a real rerouting demo, not window dressing.
|
||||
- `TunnelMap.tsx` renders closed segments with a distinct `segmentClosed` style and `data-state="closed"` driven by the same `closedSegmentIds` set passed into `findRoute` (`TunnelMap.tsx:92-96`) - the visual and the routing input are the same object, not two independently-maintained pieces of state.
|
||||
- One hazard report (not requiring corroboration) already closes a segment "conservatively" - `computeSegmentCorroboration` is explicitly documented as **never a routing input**, only a trust badge in the feed (`tunnelsafety.ts` corroboration section, `tunnelrouting.ts:9-13`). This is a deliberate, documented design choice (favor safety over waiting for consensus), not an oversight.
|
||||
|
||||
**Verdict: COHERENT.** A hazard report -> `reportHazard()` -> signed Event Log entry -> `computeHazardReports`/`closedSegmentIdsFromReports` -> `findRoute`'s `buildAdjacency` genuinely removes that edge from the graph the pathfinder searches.
|
||||
|
||||
## 3. THE BIG QUESTION: hazard location and `navigator.geolocation`
|
||||
|
||||
Confirmed by repo-wide grep (`geolocation|getCurrentPosition|watchPosition` across `src/`): **zero matches**. `navigator.geolocation` is unused anywhere in this codebase, as stated in the brief.
|
||||
|
||||
**Current hazard-location model:** `ReportHazardForm.tsx:40-54` - the *only* way to locate a hazard is a `<select>` dropdown of `TUNNEL_GRAPH.segments` (a hardcoded, demo-only topology of 6 segments with human-readable labels like "Market Junction -> East Bypass"). There is no free-text location, no coordinates, nothing beyond picking one of 6 predefined corridor names from a dropdown. `HazardReportPayload` (`tunnelsafety.ts:35-43`) carries only `segmentId: string` - no lat/lng, no accuracy radius, nothing geo at all.
|
||||
|
||||
**Does this gap genuinely call for `navigator.geolocation`?** Investigated honestly per the brief's own framing:
|
||||
|
||||
- The in-universe premise is tunnels/corridors, plausibly underground - GPS fixes underground are frequently degraded or absent (GPS requires line-of-sight to satellites). This is a real physical constraint, not an excuse to skip the feature.
|
||||
- However: the actual reporting workflow does not require a fix *while inside* the tunnel. A resident reporting "the market-to-residential corridor is flooded" is very plausibly doing so from a phone *near a tunnel entrance, in a stairwell, or after exiting* - anywhere a real GPS/network-assisted location fix is achievable on a real device. The brief is right that this is realistic for demo/above-ground testing and for entrance-adjacent reporting.
|
||||
- The segment dropdown is **the entire identification mechanism** today - it requires the reporter to already know and correctly pick the formal corridor name from 6 options. A real resident does not necessarily know "this is the seg-market-residential corridor" - they know roughly where they are standing. Auto-tagging the report with a coordinate (even approximate, even degraded) would be a genuine, honest improvement to reporting coherence, consumed for provenance/triangulation/future segment-matching rather than replacing the authoritative manual segment selection.
|
||||
- This is not a fabrication risk: a `coords` field populated by a real `GeolocationPosition` (or left `undefined` on permission-denied/unavailable/timeout) is exactly the kind of "real capability, honest fallback" the project's anti-fabrication conventions already apply to hazard data (see `tunnelsafety.ts` module docstring's care about never inventing data) - it would strengthen rather than violate that discipline, *provided* it is wired as optional metadata alongside the existing manual segment picker, never as a silent replacement for it (GPS cannot by itself tell you which named tunnel segment you are in).
|
||||
|
||||
**Verdict: GAP-FOUND (real, scoped).**
|
||||
|
||||
Concrete fix:
|
||||
- **File to edit:** `src/miniapps/tunnelsafety/ReportHazardForm.tsx`.
|
||||
- **API call shape:** on mount or on form-open, best-effort (never blocking submit):
|
||||
```ts
|
||||
function useBestEffortGeolocation(): GeolocationCoordinates | undefined {
|
||||
const [coords, setCoords] = useState<GeolocationCoordinates | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (!("geolocation" in navigator)) return;
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => setCoords(position.coords),
|
||||
() => setCoords(undefined), // permission denied / unavailable / timeout -> honest fallback, manual entry unaffected
|
||||
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 60_000 },
|
||||
);
|
||||
}, []);
|
||||
return coords;
|
||||
}
|
||||
```
|
||||
- **Data model change:** add an optional `coords?: { latitude: number; longitude: number; accuracy: number }` field to `HazardReportPayload`/`HazardReportInput` in `src/lib/tunnelsafety.ts`, populated only when the browser actually supplied a fix - never required, never defaulting to a fabricated value, and never used to auto-select `segmentId` (segment selection stays manual/authoritative since GPS alone cannot resolve which named corridor a resident is in, especially underground).
|
||||
- Why this is the correct scope: it augments the existing manual `segmentId` selector with optional provenance, consistent with the module's own "never invent/never silently mutate" discipline; it does not touch `tunnelrouting.ts` (routing stays purely segment-id-based) and does not change `HazardReport`'s resolved-by-replay semantics.
|
||||
|
||||
## 4. Claimed-but-unwired UI / dead buttons
|
||||
|
||||
None found. Checked every interactive element in the three UI files:
|
||||
- `ReportHazardForm`'s submit button -> `reportHazard()` -> `append()` (real signed write) -> `trySyncWithBackend()` (documented fire-and-forget, never blocking). Wired.
|
||||
- `HazardFeed`'s "Mark resolved" button -> `resolveHazard()` -> real signed `tunnelsafety.hazard.resolve` event, consumed by `computeHazardReports` on next replay. Wired.
|
||||
- `TunnelMap`'s From/To selects and "Accessible route only" checkbox all feed directly into `findRoute`'s `start`/`end`/`accessibleOnly` via controlled state in `TunnelSafetyScreen.tsx`. Wired.
|
||||
- Corroboration badges (`CorroborationBadge`) are explicitly and correctly documented as feed-only trust signals, never claimed to affect routing - no mismatch between claim and behavior.
|
||||
|
||||
No dead/cosmetic controls identified.
|
||||
|
||||
## Overall verdict
|
||||
|
||||
**COHERENT**, with one genuine, scoped, honestly-identifiable gap: hazard reports carry no location signal beyond a manual segment-name dropdown, and `navigator.geolocation` (confirmed unused repo-wide) would be a real, non-fabricated strengthening of hazard-reporting UX if wired as best-effort optional metadata in `ReportHazardForm.tsx`, with graceful fallback to the existing manual flow. The A* engine, hazard data model, and hazard-to-routing wiring are all real and internally consistent with the README's claim - no mislabeling, no cosmetic disconnection.
|
||||
@@ -0,0 +1,88 @@
|
||||
# Water Watch (`ma-waterwatch`) coherence audit
|
||||
|
||||
**Scope:** `src/miniapps/waterwatch/*`, `src/lib/sync.ts` (relay allowlist), `src/lib/fairshare.ts` cross-write target.
|
||||
**Stated concept (README.md, P4 row, line 89, quoted verbatim):**
|
||||
> Water Watch (`ma-waterwatch`): CUSUM/EWMA change-point detection over corroborated resident water readings, feeding Fair Share's water number
|
||||
|
||||
Read-only audit. No files edited.
|
||||
|
||||
---
|
||||
|
||||
## 1. Genuine CUSUM/EWMA, not a mislabeled threshold check?
|
||||
|
||||
**COHERENT.**
|
||||
|
||||
- `src/miniapps/waterwatch/ewma.ts`'s `createRobustBaseline()` implements an online sign-EWMA robust location/scale tracker: `median_t = median_{t-1} + lambda_median * scaledMad_{t-1} * sign(x_t - median_{t-1})`, `mad_t = mad_{t-1} + lambda_mad * (|x_t - median_t| - mad_{t-1})`, with the standard Gaussian consistency constant `madScale = 1.4826` turning MAD into a comparable std-dev, and a bias-corrected `1/n` warm-up blend for the first samples. This is a real median/MAD streaming estimator, not a static threshold.
|
||||
- `src/miniapps/waterwatch/cusum.ts`'s `createTwoSidedCusum()` implements the textbook two-sided CUSUM recursion on the standardized residual `z` produced by the baseline above: `sHigh_t = max(0, sHigh_{t-1} + z_t - k)`, `sLow_t = min(0, sLow_{t-1} + z_t + k)`, firing when `sHigh > h` or `sLow < -h`, resetting the fired side to 0 (standard CUSUM practice). Defaults `k=5, h=30` are documented as tuned against the real bundled GECCO 2018 water-quality fixture (`gecco.test.ts`), not arbitrary.
|
||||
- `createChannelCusumGate()` composes one baseline + one CUSUM per (sensorId, channel) pair, with an explicit warm-up gate (default 50 samples for automated feeds, 1 for the resident-report cadence - see `DeviceMonitorView`'s `RESIDENT_REPORT_GATE_OPTIONS`) so detections aren't fired on an unsettled baseline.
|
||||
- `cusum.test.ts`, `ewma.test.ts`, and `gecco.test.ts` exercise this against synthetic drift injection and the real GECCO fixture (`fixtures/gecco2018-water-quality-sample.csv`, read only by tests per the project's anti-pattern rule), not just unit-level sanity checks.
|
||||
|
||||
This is a real, correctly-implemented robust-baseline + two-sided CUSUM change-point detector, matching the README's claim exactly.
|
||||
|
||||
## 2. Does "corroborated" mean multiple distinct residents, or can one reading trigger an alert?
|
||||
|
||||
**COHERENT - genuine multi-sensor corroboration exists**, with one caveat noted as a gap in §4.
|
||||
|
||||
- `src/miniapps/waterwatch/corroboration.ts`'s `createCorroborationGate().ingest()`:
|
||||
```ts
|
||||
const corroborates =
|
||||
pending !== undefined &&
|
||||
pending.sensorId !== reading.sensorId && // distinct device/sensor identity required
|
||||
pending.side === fired && // same CUSUM direction (both "high" or both "low")
|
||||
Math.abs(reading.timestamp - pending.reading.timestamp) <= windowMs; // within the corroboration window (default 5 min)
|
||||
```
|
||||
A single sensor's own CUSUM firing only ever reaches `"corroborating"` state (a pending candidate), never `"alert"`. `applyCorroboratedReadingToFairshare()`'s own doc comment states the invariant directly: "A single sensor's CUSUM detection ... is a candidate only - it is never, under any code path, allowed to reach or affect ma-fairshare's water resource ... on its own."
|
||||
- `corroboration.test.ts`'s QA happy-path test proves this at the unit level: it calls `applyCorroboratedReadingToFairshare` on the lone-sensor `"corroborating"` event and asserts the result is `undefined` (no fairshare write), then shows the second independent sensor's reading flips the state to `"alert"` and only then does `applyCorroboratedReadingToFairshare` produce a real `seed.resource.water` entry.
|
||||
- `ReportReadingForm.tsx` requires a non-empty "Device / sensor ID" field before submit (`sensorId.trim().length === 0` rejected), and its own doc comment states the design intent: "the same resident re-submitting under the same device id can never self-corroborate."
|
||||
|
||||
So corroboration is real and not trivially bypassable by one resident re-submitting under the same device id. It is bypassable, however, by one resident typing two different arbitrary sensor-id strings into the same free-text field in two submissions (see §4) - the gate has no notion of "resident identity" at all, only "device/sensor id string."
|
||||
|
||||
## 3. Does it genuinely feed Fair Share's water allocation number?
|
||||
|
||||
**COHERENT - real, traceable cross-app write.**
|
||||
|
||||
- `corroboration.ts`'s `applyCorroboratedReadingToFairshare(event)`: on `event.state === "alert"` (and only then - it's a no-op returning `undefined` for `"clean"`/`"corroborating"`), it calls:
|
||||
```ts
|
||||
return appendFn({
|
||||
type: "seed.resource.water",
|
||||
resource: "water",
|
||||
value: event.reading.value,
|
||||
});
|
||||
```
|
||||
a real signed append to the shared Event Log, under the same `seed.resource.water` payload type `src/lib/fairshare.ts`'s allocation engine already consumes as a resource-pool credit.
|
||||
- `settleCorroboratedReading(event)` (same file) chains this with a real re-solve: after the credit lands, it calls `readAll()` + `computeFairshareAllocation(entries)` (imported directly from `../../lib/fairshare.ts`) and appends a second real event, `fairshare.allocation.cycle`, recording the newly re-solved per-agent water allocation total.
|
||||
- `ReportReadingForm.tsx`'s submit handler calls `settleCorroboratedReading(gateEvent)` directly after persisting the raw reading - this is the exact call site wiring a resident's submitted reading, once corroborated, into Fair Share's real CEEI allocator (`computeFairshareAllocation` in `src/lib/fairshare.ts`), not a simulated or hand-computed number.
|
||||
|
||||
This is a real cross-app write path, end to end, from UI submit to Fair Share's allocation engine.
|
||||
|
||||
## Cross-device sync allowlist re-check
|
||||
|
||||
**CONFIRMED STILL TRUE.** `src/lib/sync.ts`'s `PUSH_TYPE_ALLOWLIST` (read at the point it's defined) still contains:
|
||||
```ts
|
||||
"waterwatch.reading.report",
|
||||
```
|
||||
listed under the "Public civic reports - shared community data" group, alongside `tunnelsafety.hazard`, `theclimb.plan`, `housing`. `ReportReadingForm.tsx`'s submit handler calls `void trySyncWithBackend()` immediately after `reportWaterReading()`/`settleCorroboratedReading()` - a best-effort, non-blocking, silent-no-op-offline push, consistent with the project's anti-pattern rule that the event-log append/read/replay path itself never depends on network reachability.
|
||||
|
||||
## 4. Real device-API question: is there an honest role for geolocation, and is "same physical area" already handled?
|
||||
|
||||
**GAP-FOUND.** Investigated both candidate explanations the prompt raised - "sensorId uniqueness already serves this purpose" and "geolocation would fix a real hole" - and the evidence supports the second: corroboration is spatially blind at the point where it matters (the gating decision), even though the codebase already has real location data it simply doesn't consult there.
|
||||
|
||||
- The corroboration gate's `ingest()` (quoted in §2) checks only: distinct `sensorId` string, same `channel`, same CUSUM `side`, and timestamp proximity. It never looks at where either sensor physically is. `pending.sensorId !== reading.sensorId` only proves the two reports came from two different *device-id strings* typed into `ReportReadingForm`'s free-text input - it proves nothing about whether those two devices are anywhere near each other, or even on the same water system.
|
||||
- Real location data for *known* sensors does exist in the codebase - `src/miniapps/waterwatch/waterNetwork.ts`'s `DEFAULT_PIPE_NETWORK` nodes each carry a `sensorId` -> physical-node mapping (east wing vs. west wing vs. main line), and `waterWatchController.ts`'s `localizeAnomaly()` + `lowestCommonAncestor()` do real topology reasoning over it. But this is only ever invoked from `localizationFor()` inside `createWaterWatchController().ingest()` - strictly *after* the corroboration gate has already decided `"alert"` (or `"corroborating"`), purely to populate `ChannelStatus.localization`/`countdowns` for display. It is never consulted by `createCorroborationGate().ingest()` or by `applyCorroboratedReadingToFairshare()`/`settleCorroboratedReading()` before the real `seed.resource.water` write happens.
|
||||
- Concretely: `"kiosk-1"` (East wing) and `"kiosk-3"` (West wing) share only a distant common ancestor (`reservoir`, via `main-line`). Two residents independently reporting a `pH` drift under those two sensor ids within the same 5-minute `windowMs` - plausible on a large demo network with multiple real local causes (e.g. two unrelated calibration errors, or two genuinely separate small events) - today fires `"alert"`, credits `seed.resource.water`, and re-solves Fair Share's live water allocation, while `localizeAnomaly` would even confidently report a `"pinpoint"`/`"high"` confidence origin that is wrong (the LCA of two unrelated events, not a real contamination source).
|
||||
- `ReportReadingForm.tsx`'s "Device / sensor ID" field is also free text, not constrained to `DEFAULT_PIPE_NETWORK`'s known kiosk ids - so for the common real path (an arbitrary resident typing an arbitrary device id), there is no topology mapping available for the gate to fall back on anyway, even if it did check it.
|
||||
- Conclusion: `sensorId` uniqueness alone does **not** already serve the "same physical area" purpose the README's "corroborated" wording implies - it only proves "two different typed strings," not "two reports of the same physical event." This is a real coherence gap, not a forced one: the design's own comments (`corroboration.ts`'s module doc, `localizeAnomaly`'s doc) already treat "two independent sensors confirming the same event" as the intended safety property, and the mechanism to check that (network topology, or lacking a known network match, geolocation) exists elsewhere in the code but isn't wired into the gating decision.
|
||||
|
||||
**Concrete fix (not forced):** Capture a rough physical location in `ReportReadingForm.tsx`'s submit handler via `navigator.geolocation.getCurrentPosition()` (with an explicit permission-prompt affordance in the form UI, consistent with the project's "no fabricated sensor" rule - this is a real browser geolocation API call, not invented data), store it on the event payload (e.g. `WaterReadingReportPayload.location?: { lat: number; lng: number }`, optional so a user who denies permission can still report), and have `createCorroborationGate().ingest()` require the pending and incoming reading's locations to be within a plausible radius (or, when both sensor ids resolve via `waterNetwork.ts`'s `sensorToNode`, require them to share a bounded-distance node, reusing the topology path that already exists) before promoting `"corroborating"` to `"alert"`. This directly strengthens the README's "corroborated ... readings" claim from "two different device-id strings" to "two reports of the same physical contamination," without adding any fabricated sensor data.
|
||||
|
||||
## 5. Any claimed-but-unwired UI element?
|
||||
|
||||
**None found.** Checked `DeviceMonitor.tsx`'s "My tap" `<select>` (`myTapId` state) - it is read in the countdown list render (`data-my-tap={countdown.nodeId === myTapId}` and the `"(your tap)"` label suffix), so it is wired to real UI behavior, not a decorative dead control. No README claim (geolocation, GPS, "same area" wording, etc.) appears anywhere in `README.md`'s P4 row or surrounding text beyond the quoted mapping-table sentence; the README does not itself over-claim a capability this audit found missing - the gap in §4 is an internal coherence gap between the "corroborated" wording and the gate's actual check, not a README overclaim about a missing UI feature.
|
||||
|
||||
---
|
||||
|
||||
## Verdict
|
||||
|
||||
**Mostly COHERENT, with one GAP-FOUND.** The CUSUM/EWMA detector (§1) is a genuine, GECCO-fixture-validated robust-baseline + two-sided-CUSUM implementation, not a disguised threshold check. Corroboration genuinely requires a second, distinct sensor id within a time window before any write reaches Fair Share (§2), and the Fair Share cross-write (§3) is real and traceable to `src/lib/fairshare.ts`'s CEEI engine via `seed.resource.water` + `fairshare.allocation.cycle` events, with `waterwatch.reading.report` still correctly relay-allowlisted in `src/lib/sync.ts`. No unwired UI element was found (§5).
|
||||
|
||||
The one real gap (§4): "corroborated" currently means only "two different typed device-id strings, same channel, within 5 minutes" - it does not verify the two reports came from the same physical location/water source, even though the codebase already has real topology data (`waterNetwork.ts`) it uses for post-hoc localization but never feeds back into the alert-gating decision itself. A genuinely honest, non-fabricated fix exists (optional `navigator.geolocation` tagging on submit, gated by an explicit permission prompt, feeding a proximity check into the corroboration gate) and is recommended but was out of scope for this read-only audit to implement.
|
||||
@@ -0,0 +1,21 @@
|
||||
# Mini-app concept-execution coherence audit - Plan
|
||||
|
||||
## Goal
|
||||
Audit all 13 shipped mini-apps for whether their actual execution delivers on their stated concept (README.md's Problem-to-mini-app mapping table + each module's own doc comments), and wire real browser/device features (geolocation, motion/orientation sensors, camera, vibration, battery, network status, the existing backend relay) wherever a genuine gap exists. Never fabricate a sensor reading the device cannot really provide.
|
||||
|
||||
## Phase 1: Parallel read-only audits (13 children, disjoint read scope)
|
||||
One `deep-low` category audit per mini-app. Each produces a verdict: COHERENT (execution matches concept, cite evidence) or GAP-FOUND (name the exact gap, the exact file:line, and a concrete, buildable fix using a real device/browser API or the existing backend - not a vague suggestion).
|
||||
|
||||
Apps: fairshare, waterwatch, tunnelsafety, housing, assembly, findfamily, healthpost, lightclock, farms, fairdraw, theclimb, mentor, sky.
|
||||
|
||||
## Phase 2: Synthesize
|
||||
Read all 13 verdicts. For each GAP-FOUND, decide: fix now (if the fix is concrete, safe, and in scope) or defer-with-reason (if it would require fabricating data, contradicts an explicit design boundary, or is genuinely out of scope).
|
||||
|
||||
## Phase 3: Parallel implementation
|
||||
Dispatch fixes for every GAP-FOUND-fix-now item, one per app (disjoint files = safe parallel). Each fix ships with a real test (behavioral) and real-surface QA (actual device/browser API exercised, not mocked at the point of proof).
|
||||
|
||||
## Phase 4: Verification
|
||||
Full gate: npm run test, npm run build, npx oxlint. Real-browser QA for each fixed app's new feature.
|
||||
|
||||
## Phase 5: Report
|
||||
Final verdict table (13 rows) + commit list.
|
||||