From 78636d0bd5c75a5eaaa0bcb1191b687edf2659e3 Mon Sep 17 00:00:00 2001 From: bchanot Date: Tue, 27 Oct 2026 22:36:48 +0100 Subject: [PATCH] docs(docs): draft V1-2 anatomical sheets contract, record V1-1 merge --- CLAUDE.md | 9 +- docs/development/V1-1_OWNERS_ANIMALS.md | 9 +- docs/development/V1-2_ANATOMICAL_SHEETS.md | 1005 ++++++++++++++++++++ 3 files changed, 1016 insertions(+), 7 deletions(-) create mode 100644 docs/development/V1-2_ANATOMICAL_SHEETS.md diff --git a/CLAUDE.md b/CLAUDE.md index 1e4b83d1..10b99407 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,12 +49,13 @@ MVP species: equine only for anatomical sheets (V1-1.4 records ten species of an Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1-2 sheets from Supabase, V1-3 cloud bilans, V1-4 stored PDF and sharing, V1-5 mobile and accessibility pass (`docs/development/IMPLEMENTATION_PLAN.md` §0; V1-1 contract `docs/development/V1-1_OWNERS_ANIMALS.md`: -business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on -`feature/v1-1-clients-animals` V1-1.1 to V1-1.5 (validated) and V1-1.6 are built: migrations `20261025100000_workspaces.sql`, +business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; V1-1 merged into +`develop` 2026-10-27, merge 9135d73: migrations `20261025100000_workspaces.sql`, `20261025110000_clients.sql` and `20261026100000_animals_relations.sql` (contract §8.3), tested on PGlite and the isolated stack -`pnpm db:sandbox`, not applied to Supabase DEV; V1-1.3 the native modal dialog (D13) and the Playwright + axe suites +`pnpm db:sandbox`, applied to Supabase DEV 2026-10-27 by the owner procedure (SUPABASE.md §3.3); V1-1.3 the native modal dialog (D13) and the Playwright + axe suites (D14, `docs/development/BROWSER_TESTS.md`); V1-1.5 the client screens (`/app/clients`, contract §11.7) and V1-1.6 -the animal screens and the relations (`/app/animals`, contract §11.8; D11: drawer only, no tab bar) on the isolated stack). +the animal screens and the relations (`/app/animals`, contract §11.8; D11: drawer only, no tab bar)). +V1-2 contract (draft, owner review pending): `docs/development/V1-2_ANATOMICAL_SHEETS.md`, branch `feature/v1-2-anatomical-sheets`. --- diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index b908134f..eb46c17b 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -12,14 +12,17 @@ authorised V1-1.2. V1-1.2 and V1-1.3 were validated on 2026-10-25 and 2026-10-26 (BDR-076; brief « Validation V1-1.3 et autorisation V1-1.4 Animaux et relations », BDR-077), which authorised V1-1.4. Migrations M1 (§8.1), M2 (§8.2) and M3 (§8.3) are written and tested on the isolated stack -(`pnpm db:sandbox`, SUPABASE.md §5.1); none is applied to Supabase DEV (owner -procedure: SUPABASE.md §3.3). V1-1.4 was validated on 2026-10-26 (brief +(`pnpm db:sandbox`, SUPABASE.md §5.1), then applied to Supabase DEV on +2026-10-27 through the owner procedure of SUPABASE.md §3.3, run on the owner's +authorisation. V1-1.4 was validated on 2026-10-26 (brief « Validation V1-1.4 et autorisation V1-1.5 Interface Clients »), which authorised the client screens of V1-1.5 (§11.7), built and tested on the isolated stack. V1-1.5 was validated on 2026-10-26 (brief « Validation V1-1.5 et autorisation V1-1.6 Interface Animaux et clôture »), which authorised the animal screens and the relations of V1-1.6 (§11.8), built and tested on the -isolated stack, and the closure inventory (§15). +isolated stack, and the closure inventory (§15). The owner ran the browser +acceptance on DEV on 2026-10-27, and V1-1 was merged into `develop` on +2026-10-27 on the owner's go (merge commit 9135d73). Branch: `feature/v1-1-clients-animals`. Roadmap position: `IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays the permission frame of Step 10. The file name keeps "OWNERS" so the documents diff --git a/docs/development/V1-2_ANATOMICAL_SHEETS.md b/docs/development/V1-2_ANATOMICAL_SHEETS.md new file mode 100644 index 00000000..91d272bc --- /dev/null +++ b/docs/development/V1-2_ANATOMICAL_SHEETS.md @@ -0,0 +1,1005 @@ +# V1-2 Anatomical sheets: contract + +Status: DRAFT for owner review (V1-2.0, 2026-10-27). The owner approved the +eight functional orientations D1 to D8 of the V1-2 framing audit and added the +mandatory requirement D9, administration of official sheets from the +application, in the brief « V1-2.0 : contrat fonctionnel et technique des +fiches anatomiques » (BDR-081). Everything else in this file (architecture, +data model, rules, step split, the options of §17) is a proposal until the +owner ratifies it. V1-2.0 changes no code, migration, policy, RPC, anatomical +data or DEV state. + +This revision integrates three fresh plan challenges of the first draft +(correctness, robustness, simplicity; 2026-10-27). Their blockers and the +changes they caused are listed in §19. + +Branch: `feature/v1-2-anatomical-sheets` (off `develop` 9135d73, the V1-1 +merge). Roadmap position: `IMPLEMENTATION_PLAN.md` §0, V1-2. This contract +absorbs plan Step 13 (provider over Supabase, sheet library) and, for official +sheets only, the editor of plan Step 17 at the level described in §8.2. The +community parts of Steps 17 and 18 (personal sheets, sharing, follows, forks) +stay out. + +Parts: 1 facts, 2 scope, 3 nomenclature, 4 decisions D1 to D9, 5 roles and +permissions, 6 lifecycle, review and publication, 7 species and new sheets, +8 editor, 9 drawings, 10 loading, 11 screens and journeys, 12 SQL defects and +migrations, 13 security, 14 equine sheet, 15 tests, 16 implementation steps, +17 decisions for the owner, 18 documents touched by V1-2.0, 19 challenge +record. + +--- + +## 1. Facts the contract rests on + +State of `develop` 9135d73 and of Supabase DEV, read on 2026-10-27 in a +read-only session (`default_transaction_read_only=on`). Line numbers refer to +`supabase/migrations/20261008110000_anatomical_sheets.sql` unless named. + +| Area | State | +|---|---| +| Document model | Rust core, `crates/core/src/domain/sheet/schema.rs`, schema version 2, strict (`deny_unknown_fields`). Root: `species_id`, `name`, `description`, `scope_disclaimer` (FR/EN), `attribution`, `vertebral_config.regions` (ordered, `count`, optional `count_range`), `references`, annotation `categories`, `views` (one main, details with `parent_view_id`, own drawing or `view_box` crop), `annotations` (`point`, `zone`, `detail_trigger`; geometry circle, polygon or path, optional: an annotation without geometry draws nothing), `finding_zones` (categories of kind `dysfunction`, `consultation_reason`, `anamnesis`, `custom`; recursive nodes with `requires_vet_referral`, `reference_ids`). | +| Element identity | Annotation ids are unique in the document. Finding category and node ids are unique among siblings only (`validate.rs` l.409-421): in the equine draft, the 811 categories and nodes share 310 distinct ids (`mechanical` appears 19 times). A finding element is identified by its path key `/` (`report/migration_map.rs`), which changes when a node moves. | +| Review metadata | `review_status` (`inherited` default, `reviewed`, `to_confirm`) on annotations, finding categories and nodes. Stored, read by no gate (SQL, app, PDF). | +| Integrity | `validate_sheet_document`: 21 codes, 19 errors and 2 warnings (`annotation.no_findings`, `finding_zone.unreferenced`). SQL mirror `private.sheet_document_issues`: 17 of the 19 errors (no `view.parent.cycle`, no `finding.id.duplicate`) plus `document.shape`, `reference.url.scheme`, `view.asset.unknown`. The SQL shape check tests the presence of arrays only; it is not the strict schema. | +| Fingerprint | `sha256-rfc8785-validated-v1`, computed by the core only, refused for a document with an error-level issue (`fingerprint.rs` l.260-265); SQL cannot compute it. It covers `svg_asset_id` values. Equine draft `12d78872…`; the v0 alias is bound to sheet `503dc301…` only (`fingerprint.rs` l.44-49, `rebase.rs` l.42-45). | +| Creation | `create_empty_sheet_document(species_id, name)`: one main view `view-main` without drawing, empty collections. No other authoring operation exists in the core. | +| Tables | `species` (10 rows, `other` included), `anatomical_sheets` (monolingual `name`, `slug`, `description`), `anatomical_sheet_versions` (`draft`, `published`, `deprecated`; one draft per sheet; numbers never reused), `anatomical_sheet_assets` (rows unique per sheet and sha256, `uploaded_at`). | +| Immutability | `guard_sheet_version_update` freezes published rows except the deprecation transition, comparing a fixed column list (l.219-232). `guard_sheet_version_delete` refuses `published` only (l.275-278): a deprecated version can be deleted physically today (pgTAP `005_anatomical_sheets.sql` l.551 asserts it). | +| RPCs | 12 for authenticated callers (create, create_draft, publish, deprecate, delete_version, fork, archive, restore, delete_sheet, set_visibility, register_asset, delete_asset) plus `confirm_sheet_asset_upload` (service role). | +| Access | `can_edit_sheet` (l.494-510) = creator of a non-deleted sheet, or any platform owner or admin on an official sheet; it gates every lifecycle RPC, the draft, version and asset policies and the Storage read. `can_use_sheet` = active sheet and (public or editable). Editors update draft `content` and `change_note`, and sheet `name`, `slug`, `description`, by direct table UPDATE: no RPC, no audit, no concurrency check. | +| Storage | Bucket `anatomical-sheet-assets`: private, SVG only, 20 MiB. Object key `.svg`, shared by every sheet that registers the same bytes. Read through `private.can_read_sheet_asset_object` (confirmed row, editor or non-draft version of a usable sheet). No write policy for API roles. The operator tool `pnpm assets:upload` reads the asset table with the service key over PostgREST, writes `.svg`, re-hashes an existing object, and confirms (`crates/core/src/bin/upload_sheet_assets/storage.rs`). | +| SVG reader | The core reader removes anything off its allowlist (`metadata`, `text`, `style`, `sodipodi:*`, `inkscape:*`, …) and a drawing with any removal is refused, never repaired (`sanitize.rs`, `loaded.rs`, LRN-055). Typical vector-tool exports are therefore refused; the equine drawing passes because the R5 pipeline cleaned it (`curation/draft/drawing.rs`). | +| Publication gate | Server: `publish_sheet_version` runs the SQL integrity rules and the unknown-asset check. Client: `packages/supabase/src/anatomical-sheets.ts` `publishSheetVersion` reads, validates, then publishes. | +| Application | No access to sheet tables. The report editor renders the bundled sheet (`SHEET_BUNDLE=draft` in the dev server and preview builds, `none` in a default build). `SheetProvider.getReferenceSheet(speciesId)` only. `LoadedSheet` requires a report migration map, which the session passes to the report and archive readers (`session.rs` l.85, l.120); drawing bytes are not checked against their sha256 at load. | +| Archive caps | `SnapshotCaps`: 64 views, 1 024 annotations, 8 192 finding nodes (categories counted), depth 8, labels 512 UTF-16 units, 4 drawings, 2 MiB per drawing, 6 MiB in total. A PDF snapshot carries every view and every reachable drawing, so these caps bound any sheet that must stay exportable. `archive::SheetStatus` is `draft` or `published`, part of the strict snapshot contract. | +| Roles | `platform_role`: owner, admin, moderator, support. DEV holds one owner. No professional status (plan Step 9). | +| MFA | TOTP enrolment and verification enabled server-side (up to 10 factors); no `has_mfa()` helper, no enrolment UI (`IDENTITY.md` §4). Owner follow-up 7.10 (2026-10-12): MFA mandatory before any sensitive admin feature. | +| Worker | Rust worker R1 (keyed job loop, sandboxed decode child) serves avatars only and links no core module (`crates/worker/src/main.rs`). Stopped on DEV (AVATAR-01). | +| Seed | `equine_draft.sql` converges: it overwrites the draft's content whenever it differs and the sheet has one version, and runs in every environment (`SUPABASE.md` §3). The report editor's bundle reads the same seed folder. | +| DEV data | 12 migrations. One sheet `503dc301…` (equine, official, `private`, `active`, no current version), one version v1 `draft` (schema 2, content identical to the seed draft), one drawing row `7f767f74…` confirmed 2026-10-23, its object at `.svg`. Audit: `version.created`, `asset.uploaded`. | +| Design | The validated mockup (`docs/design/`) shows a sidebar entry « Fiches anatomiques »; no sheet screen and no administration screen are drawn. V1-1 built its client and animal screens from existing components without a new mockup. | + +--- + +## 2. Scope + +In V1-2: + +1. an administration space where authorised staff list, filter and create + official sheets, edit drafts (structured editor and minimal visual tool, + §8.2), upload drawings, preview, read the completeness report, submit to + review, review, publish, deprecate and archive, with the full history; +2. a traceable review workflow and an atomic publication gate on the server; +3. a read-only catalogue of published official sheets for eligible signed-in + users; +4. loading of a stored version into the Rust core for preview and catalogue, + with integrity checks on the document, the fingerprint and the drawings; +5. hardening of the existing SQL lifecycle; +6. the preparation of the equine review, without publication. + +Out of V1-2: personal and community sheets, sharing, follows, forks, +marketplace, editing by students, grants scoped by species, the level 2 editor +(§8.3), package export and import between environments, authoring in +production, the switch of the report editor to stored sheets and the link from +bilans to versions (V1-3), storage of report migration maps (V1-3), offline +cache (plan Step 16), professional verification (plan Step 9), deletion of +Storage objects, and the publication of the equine draft (an owner act after +its review). + +--- + +## 3. Nomenclature + +| FR (UI) | EN (UI) | Code | +|---|---|---| +| Fiche anatomique | Anatomical sheet | sheet | +| Fiche officielle | Official sheet | `is_official` | +| Version, brouillon, publiée, retirée | Version, draft, published, withdrawn | `draft`, `published`, `deprecated` | +| Revue, soumission | Review, submission | review round (§6.3) | +| Relecteur, relectrice | Reviewer | capability `sheet_reviewer` | +| Éditeur de fiches | Sheet editor | capability `sheet_editor` | +| Responsable de publication | Publisher | capability `sheet_publisher` | +| À confirmer, relu, repris | To confirm, reviewed, inherited | `to_confirm`, `reviewed`, `inherited` | +| Complétude | Completeness | core report §6.4 | +| Illustration | Drawing | asset row + Storage object | +| Vue principale, vue détaillée | Main view, detail view | `main`, `detail` | +| Point, zone, accès à une vue détaillée | Point, zone, detail view link | `point`, `zone`, `detail_trigger` | +| Catalogue des constats | Finding catalogue | `finding_zones` | +| Empreinte | Fingerprint | `sha256-rfc8785-validated-v1` | +| Clé d'élément | Element key | annotation id, or finding path key `/` | + +The French labels of statuses and capabilities are proposals (§17, O16). + +--- + +## 4. Decisions D1 to D9 + +Owner orientations of the brief. The column « Contract » says where each one +becomes rules; those rules are proposals until ratified. + +| Id | Owner orientation (summary) | Contract | +|---|---|---| +| D1 | Official publication is reserved to habilitated platform administrators. Business validation is identified and traced separately from the technical act of publishing. `platform_role` is never a professional status. | §5.1 capabilities, §5.3 separation, §6.3 rounds | +| D2 | No official publication while blocking `to_confirm` items remain. `to_confirm` never becomes `reviewed` automatically. Completeness rules and validation conditions are defined. | §6.4, §6.5, §17 O3 | +| D3 | Official drafts are visible only to administrators, editors and explicitly authorised reviewers. Ordinary practitioners never see a sheet in preparation. The equine sheet stays a draft. | §5.2, §9.3, §10, §14 | +| D4 | Published official sheets are readable by authenticated, authorised users whatever their workspace, under the retained RLS. Reading is separate from editing. | §5.1 reader eligibility, §5.2 | +| D5 | At launch, creating official sheets and the related administration is reserved to habilitated administrators. Personal and community sheets are not opened in the MVP. | §5.2, §12 M4 | +| D6 | A traceable review before official publication identifies the draft's authors, the submitter, the reviewers, the decisions and comments, the publisher, and the exact version validated. A simple but really usable review interface. | §6.3, §11 journeys R1, A6 | +| D7 | The report editor keeps working as today during V1-2. Loading published versions from Supabase is prepared; the switch and the adaptation of bilans are framed in V1-3. The readers of historical data are not modified early. | §10 | +| D8 | Published versions are immutable; changing a published sheet creates a new draft. Versions referenced by bilans stay readable by authorised users after archiving or a newer publication, never exposed to users without the needed permissions. | §6.7, §9.3, F13 | +| D9 | Administrators create, read, edit, version and prepare the publication of official sheets from the application, for any species, without editing the database or the project sources. Rust stays the validation authority; no divergent schema copy. | §7, §8, §9, §11 | + +--- + +## 5. Roles and permissions + +### 5.1 Notions + +| Notion | Where it lives | Effect in V1-2 | +|---|---|---| +| Platform role | `profile_roles`, `platform_role` | Staff role. Owner and admin may hold the editor and publisher capabilities; moderator and support get nothing in the catalogue. | +| Catalogue capability (new) | `anatomical_catalog_grants` (M5): `sheet_editor`, `sheet_reviewer`, `sheet_publisher`; global scope | Explicit, revocable, audited allowlist (§17, O1). | +| Professional status | plan Step 9, not built | None. A reviewer capability is a review mandate given by the owner, never a statement that the account is a verified professional. | +| Workspace membership | V1-1 tables | None: no catalogue rule reads workspace tables and no V1-1 rule reads catalogue tables. | +| Reader eligibility (new) | `private.can_read_official_catalog(uid)` | Active profile and confirmed email, checked in SQL as the V1-1 helpers do. | + +Who may hold a capability (proposal): + +- `sheet_editor` and `sheet_publisher`: an account whose platform role is + owner or admin, checked at use. Losing the platform role suspends the + capability without deleting the grant row. +- `sheet_reviewer`: any active account with a confirmed email (partner + osteopath, veterinarian, staff). +- Grants are written by the platform owner only, through audited RPCs. The + owner grants itself at first use; no migration grants anything. + +`private.can_edit_sheet` is redefined for official sheets (M4): it requires +`sheet_editor` and `has_mfa()`; owner and admin without the capability lose +draft reads, lifecycle RPCs and draft drawing reads. Every predicate built on +it inherits the change, and pgTAP proves « admin without capability refused » +for each RPC and policy (§15). + +### 5.2 Matrix + +R = reader (eligible account without capability), E = sheet editor, +V = sheet reviewer, P = sheet publisher, O = platform owner acting on grants +or species. A person may hold several capabilities. Every operation except the +two reader lines requires an `aal2` session (§5.4), in RPCs and in the table +and Storage policies alike. + +| Operation | R | E | V | P | O | Others: moderator, support, unconfirmed, deactivated, anonymous | +|---|---|---|---|---|---|---| +| List the catalogue (active official sheets with a published version) | yes | yes | yes | yes | yes | no | +| Read a published or deprecated version by id, sheet archived included (D8) | yes | yes | yes | yes | yes | no | +| Read drafts, rounds, completeness, history of official sheets | no | yes | yes | yes | no | no | +| Create an official sheet, save its draft, upload drawings, delete a draft | no | yes | no | no | no | no | +| Submit a draft, withdraw a submission | no | yes | no | no | no | no | +| Comment a round | no | yes | yes | yes | no | no | +| Approve or request changes (§5.3) | no | no | yes | no | no | no | +| Publish an approved round, deprecate a version, archive and restore a sheet | no | no | no | yes | no | no | +| Grant and revoke capabilities, add a species | no | no | no | no | yes | no | +| Create a personal sheet, fork, change visibility | no | no | no | no | no | no (closed in V1-2, D5) | + +Service role: only the verification RPCs of §9.2 and the narrow read RPC of +the operator tool (§9.4); no table privilege on catalogue tables if F12 is +confirmed. + +### 5.3 Separation of duties (proposal S1) + +- The round records its author set at submission: the account that created + the draft (or supplied its initial document) and every account that saved it + since its base version. +- The approver is never a member of that author set. +- A save whose content equals the stored content is refused (no revision + bump), so one empty save cannot move authorship. +- Publication needs `sheet_publisher`; the publisher may be the approver. +- The review screen shows the author set to every reader of the round, so + reviewers do not need the audit log. + +Consequence: with one owner and nobody else holding `sheet_reviewer`, no +official sheet can be published. That is the intent of D1; the options are in +§17, O2. + +### 5.4 Strong authentication (§17, O4) + +- `private.has_mfa()` reads `auth.jwt() ->> 'aal' = 'aal2'`. +- Every catalogue write RPC, the editor branch of the version and asset + policies, and the editor branch of the Storage read require it; the reader + lines of §5.2 do not. +- The application gains TOTP enrolment and removal in Mon compte, Sécurité, + and a step-up challenge when entering `/app/admin`. +- Lockout: the owner enrols two factors; `IDENTITY.md` gets a recovery + runbook per environment (DEV: SQL on the database container by the owner, + Studio being closed to the LAN). + +--- + +## 6. Lifecycle, review and publication + +### 6.1 States + +Versions keep their three statuses. Reviews are separate rows, so the version +enum and its immutability stay untouched. + +``` +version: draft ──publish──▶ published ──deprecate──▶ deprecated +round (on a draft): + open ──approve──▶ approved ──(publication)──▶ the version is published + open ──request changes──▶ changes_requested + open | approved ──withdraw──▶ withdrawn +``` + +While a round is `open` or `approved`, the draft content is frozen (trigger, +every role, seed included). A change after approval needs a withdrawal, which +voids the approval; the next submission opens a new round. A draft that has +rounds cannot be deleted (foreign key `restrict`), so the D6 trail survives. + +Every lifecycle RPC locks in one order: sheet, then version, then round. +Deadlock and serialization errors map to a closed, retryable failure. + +### 6.2 Drafts + +- A draft is created from the empty document (new sheet, §7.3) or from a + published version of the same sheet (existing `create_sheet_draft`). M5 + records its origin in `source_version_id`, the base of the review diff. +- Saving goes through `save_sheet_draft(version_id, expected_revision, + document, change_note)`. The server checks the shape, the size (existing + 2 MiB column cap), the species, the frozen state, the revision, and refuses + an unchanged document; it increments `revision`, records `saved_by` and + audits `anatomical_sheet_version.saved` with the revision. A draft may hold + integrity errors while it is being written; submission refuses them. +- A trigger bumps `revision` on any content write, so a write outside the RPC + (seed, operator) cannot slip under an open round unseen. +- The direct UPDATE grants on `content`, `change_note`, `name`, `slug` and + `description` are revoked (M4). The sheet row's `name` and `description` + are set at creation and refreshed from the document at publication; the + catalogue shows the published document's FR and EN texts (§10). The slug is + set at creation and never shown in routes. +- A stale `expected_revision` answers the closed failure `draft_conflict`; + nothing is overwritten silently. + +### 6.3 Review rounds + +`anatomical_sheet_reviews` (M5), one row per round: + +| Column | Meaning | +|---|---| +| `version_id`, `round` | the draft and the round number | +| `revision` | the revision submitted; with the freeze, `(version_id, revision)` is the « exact version » of D6 | +| `authors` | the author set of §5.3 | +| `submitted_by`, `submitted_at`, `submission_note` | the submitter | +| `verdict` | the server verdict of §6.4 for this revision: issues, completeness counts, caps, fingerprint, the element changes since the base (§6.5); written by the verification of §6.4, never by a page | +| `status` | `open`, `approved`, `changes_requested`, `withdrawn` | +| `decided_by`, `decided_at`, `decision_note` | the approver or the reviewer who requested changes; the note is required | + +`anatomical_sheet_review_comments` (M5), append-only: author, body (≤ 4 000 +characters), optional element keys, time. Several reviewers may comment; one +decision closes the round (§17, O5). The publication is recorded on the +version (`published_review_id`, `published_by`, `published_at`), not +duplicated on the round. + +`submit_sheet_review(version_id, expected_revision, note)` refuses a stale +revision. + +### 6.4 Server verdict and publication rules + +The database alone cannot parse the strict schema, compute the fingerprint, +check the caps in UTF-16 units or read an SVG. The verdict that publication +relies on therefore comes from the Rust core running on the server side, in +one of two ways (§17, O15): + +- A (recommended): a worker job `sheet_revision_verify`, queued by the + submission, reads the submitted revision and its drawings in place, runs the + core (strict parse, `validate_sheet_document`, completeness, caps, element + changes against the base, fingerprint, sha256 and `read_svg` of each + drawing), and writes the verdict on the round. The round is reviewable once + the verdict is in. +- B: no worker. The approver's page and the publisher's page each run the + same core checks on the stored revision and record their verdict hash and + fingerprint; publication requires both equal and clean. The checks are then + two independent client computations by MFA staff, not a server proof. + +The SQL keeps only what the database knows; the existing referential mirror +stays as it is and does not grow (the core is the authority). + +Blocking rules at publication: + +| Code (proposal) | Rule | Source | +|---|---|---| +| `publish.verdict.missing` / `.failed` | the round's verdict exists and has no blocking issue below | verdict | +| the 19 error codes | `validate_sheet_document` errors | verdict | +| `publish.caps` | the archive caps of §1, all of them | verdict | +| `publish.annotation.no_geometry` | every annotation has a geometry | verdict | +| `publish.disclaimer.missing` | `scope_disclaimer` filled in French and English (§17, O6) | verdict | +| `publish.drawing.invalid` | every reachable drawing: object present, sha256 and size equal to its row, accepted by `read_svg` without removal | verdict | +| `publish.to_confirm.open` | no `to_confirm` element left (§17, O3) | verdict, and a SQL JSONB path presence check | +| `publish.inherited.new` | an element is `inherited` only if it is `inherited` under the same key in the base version; a new sheet has none | verdict | +| `publish.sheet.inactive` | the sheet is active | SQL | +| `publish.species.invalid` | the species is not `other` | SQL | +| `publish.review.missing` | an `approved` round on the current revision | SQL | +| `publish.separation` | rule S1 | SQL | +| `publish.mfa` | `aal2` session | SQL | + +Shown, never blocking: `inherited` elements kept from the base, uncited +elements, the two warning codes, the number of vet referral nodes. + +Submission applies the verdict rules (once the verdict is in, for A) except +`to_confirm`, so a reviewer never receives a draft that cannot be published +for a technical reason. + +### 6.5 Review statuses of elements (D2) + +- Elements are identified by their key (§3); finding ids alone are never used. +- No code path sets `reviewed` on its own: no default, no import mapping, no + migration. The editor changes one element, or one subtree through an + explicit « Marquer comme relu » on a zone or a category (one human action, + listed like any other change). +- An element created in the editor starts as `to_confirm` (§17, O7). + `inherited` is never assigned by the editor; `publish.inherited.new` refuses + it on any element absent from the base. +- The verdict lists, against the base version: elements now `reviewed` that + were not, elements whose status left `to_confirm`, and `reviewed` elements + whose content changed (labels, children, vet flag, geometry, references). + The review screen shows that list above the decision; approving the round is + the acknowledgement. +- Approval never changes the document. + +Expected effort for a new species: an editor creates the catalogue with every +element `to_confirm`; the business reviewer reads it through the review +screen, comments; the editor marks zones or categories reviewed after the +answers (tens of actions, not hundreds); the reviewer approves the listed +changes. + +### 6.6 Publication (atomic) + +`publish_sheet_version(review_id)`, in one transaction: lock sheet, version, +round; check every rule of §6.4; set the version `published` with +`published_by`, `published_at`, `published_review_id` and the fingerprint +taken from the verdict (never from a client parameter); refresh the sheet +row's `name` and `description` from the document; move `current_version_id`; +audit `anatomical_sheet_version.published` with the revision, the fingerprint +and the round. The old signature `publish_sheet_version(uuid)` is dropped in +the same migration (`CREATE OR REPLACE` with new arguments would leave it +callable), as is every superseded RPC signature, each proven absent by pgTAP. +The client gate `publishSheetVersion` is deleted in the same step. + +`guard_sheet_version_update` is extended so the deprecation transition +cannot change any column added by V1-2 (fingerprint, review link, revision, +savers, source). + +A wrong published version is repaired only by deprecating it and publishing a +corrected one. + +### 6.7 Deprecation, archive, deletion, historical reads (D8) + +- A version that was ever published is never modified or deleted: M4 extends + the delete guard to `deprecated` for every role (F13). +- Deprecation keeps the version readable by id. Deprecating the current + version makes the latest remaining published one current again; the A8 + confirmation names it. +- Archiving an official sheet removes it from the listing; its published and + deprecated versions stay readable by id for eligible readers (M4 changes the + read predicate, which today requires an active sheet). +- An official sheet that ever had a published version cannot be deleted; + drafts without rounds can. +- Readers see no trace of drafts: their column grants on sheets exclude + `last_version_number` and `updated_at`, and the asset-row policy shows them + only drawings referenced by a published or deprecated version. +- Narrowing the read of archived versions to « referenced by a bilan the + reader can see » needs the bilan table of V1-3 (§17, O8). + +--- + +## 7. Species and new sheets + +### 7.1 What the current model allows + +Nothing in the document schema is equine-specific: `species_id` is a free +stable id, vertebral regions are data, labels are FR/EN pairs. The equine +specifics found are the report migration map (a legacy equine concept, kept +as is; §10 adds a load path without it), `NewReportRoute.DEFAULT_SPECIES_ID = +'equine'` and the bundle plugin (local tool, unchanged until V1-3), the +curation pipeline (an equine tool), and the archive caps (4 drawings), which +bind every species. + +### 7.2 Species rows + +- A sheet needs an active `species` row; `other` is refused at creation and at + publication. +- Adding a species needs a row. Proposal: `create_species(id, name_fr, + name_en, sort_order)`, platform owner with MFA, audited, offered inline in + the sheet creation form. This amends V1-1 §5.4 and N1 (« no other species is + added »): the new species appears at once in the animal forms of V1-1 + (§17, O9). No deactivation in V1-2. +- Several official sheets may describe one species; V1-3 decides how a bilan + picks one (§17, O10). + +### 7.3 Starting a sheet + +- From the empty document: species, FR and EN names, slug; everything else + is entered in the editor. +- Optional (§17, O11): a core edit command copies the finding catalogue + (zones, categories, nodes, references) of a published official version that + the page has loaded into the draft, every `review_status` forced to + `to_confirm`, no views, annotations or drawings; provenance goes in the + change note and the audit, not in `based_on_*` (those columns mean fork + lineage). +- No template of scientific content is shipped. Vertebral formulas, zones and + findings of a new species are entered by the editor from sources cited in + the references registry. + +### 7.4 Species-specific checks + +The core checks structure only: unique region codes, order as given, +`count ≥ 1`, coherent `count_range`, region codes used by annotations exist. +Expected vertebral formulas per species would be veterinary data nobody has +supplied; they are not invented. + +--- + +## 8. Editor + +### 8.1 Architecture + +- The page holds the draft document as one JSON string. Every change is a + Rust core command (`sheet.edit`, V1-2.3): generic primitives (insert, + update, remove, move) over element keys, refusing only what would break + strict parsing; referential gaps are left to the validation panel. A + `dependents(key)` query feeds the delete confirmations. TypeScript holds no + schema of its own and no Zod copy; it reads the ts-rs types. +- Ids are generated by the page (`-<10 lowercase base32 + characters>`, alphabet `a-z2-7`, inside the stable-id rule), passed to the + core, never derived from labels, never editable, never reused. +- Pointer moves update the page's preview only; the core command runs on + pointer-up. +- Undo and redo: a stack bounded by size (8 MiB of document strings, + proposal). +- Saving is explicit (« Enregistrer ») with the leave guard of V1-1. Unsaved + work is also kept in the browser, with the report editor's persistence + pattern, and offered back after a crash or an expired session. A conflict + shows the server revision and offers « recharger » or « garder ma version » + (which reapplies it on the new revision after confirmation); never a silent + overwrite (§17, O12). +- The validation panel lists the core issues and the completeness report + with FR and EN messages per code, a link to the element, and the serialised + size against the 2 MiB server cap. + +### 8.2 Level 1, in the MVP + +An editor can, from the application only: + +- set the general information: FR and EN name, description and scope + disclaimer, attribution (authors, licence, notes); +- manage the references registry: add, edit, delete; type, citation, URL + (http or https only), DOI; +- manage the vertebral regions: add, edit, reorder, delete; +- manage annotation categories: name FR/EN, colour; +- manage views: the main view, detail views (parent, own drawing or crop of + the parent drawn as a rectangle on it), rename, delete; +- upload a drawing (§9), see its state, attach it to a view; +- on a view's drawing, as the practitioner sees it: + - place a point by clicking, set its radius by a handle or a field; + - draw a zone as a polygon by successive clicks, close it, move, add and + remove vertices; + - draw a detail view link the same way and choose the view it opens; + - select an annotation on the drawing or in the list, move it, delete it; + - zoom and pan; + - enter or correct every coordinate in numeric fields (keyboard + alternative and precision); +- set each annotation's FR and EN name, kind, category, laterality, finding + zone, vertebral region, colour and review status; +- edit the finding catalogue as a tree: zones, categories (kind), nodes up to + depth 8; add, rename FR/EN, describe FR/EN, flag vet referral, cite + references, set the review status of one element or « Marquer comme relu » + on a subtree, move up, down or to another parent through a dialog, delete + with a confirmation listing the dependents; +- preview the draft exactly as a practitioner (§10), read the completeness + report, submit, follow the round, read comments, withdraw. + +### 8.3 Level 2, deferred + +Curves (`path` drawn or edited by handles; existing paths are displayed and +can be replaced by a polygon), snapping, left and right mirroring, +multi-selection and group moves, scale and rotation, copying annotations +between views or sheets, creating zones from the drawing's own SVG shapes, +side-by-side visual diff of two versions, comments pinned on the drawing, +drag and drop in the finding tree, bulk import of findings, species templates, +collaborative live editing, package export and import. + +### 8.4 What level 1 does not do + +It never edits the drawing itself, accepts no raster image, draws no curves, +does not let two people edit one draft at the same time (one draft per sheet, +revision conflicts), and does not edit on a phone: below 1 024 px wide the +editor shows the lists and the properties read-only with a notice (§17, O14). + +--- + +## 9. Drawings (SVG assets) + +### 9.1 Principles + +- Content-addressed and immutable: a new drawing is a new sha256, a new row + and a new object. A published version references its asset ids, so no later + upload can alter it. +- A file is at most 2 MiB (archive cap); the bucket limit drops from 20 MiB to + 2 MiB (M6). A sheet reaches at most 4 distinct drawings (§1). +- The avatar pipeline is not reused: no transcoding, no per-user key, no + quarantine copy, no automatic replacement. Server-built keys, closed codes + and the worker's lease are reused where they fit. + +### 9.2 Preparing and uploading a drawing + +1. The page reads the file and runs the core SVG reader. If the reader would + remove anything, the page shows the removed list (elements, attributes) in + FR or EN and a preview of the result, and offers « Nettoyer et utiliser + cette version » (§17, O19): the core serialises the cleaned tree, the admin + confirms, and the cleaned bytes are the ones hashed and uploaded. This + happens before storage, so stored drawings are never repaired (LRN-055). +2. `begin_sheet_asset_upload(sheet_id, sha256, byte_size, file_name)` (editor, + MFA): creates the row `pending_upload`, or answers the existing row of the + same sheet and hash with its state; a `verified` row is never moved back. +3. If the object `.svg` does not exist yet, the page uploads it there. + An INSERT policy on `storage.objects` allows exactly that key for the caller + of a pending row, bucket literal pinned; no UPDATE or DELETE policy. If the + object already exists (shared drawing), nothing is uploaded. +4. `confirm_sheet_asset_upload(asset_id)` (editor): checks in + `storage.objects` that the object exists and its size equals the row's, + then sets `uploaded`. Editors and reviewers can draw with it from then on; + the loader checks its sha256 at every load (§10). +5. Under option A (§6.4), the verification job of a submitted revision + re-reads every reachable drawing in place: size, sha256, `read_svg` with no + removal. A mismatch under an existing key (written by another service-role + writer) is the closed code `object_conflict`, with an operator runbook; it + never overwrites. +6. Closed codes shown to the editor: `size_mismatch`, `hash_mismatch`, + `svg_rejected` (with the reader's reason), `too_large`, `upload_missing`, + `object_conflict`. + +A drawing never blocks authoring: only submission waits for the verdict. A +round whose verdict is pending shows « vérification en attente depuis N min ». + +### 9.3 Read path + +- Eligible readers: drawings referenced by a published or deprecated version + of an official sheet, whatever the sheet's status (D8). +- Editors, reviewers and publishers (MFA): every `uploaded` drawing of the + sheet. +- Nobody reads a `pending_upload` row's object through the API. + +### 9.4 Existing rows and tools + +- The DEV equine row (bytes at `.svg`, confirmed by the operator + tool) becomes `uploaded` in M6; option A verifies it in place with the first + submission of the equine draft. M6 is rehearsed on a sandbox holding a copy + of that object, not only on an empty upgrade. +- `pnpm assets:upload` stays the seed tool of local and sandbox stacks. If + F12 removes the service role's table privileges, the same step gives the + tool a narrow read RPC for its planning and reruns `pnpm e2e:sheet-assets`. +- Objects are never deleted in V1-2: the worker's purge rules get a guard + that never deletes a key matching `^[0-9a-f]{64}\.svg$`, and no trigger + enqueues a sheet object. +- The verification job runs under its own job kind and failure isolation, so + a fault in it never stops avatar processing. +- `verified_with` records the core version of each verdict; a release that + changes the SVG reader or the integrity rules replays every published + version and drawing before shipping (§15). + +--- + +## 10. Loading into the core and the application + +- `get_sheet_version(version_id)` returns the sheet id, version id and + number, status, species, document, `revision`, the fingerprint (published + only) and the drawings (asset id, sha256, size). Unknown and forbidden + versions get one answer. +- The page downloads each drawing under RLS and builds a preview payload. A + new core load type, `PreviewSheet`, checks in one call: strict document, + each drawing's sha256 against its row, the fingerprint recomputed against the + stored one (published), the caps, and each drawing through `read_svg`. It + needs no report migration map and can never open a report session. Closed + failure kinds: `not_found_or_denied`, `drawing_missing`, + `drawing_hash_mismatch`, `fingerprint_mismatch`, `invalid_document`, + `caps`, `core_unavailable`, `unavailable`. A draft with integrity errors + previews with its issues and no fingerprint. +- `LoadedSheet` (the report editor's sheet) keeps its mandatory migration map; + `archive::SheetStatus` is not extended; a deprecated version previews like a + published one with a « retirée » mark. The readers of user data + (`report/rebase`, `report/read`, `archive/read`, `session`, `pdf/{read, + json_js,import}`) are not modified in V1-2. +- The report editor stays on the bundled sheet (D7). +- The catalogue's read-only view reuses the editor canvas without + observations, plus a browsable finding catalogue. +- Supabase unavailable: the catalogue and the admin space show the + unavailable notice; the report editor keeps working on its bundle. + +--- + +## 11. Screens and journeys + +### 11.1 Routes (proposal; the paths become visible URLs, §17, O16) + +| Route | Who | Content | +|---|---|---| +| `/app/anatomy` | eligible readers | catalogue by species: sheets with a published version | +| `/app/anatomy/:sheetId` | eligible readers | current version: views, annotations, finding catalogue, references, disclaimer; earlier versions listed | +| `/app/anatomy/:sheetId/versions/:number` | eligible readers | one published or deprecated version | +| `/app/admin/sheets` | E, V, P | every official sheet; filters species, sheet status, version status, round status | +| `/app/admin/sheets/new` | E | species (new species inline for the owner), names, slug, start (empty or §7.3 option) | +| `/app/admin/sheets/:sheetId` | E, V, P | overview: versions, rounds, history, actions per capability | +| `/app/admin/sheets/:sheetId/draft` | E (V, P read-only) | editor tabs: Général, Vues et illustrations, Annotations, Constats, Références, Vertèbres, Vérification | +| `/app/admin/sheets/:sheetId/reviews/:round` | E, V, P | round: preview, verdict, changes since the base, authors, comments, decision, publication | +| `/app/admin/access` | O | capability grants | + +### 11.2 Journeys + +- A1 create: Fiches officielles → Nouvelle fiche → species, names, slug → + draft v1 opens in the editor. +- A2 drawings: Vues et illustrations → choose a file → clean if needed → + upload → attach to the main view; add a detail view by drawing its crop. +- A3 annotations: choose a view → draw points, zones, detail view links → set + properties → link to finding zones. +- A4 findings: Constats → build zones, categories and nodes, cite references, + flag vet referrals. +- A5 check and submit: Vérification → fix issues → Prévisualiser → Soumettre + à la revue with a note → verdict. +- R1 review: list « À relire » (no e-mail in V1-2) → preview, verdict, + changes since the base, authors, comments → approve or request changes with + a note. +- A6 publish: Publier on an approved round → confirmation showing the + version, revision, approver, fingerprint → published; the catalogue shows + it. +- A7 correct: on a published sheet → Nouvelle version → edit → A5, R1, A6; + the earlier version stays readable. +- A8 retire: deprecate a version (the confirmation names the version that + becomes current), archive or restore a sheet. +- P1 practitioner: Fiches anatomiques → species → sheet → views, zones, + findings; no draft is ever listed. + +### 11.3 Design + +The catalogue, the admin lists and the forms follow the V1-1 precedent: +existing components and shell, no new mockup. The editor canvas, the review +screen and the sidebar entry of the admin space are new interaction patterns: +step V1-2.4 wireframes them through the design toolchain and the owner +validates them before V1-2.6 and V1-2.7. The catalogue works at 320 to +430 px. + +--- + +## 12. SQL defects and planned migrations + +### 12.1 Defects + +None was reproduced by execution in V1-2.0, which ran no stack. « Confirmed by +reading » means the source shows the behaviour; V1-2.1 turns each line into a +test that fails on the current code before fixing it. + +| Id | Defect | Evidence | State | Fix | +|---|---|---|---|---| +| F1 | `create_anatomical_sheet` lets any active account create a non-official sheet, `public` at once, for any active species including `other`; contradicts V1-1 §5.4 | l.692 | confirmed by reading | M4 | +| F2 | `publish_sheet_version` ignores the sheet status: the draft of an archived sheet can be published; `create_sheet_draft` opens drafts on archived sheets | l.735, l.764 | confirmed by reading | M4, M5 | +| F3 | the fork copies asset rows without `uploaded_at`; the copy reads its drawings only through the source's row, so they become unreadable once the source is archived or made private | `copy_sheet_assets` l.638-660, storage predicate | confirmed by reading | M4 closes the fork in V1-2 | +| F4 | publication accepts registered but unconfirmed drawings (only `view.asset.unknown` is checked) | l.764 | confirmed by reading | M5 | +| F5 | `require_actor` checks the active profile, not the confirmed email | l.537 | confirmed by reading | M4 | +| F6 | `set_sheet_visibility` has no verification gate (BDR-033) | l.998 | confirmed by reading | M4 (refused in V1-2) | +| F7 | `confirm_sheet_asset_upload` stamps a row without checking the object (R5.5 L5); its audit actor is null | `20261009100000` l.34 | confirmed by reading | M6 | +| F8 | archiving a sheet hides its published versions from every non-editor | l.513, version select policy | confirmed by reading | M4 | +| F9 | draft content and sheet name, slug, description change by direct UPDATE: no audit, last write wins | grant lines | confirmed by reading | M4 | +| F10 | `view.parent.cycle` and `finding.id.duplicate` are not checked in SQL | code lists | confirmed by reading | none: the server verdict (§6.4) carries all core rules; the SQL mirror does not grow | +| F11 | the client publication gate reads, validates, then publishes | `packages/supabase/src/anatomical-sheets.ts` | confirmed by reading | M5, client gate deleted | +| F12 | `service_role` keeps the default table privileges on sheet tables (the revokes name `public, anon, authenticated` only), unlike V1-1 N7 | revoke block | to confirm on the stack (effective grants) | M4, with the tool's read RPC | +| F13 | a deprecated version can be deleted physically, so a historical version can vanish | l.275-278; pgTAP 005 l.551 | confirmed by reading and by an existing passing test | M4 | +| F14 | `can_edit_sheet` gives every owner and admin full rights on official sheets, with no capability and no MFA | l.494-510 | confirmed by reading | M4 | + +### 12.2 Migrations (names provisional) + +| Id | Step | Content | Data on DEV | +|---|---|---|---| +| M4 `sheet_lifecycle_hardening` | V1-2.1 | F1, F2, F3 (fork closed), F5, F6, F8, F9, F12, F13, F14; personal creation refused; deletion refused for sheets with a published version; reader column grants and asset-row policy narrowed | no row changes | +| M5 `sheet_catalog_workflow` | V1-2.1 | capabilities, `has_mfa`, `revision`, `saved_by`, `source_version_id`, `published_review_id`, `document_fingerprint` on versions; rounds and comments; freeze and revision triggers; extended immutability guard; `save_sheet_draft`, submit, withdraw, comment, decide, publish; catalogue and version RPCs; `create_species`; superseded signatures dropped | equine draft gets `revision` 0, no round, no grant | +| M6 `sheet_asset_upload` | V1-2.2 | asset states, upload RPCs, INSERT policy, bucket limit 2 MiB, verification job RPCs (option A), read predicate | equine row set `uploaded` | + +Each migration ships its pgTAP file (allowed and denied cases), regenerated +`database.types.ts`, a `db:sandbox up upgrade` run from the DEV state (M6 +with a copy of the DEV object), and is applied to DEV by the owner at closure +(`SUPABASE.md` §3.3). BLK-008 stays the rule: no document schema bump in V1-2. + +--- + +## 13. Security + +| Threat | Control | +|---|---| +| Privilege escalation through the catalogue | default deny; capabilities in their own table, written by the owner only; `can_edit_sheet` redefined; no table write grant; security definer functions with `search_path = ''`, EXECUTE revoked from public and anon; superseded signatures dropped | +| Takeover of an admin account | `aal2` in RPCs and in the editor branches of policies; deactivation cuts access at the next request; two factors for the owner | +| Self-approval | S1 on the author set captured at submission; empty saves refused | +| Malicious SVG | core reader in the page before upload, in the verification job (option A), at every load and at export; the page never inserts stored bytes (core-composed tree only); production CSP | +| Wrong bytes under a hash | size checked in SQL at confirmation; sha256 at every load and in the verdict; no overwrite | +| Publishing something other than what was reviewed | frozen draft, round bound to a revision, verdict per revision, fingerprint from the verdict, atomic gate | +| D2 bypass by relabelling | element keys, `publish.inherited.new`, the change list against the base | +| Concurrent edits | revision checks on save and submit, one draft per sheet, one lock order | +| Draft leak to practitioners | capability-only reads of drafts, rounds and draft drawings; reader column grants narrowed; one answer for unknown and forbidden; tests per actor | +| Labels and references in the UI | React escaping; the core escapes annotation titles; reference URLs http(s) only, opened with `rel="noopener noreferrer"` | +| Audit gaps | every RPC calls `private.log_event` (saves, grants, species, rounds, comments, uploads, verdicts) | +| Service key | the verification job and the seed tool only, through RPCs | +| Size and volume | content 2 MiB, drawing 2 MiB, comment 4 000 characters, change note 1 000; per-actor write budget as V1-1 D15 (thresholds in V1-2.1) | + +Residual risks: the reviewer capability does not prove a professional +qualification (owner judgement until Step 9); under option B the verdict rests +on two client computations; a later core change could make published versions +unloadable, which the replay gate of §15 catches before release; raising the +archive caps later is an archive contract change (older readers refuse bigger +snapshots). + +--- + +## 14. Equine sheet + +- The draft stays a draft. No migration creates a round, a grant or a + publication; no status of its 839 elements changes (28 annotations, 81 + finding categories, 730 nodes: 188 `to_confirm`, 31 `reviewed`, 620 + `inherited`, the last omitted on disk as the schema default). +- Authority (§17, O17). The equine content changes only through + `curation/changes.json` and the Rust pipeline during V1-2: the converging + seed would overwrite application edits, the report editor's bundle and the + oracles read the Git files, and the ids `503dc301…` / `7f767f74…` that the + v0 fingerprint alias needs are kept only by the seed. The admin space opens, + previews, verifies and submits the equine draft, but its editor is read-only + for this sheet. The switch to the database (seed made insert-only and + fresh-stack-only, export back to Git for the bundle, comparison by the `v1` + fingerprint) is designed with V1-3, which also binds bilans to versions. +- V1-2.8 content, each item an owner decision (§17, O18): the carpus statuses + (26 elements shown `inherited` though added by a level B change), the 11 + level B changes missing from `REVIEW-REPORT.md`, the overlapping carpus and + elbow areas, the 10 moved points, a new oracle baseline if a changeset is + applied (RR-10); and the review dossier in the application: the 188 + `to_confirm` elements by key, the 11 open questions mapped to element keys, + the legal text to re-read on Légifrance. Note: the 620 `inherited` elements + stay allowed by `publish.inherited.new` because the base is the legacy + import; whether they may be published unread is O3's question. +- Other species are never blocked by the equine questions: each sheet has its + own completeness, references and rounds. + +--- + +## 15. Tests and Definition of Done + +- SQL (pgTAP on PGlite and on the real image): every RPC allowed and denied + per actor class of §5.2, including « owner or admin without capability » + and « capability without `aal2` »; drafts, rounds, grants and pending + objects unreadable to readers; reviewer cannot publish; any author cannot + approve; moderator, support, unconfirmed, deactivated, anonymous refused; + frozen draft; revision conflict on save and submit; each publication rule of + §6.4 failing alone; deprecated version deletion refused; D8 reads after + archive and deprecation; superseded signatures absent; upgrade from the DEV + state. +- Concurrency on the real stack, two sessions: two saves, save against + submit, publish against withdraw, two publishers, deprecate against publish. +- Performance: save, submit and publish timed on a synthetic document at the + caps (1 024 annotations, 8 192 nodes), not only on the equine draft. +- Core: every edit primitive outputs a strictly parseable document and keeps + existing keys (property tests); completeness, element changes by key, the + `inherited` rule; `PreviewSheet` checks (hash, fingerprint, caps); the SVG + clean operation on vector-tool exports; caps fixtures at cap − 1, cap, + cap + 1 and with astral characters; wasm facade and ts-rs types; the N-1 + reader untouched; the frozen oracles green. +- Worker (option A): verdicts accepted and each closed code, the hostile SVG + corpus, failure isolation from avatars, the purge guard, sandbox tests, an + e2e on the sandbox stack; `pnpm e2e:avatar` and `pnpm e2e:sheet-assets` + unchanged in outcome. +- Release replay: a script loads every published version and drawing of a + stack through the new core and fails on any regression. +- Application: failure kinds to FR and EN messages, editor state (undo, + conflict, local recovery, leave guard), capability-driven actions. +- Browser (`e2e:shell` on the sandbox, never DEV): journeys A1 to A8, R1, P1 + with two accounts, axe, 320 to 430 px for the catalogue, FR and EN. +- Each step: `pnpm check:all`, fresh verifier against this contract, fresh + security audit. + +--- + +## 16. Implementation steps + +Every step works on the sandbox stack only; DEV changes are owner actions at +closure. Owner checkpoints sit after the server workflow (V1-2.2), after the +first screens (V1-2.6), after the end-to-end journey (V1-2.7) and at closure +(V1-2.9), as in V1-1; the owner may ask for more. All steps are MVP: D9 makes +administration essential. + +The brief's twelve items map to the steps as follows: 1 contract → V1-2.0; +2 SQL hardening, 3 review workflow, 4 catalogue, draft and version API → +V1-2.1; 4 assets → V1-2.2; 5 core and application loading → V1-2.3; +6 catalogue, 7 administration → V1-2.5; 8 drafts, 9 drawings, annotations, +categories, references → V1-2.6; 10 preview and validation → V1-2.7; +11 equine → V1-2.8; 12 acceptance and closure → V1-2.9. + +### V1-2.0 Contract and decisions + +- Objective: this document, the decisions of §17, the doc fixes of §18. +- Initial state: audit delivered; D1 to D9 given by the owner. +- Changes: documents only. Migrations: none. Tests: none. +- Dependencies: none. Risk: deciding too wide or too narrow. +- Acceptance: the owner ratifies §5 to §16 with the §17 options chosen; BDR + recorded. +- Checkpoint: owner ratification. + +### V1-2.1 Server workflow (M4, M5) + +- Objective: hardening, capabilities, MFA in SQL, drafts with revisions, + rounds, the single rewrite of the publication gate, the catalogue and + version API, `packages/supabase/src/sheets.ts` with closed failure kinds, + the client gate deleted. +- Initial state: 12 migrations, defects F1 to F14. +- Dependencies: V1-2.0; O1 to O9. +- Tests: one test per defect red on the old code then green (F1, F2, F3, F5, + F6, F8, F9, F13, F14, and F12 if confirmed); every §6.4 SQL rule allowed and + denied, with the verdict rows written by a test fixture; concurrency; + performance at the caps; pgTAP 005 to 008 and 011 adapted where they + asserted the old behaviour (005 l.551 flips). +- Risks: suites that assume the old grants (007 depends on the seed); the seed + tool against F12. +- Acceptance: the whole cycle create, save, conflict, submit, comment, + approve, publish, deprecate, archive runs in SQL on the sandbox with two + accounts; every refusal of §15 SQL proven; types check clean. +- Checkpoint: gates only (owner at V1-2.2). + +### V1-2.2 Drawings and server verdict (M6, worker job under option A) + +- Objective: §9.2 and §6.4 verdict (A or B per O15). +- Dependencies: V1-2.1; O15, O19. +- Tests: `pnpm worker:test`, hostile corpus, e2e on the sandbox, DEV-like + rehearsal of M6 with the equine object. +- Risks: worker availability on DEV (stopped today): under A, a running, + health-checked worker is a precondition of reviews on any stack. +- Acceptance: upload, confirmation, verdict accepted and each code refused; + never an overwrite; avatars unaffected; publication refused without a clean + verdict. +- Checkpoint: owner validates the server workflow (V1-2.1 and V1-2.2). + +### V1-2.3 Core: preview load, completeness, changes, edit primitives + +- Objective: `PreviewSheet`, `sheet.completeness`, element changes by key, + `sheet.edit` primitives, `dependents`, SVG clean, the §7.3 copy command if + O11. +- Dependencies: V1-2.0 (may run in parallel with V1-2.1 and V1-2.2). +- Tests: cargo units and properties, caps fixtures, wasm proofs, N-1 test, + oracles. +- Risks: none of the protected readers is touched; any need to change one + stops the step for an owner decision. +- Acceptance: hash and fingerprint mismatches refused; the equine draft + previews with the same index and fingerprint as from the bundle. +- Checkpoint: gates only. + +### V1-2.4 Wireframes (parallel to V1-2.1 to V1-2.3) + +- Objective: editor canvas, review screen, admin entry in the sidebar. +- Acceptance: owner-validated file in `docs/design/` with its README line. +- Checkpoint: owner validation of these screens. + +### V1-2.5 Catalogue and administration space + +- Objective: `/app/anatomy` (P1), admin list and filters, creation, overview, + capability grants, inline species creation, MFA enrolment and step-up, + sidebar entries. +- Dependencies: V1-2.1, V1-2.3; V1-2.4 for the admin entry. +- Tests: unit, `e2e:shell` P1 and A1, access per capability, MFA required, + axe, 320 to 430 px for the catalogue, FR/EN. +- Acceptance: a sheet published on the sandbox through SQL is browsable; + drafts never listed; archived sheets absent from the list and readable by + id; an owner with MFA grants capabilities and creates a sheet; every other + actor refused in the UI and in SQL. +- Checkpoint: gates only (owner at V1-2.6). + +### V1-2.6 Editor level 1 + +- Objective: structured tabs, drawing upload with cleaning, views and crops, + point, zone and link drawing, annotation properties, finding tree, local + recovery, conflicts (§8.2). +- Dependencies: V1-2.2, V1-2.3, V1-2.4, V1-2.5. +- Tests: `e2e:shell` A2, A3, A4 with a conflict; keyboard path through + numeric fields; axe. +- Risks: precision on small zones; pointer and coordinate mapping. +- Acceptance: a sheet for a species other than the horse, with a drawing + exported from a vector tool, a detail view, points, zones, links and a + finding catalogue, is built from scratch in the UI and passes every verdict + rule except review. +- Checkpoint: owner tries it. + +### V1-2.7 Preview, review and publication UI + +- Objective: preview as a practitioner, verdict, changes since the base, + round screen, publication confirmation, deprecation and archive. +- Dependencies: V1-2.6. +- Tests: `e2e:shell` A5, R1, A6, A7, A8 with two accounts; S1 refusals. +- Acceptance: a sandbox sheet goes from creation to publication with two + people, every column of §6.3 filled; a new version corrects it and the first + stays readable. +- Checkpoint: owner runs the journey with a second account. + +### V1-2.8 Equine review preparation + +- Objective: §14, decisions O17 and O18. +- Dependencies: V1-2.7. +- Tests: `pnpm r5:import-equine --check`, oracles if a changeset is applied. +- Acceptance: the equine draft is submittable on the sandbox and its round + shows the dossier; nothing published; statuses unchanged except by + owner-decided changes. +- Checkpoint: owner and the business reviewer. + +### V1-2.9 FR/EN acceptance, tests and closure + +- Objective: full journeys FR and EN, docs (ANATOMICAL_SHEET_MODEL, SUPABASE, + STORAGE, IDENTITY with the MFA runbook, IMPLEMENTATION_PLAN, CLAUDE.md, + `.claude/rules/sheet-model.md`, CHANGELOG), DEV procedure for M4 to M6 (and + the worker under A), closure inventory. +- Acceptance: `check:all` green, `e2e:shell` green, release replay green, + fresh verifier and security audit; merge only on the owner's go. +- Checkpoint: owner. + +### Deferred (not V1-2) + +Level 2 editor (§8.3), package export and import, authoring in production +(needs a production stack, a worker and an id-preserving import), equine +authority switch (V1-3), storage of report migration maps (V1-3), personal and +community sheets, sharing, follows, forks, students, species-scoped grants, +review quorum, e-mail notifications, species deactivation, Storage object +deletion, offline cache, report editor switch and version links (V1-3), +professional verification (Step 9). + +--- + +## 17. Decisions for the owner + +| Id | Question | Options | Proposal | +|---|---|---|---| +| O1 | Who holds catalogue rights | a) explicit capabilities for editor, reviewer, publisher, granted by the owner; b) reviewer explicit, editor and publisher implicit for every owner and admin | a (D1 « habilités ») | +| O2 | Separation of duties | a) S1: no author approves, publisher may approve; b) three distinct people; c) traced only | a | +| O3 | `to_confirm` and `inherited` at publication | a) no `to_confirm` left, `inherited` from the base allowed; b) a), and `inherited` also forbidden (every element read); c) the reviewer may accept named `to_confirm` items, kept visible as « à confirmer » | a | +| O4 | MFA | a) every catalogue write and draft read; b) publication and grants only; c) later, risk accepted | a | +| O5 | Review quorum | a) one decision closes a round; b) N approvals | a | +| O6 | Scope disclaimer required to publish | yes / no | yes | +| O7 | Status of an element created in the editor | `to_confirm` / other | `to_confirm` | +| O8 | Archived sheets | a) published versions readable by id to every eligible reader; b) narrowed to referenced versions in V1-3 | a now, b reviewed in V1-3 | +| O9 | New species (amends V1-1 §5.4 and N1) | a) owner RPC, inline in sheet creation, visible in animal forms at once; b) a migration per species | a | +| O10 | Several official sheets per species | allowed / one per species | allowed | +| O11 | Copy the finding catalogue of a published sheet into a new draft (statuses reset) | in MVP / deferred | in MVP | +| O12 | Saving | a) explicit save, leave guard, local recovery; b) autosave | a | +| O13 | Package export and import | deferred with authoring in production | deferred | +| O14 | Editor below 1 024 px | read-only with notice / full | read-only | +| O15 | Server verdict | A worker job on each submitted revision (a running worker on every stack with reviews) / B two client computations | A | +| O16 | Route paths and French labels of §3 and §11.1 | as proposed / other | as proposed | +| O17 | Equine authority in V1-2 | a) pipeline, app editor read-only for the equine, switch with V1-3; b) switch in V1-2 with the seed made insert-only and an export back to Git | a | +| O18 | Equine items of §14 (carpus statuses, REVIEW-REPORT omissions, overlaps, moved points, RR-10 baseline) | each: fix in V1-2.8 through the pipeline / leave to the business review | owner | +| O19 | SVG cleaning before upload | a) admin-confirmed cleaning with the removed list; b) refusal and a written export recipe | a | +| O20 | RR-2 fingerprint rollback limit before any user sees a published sheet | ship the switch with the release / alias registry | owner | + +--- + +## 18. Documents touched by V1-2.0 + +- `docs/development/V1-2_ANATOMICAL_SHEETS.md` (this file, new). +- `docs/development/V1-1_OWNERS_ANIMALS.md`: status lines (applied to DEV, + browser acceptance, merged into `develop` 9135d73). +- `CLAUDE.md`: the stale « not applied to Supabase DEV » sentence of the + roadmap paragraph, and a pointer to this contract. +- `.claude/tasks/TODO.md`: V1-1 closed and merged; V1-2 entry. +- `.claude/memory/decisions.md` (BDR-081), `.claude/memory/journal.md`. + +To update at ratification, not before: `IMPLEMENTATION_PLAN.md` §0 and Steps +13 and 17 (editor scope moved into V1-2 for official sheets), +`ANATOMICAL_SHEET_MODEL.md` (stale « Zod owns its shape » and `content_jsonb` +mentions), `OPEN_QUESTIONS.md` conflict 2 (answered by D3), +`.claude/rules/sheet-model.md` (uploads become an application path). + +--- + +## 19. Challenge record (2026-10-27) + +Three fresh plan challengers read the first draft against the repository. + +| Lens | Verdict | Main findings and what changed | +|---|---|---| +| Correctness | FATAL (2 blockers) | Deprecated versions deletable (F13 added, §6.7); `to_confirm` relabelled `inherited` bypassed D2 (`publish.inherited.new`, change list, §6.5); finding ids unique among siblings only (element keys, §3); client fingerprint stored unchecked (verdict, §6.4); S1 too narrow (author set); sheet metadata outside review (row refreshed at publication); old publish signature kept (dropped); `can_edit_sheet` unchanged (F14); optional map would touch protected readers (`PreviewSheet`); map unbound to review (map storage moved to V1-3); seed tool broken by F12 (read RPC); code counts corrected (19 errors, 17 mirrored); F3 reworded | +| Robustness | FATAL (1 blocker) | Quarantine-only job could never verify the DEV drawing (in-place verification, no quarantine copy, §9); commit order, retries and shared keys (no overwrite, `object_conflict`, existence and size check in SQL); stopped worker blocked authoring (authoring needs `uploaded` only); fingerprint and deprecation guard (verdict value, extended guard); caps only partly on the server (verdict carries all caps); converging seed and ids across environments (equine stays on the pipeline, packages and production authoring deferred); lock order; MFA in policies and recovery; local recovery, undo by size, lowercase ids; timing at the caps; release replay; worker isolation and purge guard; no species deactivation | +| Simplicity | CONCERNS | Steps cut by vertical (server workflow in one step, four owner checkpoints); single verdict instead of a growing SQL mirror; quarantine pipeline dropped; package import and production authoring deferred; review rows slimmed (no digest, no duplicated publication columns, comments separate from the decision); « Marquer comme relu » on subtrees and an effort estimate; SVG cleaning before upload; wireframes only for new patterns; no species screen; no sheet-row metadata RPC; map storage to V1-3; generic edit primitives. Kept against the finding: three capabilities (D1 « habilités »; O1 b is offered) and option A for the verdict (the only server-side proof; O15 B is offered) |