Files

104 lines
13 KiB
Markdown

# THE COMMONS — Adversarial Edge-Case & Stress-Test Log
A record of deliberately trying to **break** every feature — boundary values,
malformed input, empty/cold states, double-submit, reload/replay, concurrency,
and feature-specific attacks. Each case is **HELD** (behaved correctly under
attack) or **BREAK** (defect found); every BREAK lists its reproduction, root
cause, fix, and re-verification.
**Result: 24 real breaks found and fixed at root cause.** Full combined gate
green afterward — `npm run test` **689 passed** (87 files; +21 regression tests
over the 668 baseline), `npm run build` exit 0, `npm run lint` exit 0.
## Method
- **Pure engines** (ledger, CEEI, CUSUM/corroboration, housing, tunnel routing,
fairdraw, governance, farms, theclimb, circadian, manifest) probed by
importing the real `.ts` modules into a Bun kernel and throwing adversarial
inputs at them directly.
- **UI / IndexedDB / mount / DB-replay paths** driven through the real shipped
app in real Chromium (Playwright, repo-native), seeded via `/admin`.
Screenshots: `.omo/evidence/edge-cases-browser/` + `.omo/evidence/adv-upload-admin/`.
- Fanned out across the shell + engine-core (orchestrator, in-kernel) and **six
parallel domain agents**, each owning a disjoint file set, plus a browser
adversary. Every fix carries a regression test; all were validated together by
the single combined gate above.
## The dominant failure mode: non-finite poisoning
15 of the 24 breaks were the same class — a `NaN` or `Infinity` slipping past a
`typeof === "number"` / `Number.isNaN`-only guard at a trust boundary (a payload
matcher, a form field, an engine input) and then poisoning a derived value: a
clearing price, a circadian trajectory, a fairness-debt ledger, a sensor
baseline. The systemic fix was **validate finiteness at every boundary** where
untrusted data (a typed form value, a P2P-synced CRDT row, a replayed event)
enters an engine. This directly serves the project's "no fabricated / corrupt
data" principle.
## All breaks found & fixed
| # | Feature | Break (repro) | Root cause | Fix |
| --- | --- | --- | --- | --- |
| 1 | Water Watch | blank/non-numeric Reading value stored as a fabricated `0` | `Number("") === 0` passed a `Number.isNaN`-only guard | require `value.trim()` non-empty + `Number.isFinite` before coercion |
| 2 | Water Watch | a single `NaN` reading permanently poisons a channel baseline → silent dead channel | non-finite value never rejected at the gate | reject non-finite `reading.value` at the corroboration gate |
| 3 | Water Watch | `NaN` reading survives replay → re-poisons every reload | `isWaterReadingReportPayload` checked only `typeof` | add `Number.isFinite` |
| 4 | Fair Share | floor consuming the whole pool → `Infinity` clearing price | residual-0 good re-entered CEEI divide-by-supply | write floor to allocations; only `residual>0` goods enter the sub-market |
| 5 | Fair Share | `Infinity` need → NaN allocation/utilities/prices | `isFairshareNeedPayload` lacked finiteness | add `Number.isFinite` |
| 6 | Fair Share | `Infinity`/`NaN` supply → NaN allocations | `isSeedResourcePayload` lacked finiteness | add `Number.isFinite` (non-finite → unseeded) |
| 7 | Fair Share | `NaN` allocation-cycle → NaN trend slope | `isAllocationCyclePayload` lacked finiteness | add `Number.isFinite` (drop point) |
| 8 | Housing | `NaN`/`Infinity` score/capacity → `NaN` fairness-debt signed into events, poisoning all future cycles | numeric finiteness never validated at the input boundary | reject non-finite capacity (and `<0`) / score via `HousingInputError` |
| 9 | Tunnel Safety | A\* returned **suboptimal (longer) routes** when coord scale ≠ edge-weight scale | raw euclidean heuristic not admissible/consistent | scale heuristic by `min(weight/euclideanLen)` → provably consistent; verified vs brute-force Dijkstra |
| 10 | Assembly (QV) | duplicate P2P-synced credit rows double-counted a resident's weight | tally iterated rows without per-resident collapse | collapse credits by `(proposalId,residentId)` (last-writer-wins) before tallying |
| 11 | Fair Draw | empty participants committed a draw then `drawOutcome(seed,0)` threw → stuck "verifying" | component published a draw it could never resolve | refuse empty draws (no commit; empty-state note) |
| 12-14 | Light Clock | negative / huge(`1e400`→∞) / `NaN` lux → `NaN` circadian phase & amplitude | `Math.pow(light,1.5)` NaN on neg/overflow poisoned RK4 | make `lightDrive` finite over its physical domain + reject non-finite lux at the form |
| 15 | Light Clock | non-finite / huge `hours` → **unbounded integration loop (hang/OOM)** | fixed-step RK4 with no finiteness/termination bound | throw on non-finite hours/step + `MAX_SIMULATION_STEPS` cap + honest UI error |
| 16 | Farms | `NaN` baseTempC → `NaN` cumulative GDD | `baseTempC` unvalidated (only tmin/tmax were) | `assertFiniteNumber(baseTempC)` |
| 17 | Farms | `NaN` yield/maturity/area → misleading result + NaN-leak into Fair Share's signed ledger | those fields unguarded | finite-only validation for all numeric crop/plot fields |
| 18 | Farms | overflow temps `1e308` → `Infinity` GDD | `(tmax+tmin)/2` overflowed | overflow-safe `tmax/2 + tmin/2` |
| 19-21 | The Climb | `Infinity` demand / shaft capacity / surface capacity → self-contradictory schedule | finiteness not checked | `Number.isFinite` guards (skip/throw) |
| 22 | The Climb | non-integer `readyPeriod` (1.5, UI-reachable) → silent 0-delivered | integer check missing (others had it) | integer check → throws → honest UI error card |
| 23 | Upload/manifest | **extra unknown manifest field leaked into stored manifest + the share wire** | `assertValidManifest` returned `input` as-is | reject unknown keys; return a reconstructed `{name,icon,entryPoint,permissions}` |
| 24 | Upload/manifest | duplicate permissions accepted; 200k-char name accepted | no dedupe / length bound | reject duplicate permission; cap name ≤200, entryPoint ≤1024 |
---
## Platform core (orchestrator, in-kernel) — all HELD
**Ledger / replay / conflicts (9/9 HELD):** basic issue; negative issue → clamps to 0 (no negative mint); `NaN` issue → 0 (no corruption); huge → `Infinity` no crash; overdraft transfer rejected (credit floor 0); unknown payload ignored; replay deterministic under shuffle/reverse; empty log → 0; **Lamport-tie double-spend** (same signer, equal `lamportTs`) → throws `UnresolvedLamportTieError` (never silently resolved); earlier-Lamport-wins flags the loser `refund`.
*(My first tie probe used different signers and correctly did not throw — a false positive in my test, corrected; the guard fires as designed.)*
**Fair Share core (4/4 HELD):** empty log, supply-but-zero-agents, single agent (full supply), need-but-zero-supply — all honest, no NaN/crash. *(Extended + 4 breaks fixed by the domain agent — see table.)*
**Water Watch core (4/4 HELD):** same-sensor self-corroboration never alerts; two independent sensors → alert; 2nd sensor outside the 5-min window stays corroborating; flat signal stays clean. *(+3 breaks fixed — see table.)*
## Cross-cutting UI / mount / DB (real-browser adversary) — 9/10 HELD, 1 BREAK (fixed)
Evidence: `.omo/evidence/edge-cases-browser/`. Admin seed invalid inputs rejected with no partial write; demo idempotency; malformed-manifest upload rejected; non-XHTML mount → visible parse error (shell intact); Sky double-submit guard = 1 entry; **Water Watch blank value = BREAK #1 (fixed)**; reload persistence (alert survives cold replay); cold/empty states honest; NotFound routes safe.
---
## Domain adversarial matrices (six parallel agents)
### Assembly / governance + Fair Draw — 42 probes, 2 breaks fixed (74 tests green)
BREAKS #10, #11 (above). HELD: QV credits ≫ budget → finite sqrt weight; exactly-at-budget; negative/NaN/Infinity credits throw; delegation cycles A→B→A, 5-node, 10k-hop all terminate (no stack overflow); self/nonexistent delegation; double ballot counted once; zero ballots no NaN; Fair Draw tampered seed/salt → `verify()` false (never a winner); re-roll/second-reveal/no-prior-commit rejected; determinism; winner index in `[0,n)` across 250 draws. **Follow-up (verified already fixed):** `putResidentCredit` still accepts any credit *value* via the unsigned P2P CRDT, but that value is never the vote-weight source — hand-traced `extractQvBallots` (`src/lib/governanceEvents.ts:136-157`) into `computeQvTally` (`src/lib/governance.ts:269-339`) confirms weight is derived solely from the signed Event Log's clamped ballot credits, with the CRDT `.credits` field read only as a membership marker. Residual (disclosed, not duplicated here): Sybil/self-enrollment buying one extra vote at the clamped honest weight — see ECONOMY.md's "Personhood / Sybil resistance" bullet.
### Housing + Tunnel Safety — breaks #8, #9 fixed (35 tests green)
HELD: infeasible (more residents than capacity), zero slots/residents, all-equal tie determinism (20 runs), fairness-debt across 30 cycles (rotates, bounded, no starvation), impossible-constraint resident, negative/NaN space report rejected, duplicate slot ids safe; tunnel disconnected graph, all segments closed, start==end, unknown nodes, accessible-only routing, cyclic graph optimal, hazard on nonexistent segment ignored. **Follow-ups (by-contract):** negative edge weights → negative distance (weights documented `>0`); fractional sub-1 capacity from idle-hours scaling (intended).
### Light Clock + Health Post + Mentor + Sky + Find Family — 72 probes, 4 breaks fixed (230 tests green)
BREAKS #12-15 (Light Clock). HELD: **Health Post** any danger sign → `urgent_referral`; ages 0/1/60/-5/12.5/NaN rejected, 2 & 59 accepted; fast-breathing threshold exact ±1 both age bands; missing/NaN/negative fields rejected. **Mentor** at-risk boundary, 0-holders vs unknown→insufficientData, empty→[]. **Sky** empty→zero counts, invalid mood rejected, bad timestamp→fallback state, double-post guard. **Find Family** exact/case/whitespace match, honest `null` no-match, **PSI: the query name never appears in any event (only ids + hex ristretto points)**.
### Farms + The Climb — breaks #16-22 fixed (44 tests green)
HELD: empty temps → insufficientData; negative temps → GDD clamps at 0; tmin>tmax well-defined; crop never matures → honest infeasible; zero area/energy → honest empty; more crops than plots → picks best; demand>capacity → partial + outstanding; zero capacity/shafts/single-period honest; congestion tie-break deterministic totals.
### Upload / manifest / mount + Admin seed — 30 engine + 17 browser cases, 4 breaks fixed (120 tests green)
BREAKS #23, #24 (manifest). HELD: missing/empty/wrong-type name/icon/entryPoint, unknown permission, permissions-not-array/null, non-object root all rejected naming the field; non-XHTML mount (`&&`, `<`, unclosed, empty) → visible parse panel, shell intact; throwing mount script non-fatal; double-click = 1 event; admin invalid inputs → inline reject + **zero events (no partial write)**; demo idempotency (2nd click 0 events).
---
## Known limitations & follow-ups (not regressions; root outside scope or by-design)
- **Credit-value forgery (Assembly QV): verified already fixed.** `putResidentCredit` still accepts any credit *value* via the unsigned P2P CRDT, but that value is never the vote-weight source: `extractQvBallots` (`src/lib/governanceEvents.ts:136-157`) feeding `computeQvTally` (`src/lib/governance.ts:269-339`) confirms weight is derived solely from the signed Event Log's clamped ballot credits, with the CRDT `.credits` field read only as a membership marker. Dedup (#10) closes the duplicate-row multiplier on top of that. Residual (disclosed, not a live gap): Sybil/self-enrollment buying one extra vote at the clamped honest weight, see ECONOMY.md's "Personhood / Sybil resistance" bullet.
- **`ceeiSpike.ts` divide-by-supply** has no zero/non-finite guard; fixed at the caller (#4/#6), a solver-level guard would be defense-in-depth.
- **Negative edge weights / fractional capacity / negative congestion cost:** by-contract engine-only overrides, not UI-reachable.
- **Test-isolation:** an intermittent `IdentityMissingError` in the full vitest run (a mounted mini-app's fire-and-forget `append` outliving a test teardown) — did not recur on the final green run; flagged as test-hygiene cleanup in `MountedMiniapp.test.tsx`.
- **`ECONNREFUSED :3000/:3001`** in tests/dev is the offline best-effort backend relay — a throw-free no-op, by design.
## Final verification
`npm run test` → **689 passed (87 files)** · `npm run build` → exit 0 · `npm run lint` → exit 0. All 24 fixes carry regression tests; none weakened or skipped.