Files
faunosteo/.claude/tasks/plans/2026-10-13-rust-r2-domain-core.md
bchanot ee0700887f feat(domain): R2.1 Rust contracts of the sheet, report and archive documents
Sheet document v2, report v3 / v2 / identity, migration map, sheet snapshot,
branding, PDF labels and archive envelope ported from the Zod schemas with
their exact semantics: strict objects where Zod is strict, optional fields
absent (never null), nullable fields required, integers as JavaScript
numbers, UTF-16 caps, hand-checked patterns, url crate for .url(), lone
surrogate escapes read as U+FFFD (L1, owner confirmation pending).
Fields in Zod schema order (PDF labels in the engine dictionary order):
the curated and legacy sheets, the demo report and the three frozen
archive envelopes print byte for byte as their Zod / attachment form.
ts-rs types regenerated; plan rev 2 after three plan challenges.
2026-10-14 00:04:01 +02:00

114 lines
27 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# PLAN — Rust R2: domain core (contracts, rules, sheet handle, reducers) + app switch
- date: 2026-10-13 | branch: `feature/rust-r2-domain-core` (off develop 1a7ee7d)
- spec: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (rev 2 + Annex C), rows II.2 / VI.2 R2 / VI.3 R2 / VI.4, decisions D-R11, D-R12 (gated functions ported, behaviour preserved), D-R13; owner brief 2026-10-13 (R2 go)
- out of scope: R3 (sanitiser, layer renderer, compose), R4 (PDF reader byte scan, writer, report-compare CLI), R5 (pipeline, importer, upload tool, `packages/domain` deletion), Step 9, CI/CD, deploy, release 0.2.0, any graphic change
- stop: after R2 delivery; no merge into develop before the owner's validation
## 0. Facts this plan rests on (inventory 2026-10-13)
- `packages/domain` (2,298 lines, 9 test files): sheet schema (strict Zod), 21 integrity rules, `createEmptySheetDocument`, `buildSheetIndex` (10 closures over Maps, last duplicate wins), report v3 / v2 (strip Zod), migration map, `migrateReportV2ToV3`, `readReportDocument`, `rebaseReportOnSheet`, archive snapshot (`buildSheetSnapshot`, `assertSnapshot` with caps, `snapshotIndexSource`), envelope v1 (`readArchiveDocument`, `ReportArchiveEnvelopeSchema`), branding, labels (25 keys).
- Consumers of `packages/domain` after R2: `packages/pdf` (engine, R4), `packages/anatomy` (pipeline + render, R3/R5), `apps/app/scripts` (`report:compare`, R4), N-1 test fixtures. The app `src/` stops importing it (VI.4).
- App logic to move: `services/zoneInteraction.ts` (213 lines: click decision + 7 reducers + `collectVertebrae` / `syncVertebrae`), `FindingsTreePicker.toggleLeaf` (Finding builder), `VertebraPicker` toggle / all / none, `reportStore` rules (`newReport`, `emptyObservation`, add / remove / move / replace), `persistence` parsing (draft via `readReportDocument`, archive via `ReportArchiveEnvelopeSchema`), `sheets/provider` parsing, `pdf/import.ts` layered read (via engine `readReportArchive` = byte scan + `readArchiveDocument`), `pdf/export.ts` `buildSheetSnapshot`, `packages/supabase` publish gate (`assertPublishable`).
- Display helpers kept in TypeScript (review II.2 class C): `zoneLabel`, `describeZone`, `zoneTrees`, `unresolvedFindings`, import message lines, `isIdentityComplete`, `pickLabel`, `FreeTextFindingInput` trimming (form glue), identity / conclusion / recommendations / next-appointment setters (Zustand assignments of form values; no validation exists today, adding one is a behaviour change: deviation from the review's "set_* validation", stated).
- Routes are static imports; `HomeRoute` and `NewReportRoute` call `useSheet` today (the sheet bundle loads on `/`).
- The engine's `readAttachedDocument` returns `JSON.parse` output after a depth pre-scan capped at 64; `readReportArchive` = that + `readArchiveDocument` + error mapping (`incompatible_version` when a numeric unknown version, else `no_attachment`).
- Zod 3.25.76 semantics to reproduce: object output in schema key order; `.optional()` = absent ok, `null` rejected, absent stays absent; `.nullable()` = key required unless `.default(null)`; `.strict()` rejects unknown keys, others strip; `.int()` = `Number.isInteger` (accepts `2.0`, `1e20`); `.min/.max` on strings count UTF-16 units; `.url()` = `new URL()` succeeds; `.uuid()` = Zod regex; JS regex `$` = end of input; discriminated unions dispatch on the tag.
- R0 facts kept: `serde_json` `preserve_order` + `float_roundtrip`, `js_number` formatter, panic = abort on wasm32, an instance is unusable after a trap, a fresh instance needs a fresh glue module record (cache-busting import).
## 1. Decisions of this plan (internal; trade-offs stated)
| # | Decision | Why / alternative rejected |
|---|---|---|
| P1 | Every JSON input is read `text → serde_json::Value → typed`. Before parsing, a pre-pass rewrites `\uD800`–`\uDFFF` escapes that are not a valid surrogate pair to `�` (JSON.parse keeps lone surrogates, serde_json refuses them). Recursion limit 128 (drafts and bundles < 20 deep; archive JSON is pre-scanned at 64 by the TS scanner). | Value-first gives JSON.parse duplicate-key semantics (last value, first position) and lets one parse feed both the layered reader and the typed structs. Refusing lone surrogates would lose a whole report that TypeScript accepts; replacing them is the smallest divergence (leniency decision L1, pinned by a fixture, reported). |
| P2 | Typed structs use serde derive plus field helpers that reproduce Zod: `opt` (absent ok, `null` refused, skipped when `None`), `nullable` (key required, `null` ok), `nullable_default` (absent → `null`), `deny_unknown_fields` exactly where Zod is `.strict()`. Integers are `JsInt` (any finite number with an integer value, kept as f64, printed by `js_number`). Constrained strings are newtypes checked by hand (UTF-16 length, the id / region / colour / sha256 / base64 / uuid / branding-URL patterns). `.url()` = `url` crate parse (WHATWG, as `new URL`), size measured; no `regex` crate. | Serde's implicit `None` for a missing `Option` and its `null`-as-`None` would silently widen what Zod accepts. f64 integers keep `1e20` or `2.0` accepted and printed as JavaScript does. |
| P3 | Discriminated unions (views, annotations, geometry, next appointment, image asset) are untagged enums whose variant structs carry a literal tag field at the Zod schema position (annotations and views: `kind` after the common fields; geometry, next appointment, image asset: tag first). Every struct declares its fields in Zod schema order. | Zod parse output order = schema order; serde's internally tagged enums would print the tag first and break byte equality with `JSON.stringify(ZodSchema.parse(x), null, 2)`, which is the strongest serialisation oracle available. D-R11 (struct order) holds. |
| P4 | Behaviour is ported site by site, quirks included: index maps last-duplicate-wins (as `new Map`), `viewsById` first-wins in the rules, `find` first-wins for `spineAnnotation` and tree paths, JS truthiness (`detailSourceId ""` → main view, `vertebrae: []` kept, `requiresVetReferral: false` dropped), `??=` on rebase labels, `unsupported_envelope` keeping the report origin, a malformed map entry failing the read (no new "never throws" behaviour). | Owner rule: no business behaviour change without a decision. Unifying policies is a later decision, not a side effect. |
| P5 | `SheetHandle` (wasm-bindgen struct) owns the loaded sheet: status, ref, species, schema version, normalized document, assets, asset hashes, migration map and the Rust index. `handle.index_data()` returns `SheetIndexData` once: normalized document, `viewById` / `annotationById` / `findingZoneById` / `regionByCode` (positions, last wins), `annotationsByView` (positions, document order), `spine[region][view]` (position, first wins), `spineIds`, `names[annotationId]`, `nodeKeys` (paths reachable by first-wins walk). The app's `SheetIndex` becomes a class over that data with today's method names (accessors only, `Object.hasOwn`), plus `ops` = the sheet-bound core calls. The handle does not run the integrity rules at load (today's behaviour); a missing main view is a load failure. | ~14 modules keep calling `sheet.annotation(id)` etc., no wasm call in a render, no rule in TypeScript. The canvas keeps the TS renderer (R3) on the normalized document and the TS asset record. |
| P6 | One core call per user action. `zone.click` returns the decision and, when the observation changes, the new observation, plus what the UI needs (`sidesPresent` for the laterality picker, `zoneIndex`). The vertebra picker's initial selection (`collectVertebrae`) is computed when the picker opens (click or chip), never in render. Vertebra grid display (`count`, `count_range`, extended state) stays React. | Review III.3 rule 1 (no call in a render path). |
| P7 | Store: every report entering the store passes the core (`report.new`, draft restore, import, `hydrateReport`), every observation write passes `report.replace_observation` (shape-checked, stripped), list rules are core calls (`add` / `remove` / `move` observation). Field assignments of form values stay Zustand (see §0). A failed core call leaves the state unchanged and raises the `core.action_failed` alert. `hydrateReport` now parses (the "stores as is" characterisation test changes by design, stated). | "Rust parser = single entry" (review I.2); one-line delegations. |
| P8 | Lazy core: `useSheet` (editor, new report) and the import action load it; `HomeRoute` gets the sheet availability from the bundle without the core and loads the core only when a file is chosen; `/login`, `/app/*`, Mon compte never reference it. The glue JS and the `.wasm` are emitted as Vite assets (`?url`), never bundled into a route chunk, fetched on first need. | Owner: no wasm on pages that do not need it. |
| P9 | Runtime: synchronous calls after `await ready()`. A `WebAssembly.RuntimeError` poisons the instance: the failing call returns `{ok:false, kind:'internal'}`, a fresh instance is created in the background (cache-busting dynamic import of the glue asset URL + new `WebAssembly` instance), sheet handles are rebuilt lazily from their retained source text, calls made meanwhile return `core_unavailable`. A load failure (fetch, CSP, compile) gives `core_unavailable` with `retry()` evicting the cached promise. | Review III.3 rules 5 and 6; R0 proof (no reuse after a trap). Async calls everywhere would reintroduce the double-click races the click chain avoids with `getState()`. |
| P10 | Two wasm builds: `packages/core-wasm/pkg/` (shipped, no `proofs` feature) and `pkg-proofs/` (trap exports, tests only). | R0 follow-up "drop --features proofs at R2"; the trap test still needs a trap. |
| P11 | Import = engine byte scan (`readAttachedDocument`, TS, frozen until R4) → `JSON.stringify` → core `archive.import` (layered read + rebase in one call) → the same `ImportError` mapping. Export = core `archive.snapshot` → frozen TS engine (still asserts and writes). | D-R12 go; R4 owns the scanner and the writer. |
| P12 | Draft quarantine: an unreadable `osteo:draft` or `osteo:archive` moves to `osteo:quarantine` (JSON list of `{key, at, raw}`, newest last, cap 10) before anything overwrites it; the draft case raises the `editor.draft_quarantined` alert. | VI.3 R2 row; today's silent drop is a loss. |
| P13 | Publish gate: `publishSheetVersion(client, versionId, validate)` takes the core validator (dependency injection); conformance fixtures `crates/core/tests/conformance/*.json` (document, Rust issues with paths, SQL codes) run in cargo and in a generated `supabase/tests/011_sheet_conformance.sql`; a cargo drift test regenerates and compares the SQL file. | Review III.4. |
| P14 | N-1 reader: the Zod schemas shipped at 1a7ee7d copied verbatim under `packages/core-wasm/tests/n-1/` (frozen, survives R5); a vitest parses every Rust-written report, draft, snapshot and envelope fixture with them. | Review III.3 rule 7, VI.3. |
| P15 | Parity corpus: a TS generator mutates small valid bases (report v3, report v2, horse-slice document, snapshot, branding, labels, envelope, migration map) field by field (delete, `null`, wrong type, empty, unknown key, `2.0`, `-1`, `1e20`, long strings at the caps) and records Zod's outcome (accepted output text or refused); committed under `crates/core/tests/parity/`; cargo asserts the same outcome and byte-equal output; a vitest drift test re-runs Zod on it while `packages/domain` exists. | "Freeze with the old code, then switch" without a dual-run harness. |
| P16 | `apps/app/src` imports nothing from `@faunosteo/domain` (ESLint `no-restricted-imports`); `pickLabel` moves to `apps/app/src/i18n/pickLabel.ts`; types come from `@faunosteo/core-wasm` (ts-rs). The `apps/app` package keeps the dependency for `scripts/` (R4). | VI.4. |
| P17 | App image: wasm stage (`rust:1.99.0-bookworm`, wasm target, `wasm-bindgen-cli` at the `Cargo.lock` version, BuildKit cache mounts) before the Node stage; nginx serves a precompressed `.wasm.gz` (`gzip_static`) when the module is present, else `gzip on` for `application/wasm` (decided on the image's `nginx -V`). Size budget test: served module ≤ 600 KB gzip. | D-R13; the VPS never builds (DEPLOY.md note). |
| P18 | CSP proof on the real image: headless Chromium behind an nginx with the DEPLOY.md headers runs the editor path (new report, zone click, picker, export, import); a variant without `'wasm-unsafe-eval'` shows the degraded state while `/login` stays usable. | VI.2 R2 end criteria. |
Visible strings, wording validated by the owner 2026-10-13 (the recommended options):
- `sheet.core_unavailable`: « Le moteur de calcul de Faunosteo n'a pas pu être chargé. Vos données de session sont conservées. » / "Faunosteo's computation engine could not be loaded. Your session data is kept."; `sheet.core_retry`: « Réessayer » / "Retry" (editor and new-report degraded notice).
- `core.action_failed` (alert): « Cette action n'a pas pu être appliquée. Réessayez ; votre bilan n'a pas été modifié. » / "This action could not be applied. Try again; your report was not changed."
- `editor.draft_quarantined` (alert): « Le brouillon de cet onglet n'a pas pu être relu par cette version de Faunosteo. Il a été mis de côté, pas supprimé. » / "This tab's draft could not be read by this version of Faunosteo. It was set aside, not deleted."
- `home.import.error_core_unavailable` (import error line): « Le moteur de lecture n'a pas pu être chargé. Réessayez l'import. » / "The reading engine could not be loaded. Try the import again."
## 2. Core operations (facade `call(op, json)` and `SheetHandle.call(op, json)`)
Envelope unchanged: `{"ok":true,"value":…}` | `{"ok":false,"kind":…,"detail":…}`. Kinds: `invalid_json`, `invalid_shape`, `unknown_op`, `internal`, plus per-op kinds below.
Free ops:
- `sheet.check` (document) → `{issues: SheetIssue[], publishable}`; `invalid_shape` when the strict schema refuses.
- `sheet.create_empty` ({species_id, name}) → document.
- `report.new` ({draft, sheet: SheetRef, id, createdAt, observationId}) → Report (draft observations kept, else one empty observation with `observationId`).
- `report.add_observation` ({report, id}) → Report; `report.remove_observation` ({report, index}) → Report; `report.move_observation` ({report, index, direction: 'up' | 'down'}) → Report (no-op at the ends); `report.replace_observation` ({report, index, observation}) → Report (`invalid_shape` when the observation does not parse).
- `vertebra.select` ({selection, action: {kind:'toggle', region, index} | {kind:'all', region, count} | {kind:'none', region}}) → Vertebra[].
- `archive.parse_envelope` (envelope JSON) → envelope (full v1 schema, shape tier, as `ReportArchiveEnvelopeSchema`).
Sheet ops (`SheetHandle`):
- constructor `SheetHandle.load(bundleJson)` → handle | error kind `invalid_sheet`; `index_data()` → `SheetIndexData`.
- `draft.restore` ({draft: string, archive: envelope | null}) → `{report, rebase: RebaseOutcome}`; kinds `unsupported_version {found}`, `invalid`.
- `archive.import` (attachment data) → `{read: ArchiveReadOutcome, rebase: RebaseOutcome}`; kinds `incompatible_version {found}` (numeric unknown version), `no_attachment` (anything else).
- `archive.snapshot` ({report}) → SheetSnapshot.
- `report.rebase` ({report, archived: snapshot | null}) → RebaseOutcome.
- `zone.click` ({observation: Observation | null, annotationId}) → `{kind: 'ignore' | 'open_view' | 'activate_fallback' | 'open_vertebra_picker' | 'open_laterality_picker' | 'remove_both_sides' | 'toggle', viewId?, observation?, zoneIndex?, sidesPresent?}`.
- `zone.add_sides` ({observation, annotationId, sides}) → Observation; `zone.remove_at` ({observation, index}) → Observation.
- `vertebra.initial` ({observation, zoneIndex}) → Vertebra[]; `vertebra.sync` ({observation, selection, viewId}) → Observation.
- `finding.toggle` ({observation, findingZoneId, path, side?}) → Observation (adds the built finding with snapshots and the vet flag, or removes the matching one).
## 3. Phases (one commit or more each; checkpoints reported when a consumer switches)
- **R2.0 Freeze (TS, before any switch)**: the three archive envelopes (`demo`, `v2full`, `v2unresolved`, fr, fixed `exportedAt`) and their bare reports exported by the current path, committed as goldens; N-1 schema copy; parity corpus generator + corpus; `horse-slice.ts` and `mini-sheet.ts` converted to JSON fixtures; characterisation of the click chain and store outputs that no test pins (exact objects).
- **R2.1 Contracts in Rust**: `domain/js.rs` (JsInt, UTF-16 lengths, patterns, own-key semantics, surrogate pre-pass), sheet schema, report v2 / v3 / identity / migration map, snapshot / branding / labels / envelope structs, ts-rs export; parity corpus green; byte equality with `JSON.stringify(Zod.parse(x), null, 2)` on the seed draft, demo report, v2 fixtures.
- **R2.2 Rules in Rust**: 21 rules + `check`, `create_empty`, index + `SheetIndexData`, `readReportDocument` + migration (612-leaf suite), rebase (exact objects), snapshot build / assert (caps, depth), envelope layered read (decision table); suites ported from `packages/domain/tests` with their exact expectations; conformance fixtures + generated pgTAP + drift test.
- **R2.3 Editor rules in Rust**: zone click + reducers (13-case suite + characterisation), finding toggle, vertebra initial / sync / select, report ops.
- **R2.4 Facade + runtime**: `crates/wasm` (`call`, `SheetHandle`, no proofs in the shipped build), `packages/core-wasm` runtime (lazy, poison, re-instantiate, retry, Node and browser sources, typed client), the trap / load-failure / handle-rebuild tests, size test.
- **R2.5 App switch**: provider + `useSheet` (+ degraded state), `SheetIndex` class, store + persistence + quarantine, click chain + pickers + findings picker, import / export, Home lazy core, publish gate, ESLint restriction, `pickLabel` move, codemod of type imports; deletion of `services/zoneInteraction.ts`, `services/sheetIndex.ts` re-exports and the data-building code in components; app suites green with their assertions (renamed calls only, each changed assertion listed).
- **R2.6 Images and serving**: Dockerfile wasm stage, `.dockerignore`, nginx compression, `check:all` stages (two wasm builds), CSP headless proof on the image, measurements (raw / gzip size, instantiate time, op timings, page-load impact, memory).
- **R2.7 Docs and gates**: RUST.md R2 section (migrated components, deleted TS, exceptions, measurements, census), CLAUDE.md, WORKSPACE.md, TEST_STRATEGY.md, packages/README.md, DEPLOY.md note, CHANGELOG; verifier + security gates; memory; owner manual procedure on the LAN.
## 4. Oracles (end criteria, review VI.2 R2 row)
1. Domain suites ported to cargo with exact expectations (validate code + path lists, migrate incl. 612 leaves, rebase exact objects, envelope decision table, branding / labels, snapshot caps); parity corpus 100 % equal.
2. App service / store / component / route suites pass on the core with their assertions; changed assertions listed one by one.
3. The three frozen envelopes: the Rust-path export parses with the frozen N-1 Zod schemas and is semantically equal (deep equal) to the frozen one; bytes differ only by key order (D-R11).
4. The 39 step6 goldens and the seed golden untouched (`git diff --stat` on their dirs empty).
5. `pnpm build` with the wasm; the module is not referenced by the auth / account chunks; served module ≤ 600 KB gzip.
6. App image boots under the production CSP headers in headless Chromium (editor path works); without `'wasm-unsafe-eval'` the editor shows the degraded state and `/login` works.
7. A deliberate trap (proofs build) re-instantiates and the next call succeeds with a rebuilt handle.
8. `pnpm check:all` green; `pnpm db:test` on the real stack with the generated pgTAP file; verifier CONFORME; security PASS.
9. Grep census: no `@faunosteo/domain` import under `apps/app/src`; no `decideZoneClick` / `syncVertebrae` / `buildSheetIndex` / `buildSheetSnapshot` / `rebaseReportOnSheet` / `readReportDocument` reachable from `apps/app/src`.
10. Owner manual FR / EN flow on the LAN (procedure delivered).
## 5. Revision 2 (2026-10-14, after three plan challenges: correctness CONCERNS(2), robustness FATAL(7) incl. 1 BLOCKER, simplicity CONCERNS(3); 45 findings)
Supersedes the rows of §1–§4 it names.
- **P7 replaced** (all three lenses): only core-built observations and reports enter the store through the core (`report.new`, draft restore, import, the reducers' outputs). Form-value edits of an observation (comment, severity, free text, finding removal by identity) stay Zustand assignments, like the identity and text setters. `report.replace_observation` is dropped. Store actions that call the core return `{ ok }`; callers (`NewReportRoute`, `HomeRoute`, the click chain) stop on failure (no navigation, no picker). `hydrateReport` is deleted (test-only seam; tests seed with `hydrateImport` or `setState`).
- **Editor degraded state (robustness BLOCKER 1, correctness 11)**: `useSheet` gets `core_unavailable` and `invalid_sheet` states; `EditorRoute` never redirects in those states, renders the notice + retry, and never restores or overwrites `osteo:draft` while the core has not read it. Test: reload `/editor` with the core failing, draft intact.
- **Runtime (robustness 2, 3, 9, 10)**: every sheet op resolves the handle through the runtime with an instance generation; calls into a poisoned glue record are refused (including `free`). The compiled `WebAssembly.Module` is kept; one spare glue record is pre-imported after a successful load so a re-instantiation needs no network; at most 3 re-instantiations per page, then `core_unavailable` ("reload"). `retry()` clears the runtime, `useSheet` and provider caches. A vitest `globalSetup` fails (never skips) when `pkg/` or `pkg-proofs/` is missing or its build stamp (hash of `crates/**` + `Cargo.lock`, written by `scripts/wasm-build.sh`) differs from the tree. The trap → re-instantiate → next call test also runs once in headless Chromium on a build linked to `pkg-proofs` (best effort; recorded if not obtainable).
- **Quarantine (robustness 4, 5, 16; simplicity 13; correctness 10)**: only the content kinds (`invalid`, `unsupported_version`) quarantine; any other kind leaves the keys untouched and shows the degraded state. Raw text goes to `osteo:quarantine:draft` / `osteo:quarantine:archive` (newest only); the source key is removed only after the quarantine write succeeded; a draft rebased with unresolved items keeps its raw pre-rebase text in `osteo:quarantine:draft-pre-rebase`. Paths that never read the draft (New report / Import from Home after a reload) keep today's semantics (a new session replaces the tab draft). No recovery UI at R2 (stated residual).
- **SheetIndexData minimal (simplicity 3, correctness 3)**: `mainViewId` (first `main` view by position), `viewById`, `annotationById`, `findingZoneById` (positions, last wins), `names[annotationId]`, `spineIds` (last-wins annotation, observable with a region), `nodeKeys` keyed by the JSON text of `[zoneId, ...path]` (collision-free) reachable by the first-wins walk on the last-wins zone, plus the normalized document. No `annotationsByView`, `spine`, `regionByCode` (no TS reader after the switch). `regions()` reads the document.
- **Ops (simplicity 4, correctness 4, 8, 13)**: exposed only with a TS caller: `sheet.check` (publish gate), `report.new`, `report.add_observation`, `report.remove_observation`, `report.move_observation`, `vertebra.select` (called in the tap handler, never in a state updater), sheet ops `draft.restore` ({draft: string, archive: string | null} → report, rebase, parsed archive or `archiveRejected`), `archive.import`, `archive.snapshot`, `zone.click` (returns the initial vertebra selection for `open_vertebra_picker`), `zone.add_sides`, `zone.remove_at`, `vertebra.initial` (chip path), `vertebra.sync`, `finding.toggle` (takes the clicked leaf's position among its siblings; parents walked first-wins as `findNode`). `sheet.create_empty`, `report.rebase`, `archive.parse_envelope` are Rust functions with cargo tests, no op. The failure envelope gains an optional numeric `found` (js_number).
- **Oracles (simplicity 2, correctness 1, 5, 6, 7, 12)**: the full mutation corpus is dropped. Instead: (a) Zod output oracles of the reference documents (`crates/core/tests/oracles`, done: draft and legacy sheets, demo v3, v2 fixtures, migration map, byte-equal); (b) a characterisation set frozen from the TS functions for the quirks (`detailSourceId: ""`, `requiresVetReferral: false`, `vertebrae: []`, `collectVertebrae` concatenated-key collision, `syncVertebrae` region order and second spine zone, rebase `??=`, malformed map entry, numeric literals `3.0` / `1e0`, lone surrogate lowercase escapes); (c) a table of hostile inputs per constraint site with Zod's accept/refuse verdict (vitest writes it with `MAKE_R2_ORACLES=1`, cargo asserts it); (d) type-level equality of ts-rs types against `z.output` per contract (vitest `expectTypeOf`); the golden-report helper switches to the core migration for the Rust run; the publish-gate tests use the real Node core. Oracle 9 reworded: "not imported by `apps/app/src`" (the engine keeps its TS index and reader until R4).
- **Fail-closed publish gate (robustness 17)**: `publishSheetVersion(client, versionId, validate)`, `validate` required; anything but `{ok: true, value: {publishable: true}}` throws before the RPC; test with a failing core.
- **Pages (simplicity 11)**: Home and `/new` read the sheet availability from the bundle without the core; the core loads at `/new` submit, on an import file pick, and in the editor.
- **Display glue accepted (simplicity 12)**: `VertebraPicker` `has` and the grid extent, `FindingsTreePicker` `matches` / `isLeafSelected` / `countSelectedUnder`, `ObservationCard` `zoneTrees` / `unresolvedFindings` / `describeZone`, import message lines: render-time predicates over core data, listed in the RUST.md census.
- **Docker / serving (robustness 12, 14, 15, 13; simplicity 9, 10)**: `packages/core-wasm/package.json` in the manifest COPY list; `pkg-proofs/` git- and docker-ignored; wasm-bindgen runs in the same RUN as the cache-mounted cargo build; the wasm-bindgen version shares the builder's `ARG` line, `scripts/wasm-build.sh` keeps the `Cargo.lock` guard; a check that the shipped `pkg/faunosteo_wasm.d.ts` has no proof export. CSP proof = `docker/csp-proof` extended to the app image: with the keyword the editor loads and one zone click works; without it the editor shows the degraded state and `/login` works; network-level assertion that `/login` and `/app/account` request neither the glue nor the `.wasm`; Firefox and WebKit too when their Playwright builds are present (else recorded). DEPLOY.md: R2+ images are never built on the VPS; the CSP must carry `'wasm-unsafe-eval'` before an R2 image is deployed.
- **Kept, with reason**: the N-1 verbatim copy (already committed; permanent, survives R5); `vertebra.select` in the core (review II.2 class A, owner listed "Sélection vertébrale"); one gate for R2 with an owner-facing checkpoint report after R2.4 (no stop: the owner asked to stop after R2).
- **Interim risks stated (robustness 8, 11)**: the import reads up to the 16 MiB attachment in the long-lived main instance until R4 moves it to a Worker; no React error boundary is added (no UI change at R2), every core entry point catches.
- **Owner decision to confirm at delivery (correctness 9)**: L1, a lone UTF-16 surrogate escape in a draft or an archive becomes U+FFFD instead of refusing the document.
- `pickLabel` → the existing `apps/app/src/i18n/pickLocaleLabel.ts` (object overload), no new copy (simplicity 6). `mini-sheet.ts` conversion dropped (R3/R5, simplicity 8). `url` crate size measured at R2.4 against the budget (simplicity 14).