From 7fec2ce86f881d853c7631d56e4ecbda43969889 Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 28 Oct 2026 11:35:51 +0100 Subject: [PATCH] docs(docs): consolidate V1-2 contract with ratified O1-O23, open AR-1 --- .claude/rules/sheet-model.md | 31 +- CLAUDE.md | 3 +- docs/development/ANATOMICAL_SHEET_MODEL.md | 29 +- docs/development/IMPLEMENTATION_PLAN.md | 17 +- docs/development/OPEN_QUESTIONS.md | 11 + docs/development/V1-1_OWNERS_ANIMALS.md | 3 + docs/development/V1-2_ANATOMICAL_SHEETS.md | 2173 ++++++++++++++------ 7 files changed, 1621 insertions(+), 646 deletions(-) diff --git a/.claude/rules/sheet-model.md b/.claude/rules/sheet-model.md index 0bcba0ae..043ba26c 100644 --- a/.claude/rules/sheet-model.md +++ b/.claude/rules/sheet-model.md @@ -1,17 +1,28 @@ --- -paths: ["crates/core/src/domain/sheet/**", "docs/development/ANATOMICAL_SHEET_MODEL.md", "supabase/seed/anatomical-sheets/**", "crates/core/src/bin/upload_sheet_assets/**"] +paths: ["crates/core/src/domain/sheet/**", "docs/development/ANATOMICAL_SHEET_MODEL.md", "docs/development/V1-2_ANATOMICAL_SHEETS.md", "supabase/seed/anatomical-sheets/**", "crates/core/src/bin/upload_sheet_assets/**"] --- # Anatomical sheet model (crates/core/src/domain/sheet + migration 20261008110000) -- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs. +- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth for the model as built: document shape, issue + codes, tables, RPCs. `docs/development/V1-2_ANATOMICAL_SHEETS.md` holds the ratified V1-2 rules (O1-O23, BDR-082): + every V1-2 change follows it, and V1-2.9 folds it back into the model file. - Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime. -- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then - `publish_sheet_version`. Integrity rule codes are shared by `validate_sheet_document` (Rust core) and - `private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table. +- A published version is immutable (trigger, every role) and, from V1-2, never deleted, even deprecated. Change = new + draft (`create_sheet_draft`) then publication; from V1-2, publication only from an approved round on a server + verdict of the core. +- The Rust core is the only authority on document rules (O22): add a rule to `validate_sheet_document` and to the spec + table only. Never extend `private.sheet_document_issues`: V1-2 (M5) removes its business rules and keeps the + structural and relational guards. - Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`. -- Official equine sheet = generated seed `draft/` (`pnpm import:equine --out` into an empty folder, then reviewed and copied; never edit `legacy-import/` or `draft/` by hand; - `curation_draft` / `curation_review` fail on drift, `pnpm import:equine --check` lists it). Every content change goes through `curation/changes.json` (traced in CHANGELOG.md). - It is a DRAFT until a platform admin publishes it after business review of `REVIEW-REPORT.md`. -- Sheet SVG bytes live in Storage bucket `anatomical-sheet-assets` as `.svg`; uploads are an operator task - (`pnpm assets:upload ` with the service key in env), never from the browser. + No bump during V1-2 (BLK-008). +- Historical equine sheet `503dc301…` = generated seed `draft/` (`pnpm import:equine --out` into an empty folder, then + reviewed and copied; never edit `legacy-import/` or `draft/` by hand; `curation_draft` / `curation_review` fail on + drift, `pnpm import:equine --check` lists it). Its content changes only through `curation/changes.json` (traced in + CHANGELOG.md), and the pipeline stays unchanged during V1-2. It is never published; equine work moves to an + application working copy (O17), whose publication is an owner act after the business review. +- Sheet SVG bytes live in Storage bucket `anatomical-sheet-assets` as `.svg`, never overwritten. Until M5 + (V1-2.1) uploads are an operator task (`pnpm assets:upload `, local stacks, service key in env); from M5, + editors upload from the application after the core's cleaning, and the worker verifies every submitted revision (M6). +- Omitted `review_status` means `inherited` (`#[serde(default)]`): any check on statuses treats an absent value as + `inherited`. diff --git a/CLAUDE.md b/CLAUDE.md index 10b99407..35fd63bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,8 @@ business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validate `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)). -V1-2 contract (draft, owner review pending): `docs/development/V1-2_ANATOMICAL_SHEETS.md`, branch `feature/v1-2-anatomical-sheets`. +V1-2 contract (decisions O1-O23 ratified 2026-10-28, BDR-082; contract under the owner's final review, no implementation before +the owner's go): `docs/development/V1-2_ANATOMICAL_SHEETS.md`, branch `feature/v1-2-anatomical-sheets`. --- diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md index 8dcc4730..6b47f053 100644 --- a/docs/development/ANATOMICAL_SHEET_MODEL.md +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -11,6 +11,15 @@ manual report points confirmed). Out of scope here: the legacy importer and the official equine draft (next step), the visual editor, cloud reports, community, booking. +V1-2 (decisions ratified 2026-10-28, `V1-2_ANATOMICAL_SHEETS.md`, BDR-082) +replaces the validation tiers of §2.1, the lifecycle of §3.1 and the access +helpers of §3.2: explicit rights with MFA, drafts saved through an RPC with +revisions, review rounds verified by the Rust worker, the SQL mirror of the +integrity rules removed (the core is the only authority), species created +inactive, the historical equine sheet kept read-only beside an application +working copy. Until V1-2.9 rewrites those parts, this file describes the +model as built. + ## 1. Two layers | Layer | Where | Role | @@ -19,8 +28,9 @@ Out of scope here: the legacy importer and the official equine draft | Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | The database stores the document as JSONB in -`anatomical_sheet_versions.content`. Zod is the shape contract at the -application boundary; SQL checks what only SQL can know (species of the +`anatomical_sheet_versions.content`. The Rust core's strict parser is the +shape contract (`crates/core/src/domain/sheet/schema.rs`, through wasm in the +browser); SQL checks what only SQL can know (species of the parent sheet, assets registered for the sheet, immutability, numbering) plus the referential rules of §3 at publication time, so a browser cannot publish a dangling document. @@ -109,8 +119,8 @@ Why these shapes: | Tier | Function | When | | ---------- | ------------------------------------------ | ----------------------------------------------------------------------------- | -| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | -| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | +| Shape | strict parse of the Rust core (`schema.rs`) | every load and every check | +| Integrity | `validate_sheet_document(doc)` (core; `sheet.check` through wasm) | editor feedback; `publishable` = no issue with `severity: 'error'` | | Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | `SheetIssue = { code, severity: 'error' | 'warning', path, message }`; the @@ -140,17 +150,20 @@ Integrity rules (error unless stated): | `reference.id.duplicate` | reference ids unique | | `finding.reference.missing` | every `reference_ids` entry (categories and nodes, any depth) is declared | | `region.count_range.invalid` | `count_range.min ≤ count ≤ count_range.max` when a range is given | -| `reference.url.scheme` (SQL only; Zod refuses it at parse) | every `references[].url` is null or starts with `http://` / `https://` | +| `reference.url.scheme` (SQL only; the core's strict parse refuses it) | every `references[].url` is null or starts with `http://` / `https://` | A draft may be saved with errors. Publishing a document with errors is -refused in TypeScript (`assertPublishable`) and in SQL: +refused on the client (`publishSheetVersion` in `packages/supabase` runs the +core's `sheet.check`) and in SQL: `private.sheet_document_issues` re-checks every error-level rule except parent cycles and sibling uniqueness (citations are walked recursively with a `jsonpath` `**` descent) and reports `document.shape` when an id-bearing collection is not an array; `private.sheet_document_unknown_assets` adds `view.asset.unknown` when a view points at an asset not registered for the sheet. Both run inside -`publish_sheet_version`. +`publish_sheet_version`. V1-2 removes the business part of this mirror and the +client gate, keeps the structural and relational guards, and publishes only on +a server verdict of the core (contract §12.2, O22). ## 3. Relational model @@ -277,7 +290,7 @@ with the community step (§17.4). | Criterion | Where it is proven | | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | A sheet with several views and annotations explicitly linked to findings | `crates/core/tests/fixtures/horse-slice.json` (from `horse-slice.ts`, deleted at R5.7; 2 views, trigger, spine region, bilateral joint, 3 finding kinds); schema + integrity tests | -| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | +| Ids stable under translation | test: renaming every label leaves ids, references and `validate_sheet_document` output unchanged | | Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501` for the table owner; zero rows touched through the API role | | New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | | Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | diff --git a/docs/development/IMPLEMENTATION_PLAN.md b/docs/development/IMPLEMENTATION_PLAN.md index 385e5d87..32058019 100644 --- a/docs/development/IMPLEMENTATION_PLAN.md +++ b/docs/development/IMPLEMENTATION_PLAN.md @@ -29,7 +29,7 @@ computer. Inventory: `.claude/audits/2026-10-25-functional-inventory.md`. |---|---|---| | P0 | Documents realigned on the code, decisions recorded (`OPEN_QUESTIONS.md` statuses) | none | | V1-1 | Clients and animals of a practitioner's workspace, with the permission frame of future cabinets (`V1-1_OWNERS_ANIMALS.md`) | 12 reduced, frame of 10 | -| V1-2 | Anatomical sheets loaded from Supabase under control (no publication of the equine draft without the owner) | 13 reduced | +| V1-2 | Official anatomical sheets administered from the application: rights, structured editor, server-verified review and publication, catalogue; the equine sheet prepared, never published inside V1-2 (`V1-2_ANATOMICAL_SHEETS.md`, decisions ratified 2026-10-28, BDR-082) | 13, and 17 reduced to official sheets | | V1-3 | Bilans persisted, linked to an animal, history | 14 (+ 11 skeleton if a quota applies) | | V1-4 | Stored PDF artifacts and authorised sharing | 15 reduced, sharing part of 12 | | V1-5 | Cross-cutting mobile and accessibility validation | design README, `TEST_STRATEGY.md` | @@ -367,7 +367,7 @@ Name: Anatomical sheets in the database and official equine seed Objective: Sheet and version tables with immutability, SVG assets in Storage, seed of the official equine sheet as a draft, SheetProvider over Supabase, read-only sheet library in the app. Dependencies: Step 3, Step 4, Step 8 Changes expected: - - supabase: anatomical_sheets, anatomical_sheet_versions (content_jsonb + schema CHECK), immutability trigger on published rows, version numbering RPC, deprecate RPC, GC function with the four preconditions (no report, no fork, no grant, no pending process) returning candidates only (deletion job at Step 18), helpers can_use_sheet/can_fork_sheet (creator-only for now), operator upload of the drawings (`pnpm assets:upload`) and the generated draft seed. Publication of the official equine sheet is an explicit act of a platform admin after the business review of REVIEW-REPORT.md (BDR-034, BDR-037); no step publishes it automatically. + - supabase: anatomical_sheets, anatomical_sheet_versions (content + schema CHECK), immutability trigger on published rows, version numbering RPC, deprecate RPC, GC function with the four preconditions (no report, no fork, no grant, no pending process) returning candidates only (deletion job at Step 18), helpers can_use_sheet/can_fork_sheet (creator-only for now), operator upload of the drawings (`pnpm assets:upload`) and the generated draft seed. Publication of the official equine sheet is an explicit act of a platform admin after the business review of REVIEW-REPORT.md (BDR-034, BDR-037); no step publishes it automatically. - packages/supabase: typed accessors; apps/app: SheetProvider.supabase replaces the bundled seed in production builds (bundled kept for tests), /app/anatomy read-only list and preview. Tests: pgTAP: UPDATE on published content raises; v2 numbering; GC preconditions each individually; non-creator cannot read a private sheet; integration: seed is idempotent and byte-faithful (checksums). Manual validation: open /app/anatomy, see "Faunosteo / Cheval / officielle" with its draft or published status, preview both views, click zones (no report yet). @@ -384,6 +384,11 @@ candidates. Roadmap item V1-2 reduces the step to a controlled loading of the sheets; whether a signed-in practitioner may load the unpublished draft is an owner decision taken at V1-2. +Step 13 note (2026-10-28): V1-2 absorbs the provider and the library +(`V1-2_ANATOMICAL_SHEETS.md` §10, §11). Drafts are never served to readers +(D3); the catalogue is read under an explicit, provisional catalogue access +until the entitlements of Step 11 (O21). The GC candidates stay with Step 18. + ```text Step 14 Name: Cloud reports @@ -444,6 +449,14 @@ Definition of Done: architecture Sprint 6 (except "promote manual point", added Risks: largest UI step; split into sub-branches (canvas tools / panels / publish) each merged green behind a "beta" flag; feature parity gaps with the vanilla tool found late (mitigate with the reference tests first). ``` +Step 17 note (2026-10-28): requirement D9 (BDR-081) moves the editor of +official sheets into V1-2, at the level 1 of `V1-2_ANATOMICAL_SHEETS.md` §8.2, +with server-verified review and publication. It supersedes, for official +sheets, the 2026-10-25 rule « no graphic editor until Step 17 »: the curation +pipeline stays the authority of the historical equine sheet only, whose work +moves to an application working copy (O17). Step 17 keeps personal sheets, the +level 2 editor (§8.3) and the community parts. + ```text Step 18 Name: Community diff --git a/docs/development/OPEN_QUESTIONS.md b/docs/development/OPEN_QUESTIONS.md index 90004d6a..16c0762b 100644 --- a/docs/development/OPEN_QUESTIONS.md +++ b/docs/development/OPEN_QUESTIONS.md @@ -49,12 +49,23 @@ Step 5). sources and the Rust pipeline, reviewed, tested and versioned. Annotating a bilan is distinct from changing the anatomical reference and never touches `curation/changes.json`. + Superseded for official sheets (owner, 2026-10-27, D9, BDR-081; decisions + ratified 2026-10-28, BDR-082): V1-2 brings the editor of official sheets, + with server-verified review and publication (`V1-2_ANATOMICAL_SHEETS.md`). + The curation pipeline stays the authority of the historical equine sheet + only; equine work moves to an application working copy (O17). 2. Publication of the official equine sheet: the plan's Step 13 used to expect "v1 published"; BDR-034 and BDR-037 keep it a draft until a platform admin publishes after business review. Confirmed (owner, 2026-10-25): the equine sheet stays a draft until business validation, and nothing publishes it automatically. Still open for V1-2: who triggers the review, and whether V1-2 may serve the unpublished draft to signed-in practitioners. + Resolved (owner, 2026-10-27 and 2026-10-28; BDR-081, BDR-082): drafts are + never served to readers (D3); an editor submits, a reviewer outside the + author set approves, a publisher publishes (O1, O2); the historical equine + sheet is never published and its review is prepared on a working copy, + whose publication stays an owner act after the business review, outside + V1-2 (O17, O18). 3. Recorded decision BDR-041 calls professional verification "Step 11"; the plan numbers it Step 9. Resolved: the plan's numbering is kept and the correction is the new entry BDR-072 (the registry is append-only, BDR-041 diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index eb46c17b..ae5e1649 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -320,6 +320,9 @@ which needs the clock and is checked by the RPCs (tomorrow's UTC date, §9.3): Reference data written by migration: the nine species of the contract (the existing `equine` row plus eight) and « Autre ». No other species is added. +(Amended by V1-2 O9, ratified 2026-10-28: a habilitated sheet editor creates a +species inactive, invisible in the animal forms, and the platform owner +activates it; `V1-2_ANATOMICAL_SHEETS.md` §7.2.) Slugs, names and order approved by the owner (§13.2 N1). Compatibility, checked on 2026-10-25: species are rows of `public.species` (text `id`, CHECK `^[a-z0-9][a-z0-9_-]{0,63}$`, which every slug below satisfies), never a diff --git a/docs/development/V1-2_ANATOMICAL_SHEETS.md b/docs/development/V1-2_ANATOMICAL_SHEETS.md index 91d272bc..e332a2d1 100644 --- a/docs/development/V1-2_ANATOMICAL_SHEETS.md +++ b/docs/development/V1-2_ANATOMICAL_SHEETS.md @@ -1,17 +1,16 @@ # 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. +Status: decisions RATIFIED, contract consolidated for the owner's final +review (V1-2.0, 2026-10-28), with ONE OPEN ARBITRATION REQUEST (AR-1, §17.2). +The owner approved the orientations D1 to D8 and added the mandatory +requirement D9 (BDR-081, 2026-10-27), then ratified the decisions O1 to O23 in +the brief « V1-2.0 : ratification des arbitrages O1 à O23 et consolidation du +contrat » (2026-10-28, BDR-082). This revision writes those decisions into the +rules, resolves the contradictions C1 to C14 found at the review of the first +revision (§19.2), restates the step plan (§16) and integrates a second round +of fresh challenges (§19.3), one finding of which needs the owner (AR-1). It +authorises no implementation: V1-2.1 starts only on the owner's explicit go. +V1-2.0 changes no code, migration, policy, RPC, anatomical data or DEV state. Branch: `feature/v1-2-anatomical-sheets` (off `develop` 9135d73, the V1-1 merge). Roadmap position: `IMPLEMENTATION_PLAN.md` §0, V1-2. This contract @@ -20,43 +19,56 @@ 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. +Fundamental requirement (owner, 2026-10-28): by the end of V1-2, a +habilitated administrator creates and edits a complete official sheet from the +application, prepares its SVG views, annotations and categories, submits it to +review and publishes the approved version. No deferral of this contract makes +that journey impossible; V1-2.7 proves it end to end with two accounts on the +sandbox, and the same journey runs on DEV once the owner has authorised the +operations of §16.11. + +Parts: 1 facts, 2 scope, 3 nomenclature, 4 decisions D1 to D9, 5 access, roles +and permissions, 6 lifecycle, review, verification and publication, 7 species +and new sheets, 8 editor, 9 drawings, 10 loading, 11 screens and journeys, +12 SQL defects, SQL authority and migrations, 13 security, 14 equine sheet, +15 tests, 16 implementation steps, 17 ratified decisions and open arbitration, +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 +read-only session (`default_transaction_read_only=on`), completed from the +repository on 2026-10-28. 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`). | +| Document model | Rust core, `crates/core/src/domain/sheet/schema.rs`, schema version 2, strict (`deny_unknown_fields`; reference URLs must be http or https at parse). 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). | +| Review metadata | `review_status` (`inherited`, `reviewed`, `to_confirm`) on annotations, finding categories and nodes only. The field is `#[serde(default)]` with default `inherited` (`schema.rs` l.186-188, 427, 453, 553): an omitted status means `inherited`. 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 plus `document.shape` and `reference.url.scheme`; `publish_sheet_version` adds `view.asset.unknown` (inventory in §12.2). | +| 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, not the drawings' sha256. 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. | +| Tables | `species` (10 rows: nine species and `other`; column `active`), `anatomical_sheets` (monolingual `name`, `slug`, `description`; `visibility`; status `active`, `archived`, `deleted`; slug unique per `coalesce(creator_user_id, zero uuid)` among non-deleted sheets, official sheets have a null creator), `anatomical_sheet_versions` (`draft`, `published`, `deprecated`; one draft per sheet; numbers never reused; `published_by`, `published_at` exist; content capped by `pg_column_size`, l.108, a compressed size), `anatomical_sheet_assets` (rows unique per sheet and sha256; `uploaded_at` null until confirmed; no immutability trigger). | +| Species access | Policy `species_select_active`: authenticated callers see active rows only. The animal forms read species through `fetchSpeciesLabels` under that policy; `create_animal` and `update_animal` refuse an inactive species; `create_anatomical_sheet` requires an active one (l.713). Table comment: « no API write path ». | +| Immutability | `guard_sheet_version_update` freezes published rows except the deprecation transition, comparing a fixed column list (l.219-232), and lets a draft become published with any column change (l.234-238). `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). `register_sheet_asset` returns the existing row of the same sheet and sha256 or inserts one (l.1021). `create_sheet_draft` accepts any non-draft source (l.756). The fork copies asset rows (`copy_sheet_assets`) and rewrites the document's drawing ids (`remap_document_assets`). | +| 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` (l.513-526) = active sheet and (`public` or editable); the sheet policy reads it (l.1183-1190). Editors update draft `content` and `change_note`, and sheet `name`, `slug`, `description`, by direct table UPDATE: no RPC, no audit, no concurrency check. | +| Service role | The sheet migration revokes table privileges from `public, anon, authenticated` only (l.1157-1160); Supabase default privileges give `service_role` everything (`20261025100000_workspaces.sql` l.311-314, which revokes them for V1-1 tables). The service key is also a GoTrue admin credential. | +| Platform roles | `platform_role`: owner, admin, moderator, support. DEV holds one owner. An owner may grant or revoke any role, owner included (`can_manage_platform_role`, `20261008100200_platform_roles.sql` l.83-95); `grant_platform_role` and `revoke_platform_role` check the caller's role, not its assurance level (l.189-238); the last owner cannot be revoked. No professional status (plan Step 9). | +| 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` (local stacks only) 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 | Hard rejections (`too_large`, `doctype`, `malformed`, `not_svg`, `too_many_elements`, `too_deep`, `too_many_uses`, `too_complex`, `reference_cycle`) and allowlist removals listed as `tag` or `tag@attribute` (`sanitize.rs`); `class`, `style` and font attributes are allowed except on the root (l.44, l.109-116, l.178-183). A drawing with any removal is refused at load, never repaired (`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 mirror and the unknown-asset check. Client: `packages/supabase/src/anatomical-sheets.ts` `publishSheetVersion` runs the core's `sheet.check`, 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). Every sheet-bound core operation, `view.canvas` included, takes a `LoadedSheet` (`ops.rs` l.209), which requires a report migration map passed 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`. | +| Entitlements | Plan Step 11 (plans, `entitlement_grants`, `has_active_entitlement`) is not built: no offer, plan or subscription exists in the model. | +| MFA | TOTP enrolment and verification enabled server-side (up to 10 factors); `jwt_expiry = 3600` and no `[auth.sessions]` limit in `supabase/config.toml`; 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, keyless sandboxed decode child), built around avatars: the backend trait holds avatar operations (`backend.rs` l.82), the spawner expects a 512² WebP (`spawn.rs` l.160), child caps 5 MiB in and 512 KiB out (`limits.rs` l.6, l.8), RPC bodies capped at 1 MiB (`http.rs` l.18), a broken child stops the process (`run.rs` l.113), purges carry their bucket (`backend.rs`). It links no core module. `pnpm db:sandbox` starts no worker. Stopped on DEV (AVATAR-01): an avatar upload of the V1-1 acceptance waits in state `uploaded`, kept on the owner's decision, and the purge queue holds due rows (13 at the 2026-10-26 preflight). A worker started on DEV would process them. | +| Seed | `equine_draft.sql` converges: it overwrites the draft's content whenever it differs and the sheet has one version, and inserts the sheet with `on conflict (id) do nothing`. It is listed for every environment (`SUPABASE.md` §3); outside local stacks it is applied by hand by the owner. The report editor's bundle reads the same seed folder. | +| DEV data | 12 migrations. One sheet `503dc301-a8b1-50d4-9e44-0919b2fc2916` (equine, official, `private`, `active`, null creator, slug `faunosteo-cheval`, 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`. | +| Equine draft | 839 status-bearing elements: 28 annotations (22 points, 5 zones, 1 detail view link, all with a geometry), 81 finding categories, 730 nodes; 188 `to_confirm`, 31 `reviewed`, 620 `inherited`, of which only 219 statuses are written in `document.json` (the 620 `inherited` are omitted as the default). Also 2 views (`main`, `head`), 27 finding zones, 48 references, 5 vertebral regions, 5 annotation categories; scope disclaimer present in FR (521 characters) and EN (488). | | 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. | --- @@ -65,26 +77,46 @@ read-only session (`default_transaction_read_only=on`). Line numbers refer to In V1-2: -1. an administration space where authorised staff list, filter and create +1. an administration space where habilitated 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. + §8.2), upload and clean drawings, preview, read the completeness report, + submit to review, review, publish, deprecate and archive, with the full + history; +2. a traceable review workflow with progressive reviews (§6.3), a server + verdict computed by the Rust worker (§6.4) and an atomic publication gate; +3. explicit rights: three capabilities and a provisional catalogue access, + granted by the owner, with MFA for every administrative operation (§5); +4. a read-only catalogue of published official sheets for accounts with + catalogue access (§5.3); +5. loading of a stored version into the Rust core for preview, editing and + catalogue, with integrity checks on the document, the fingerprint and the + drawings; +6. hardening of the existing SQL lifecycle, and the Rust core as the only + authority on document rules (§12.2); +7. new species created inactive by editors and activated by the owner (§7); +8. a working copy of the equine historical sheet and the preparation of its + review, without publication (§14). 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). +marketplace, editing by students, rights scoped by species or by sheet, the +level 2 editor (§8.3), the copy of a finding catalogue between sheets (O11), +package export and import between environments (O13), a synchronous +verification service (O15), review quorum (O5), e-mail notifications, species +deactivation and deletion, 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), entitlements and offers (plan Step 11), deletion +of Storage objects (one audited exception: §9.3), and the publication of any +equine sheet (an owner act after the business review, never inside V1-2). + +Consequences of the deferrals. None of them is needed by the fundamental +journey. Without packages (O13), content prepared on one stack never moves to +another: the sandbox serves the tests and rehearsals, DEV becomes the +authoring stack after the closure, and authoring for production (a production +stack, a running worker, either authoring there or a package import that +preserves ids) is decided before any production use. Without a catalogue copy +(O11), each new species' finding catalogue is entered by hand from cited +sources. --- @@ -94,299 +126,690 @@ its review). |---|---|---| | Fiche anatomique | Anatomical sheet | sheet | | Fiche officielle | Official sheet | `is_official` | -| Version, brouillon, publiée, retirée | Version, draft, published, withdrawn | `draft`, `published`, `deprecated` | +| Fiche historique (pipeline Git) | Historical sheet (Git pipeline) | the equine sheet `503dc301…` (§14.2) | +| Copie de travail | Working copy | `working_copy_source_version_id` (§14.3) | +| 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 | +| Vérification en cours, à relire, approuvée, modifications demandées, soumission retirée, vérification échouée | Verifying, awaiting review, approved, changes requested, submission withdrawn, verification failed | round status `verifying`, `open`, `approved`, `changes_requested`, `withdrawn`, `verification_failed` | +| Groupe de revue, groupe lu | Review group, group read | review group, acknowledgment (§6.3) | +| Accès au catalogue | Catalogue access | right `catalog_reader` (§5.3) | +| Habilitation | Capability | right `sheet_editor`, `sheet_reviewer`, `sheet_publisher` (§5.2) | +| Relecteur, relectrice | Reviewer | `sheet_reviewer` | +| Éditeur de fiches | Sheet editor | `sheet_editor` | +| Responsable de publication | Publisher | `sheet_publisher` | +| À confirmer, relu, hérité, non relu | To confirm, reviewed, inherited, not reviewed | `to_confirm`, `reviewed`, `inherited` | +| Complétude | Completeness | verdict counts (§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 `/` | +| Clé d'élément | Element key | §6.6 | -The French labels of statuses and capabilities are proposals (§17, O16). +Routes and the labels of this table are ratified (O16), with « Hérité, non +relu » / « Inherited, not reviewed » for `inherited`. The labels added by this +revision for the states of O17, O21 and O23 and the route `/app/admin/species` +(O9) follow the same convention and are confirmed on the V1-2.4 wireframes. +Every failure code, round state and validation code has an FR and an EN +message (§6.5, §15). --- ## 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. +Owner orientations, approved (BDR-081). The column « Contract » says where +each one becomes rules. | 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 | +| 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.2 capabilities, §5.5 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.6, §6.7 (O3 B: `inherited` blocks too) | +| 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, §5.3 row predicate, §9.4, §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.3 catalogue access (O21), §5.4 | +| 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.4, §12.3 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 | +| 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.8, §6.9, §9.4, 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, §12.2 | + +Reading of D3 and D9 retained by O1: « administrators » means habilitated +administrators, that is a platform owner or admin holding the matching +capability. A platform admin without a capability sees no draft. --- -## 5. Roles and permissions +## 5. Access, roles and permissions -### 5.1 Notions +### 5.1 Layers -| Notion | Where it lives | Effect in V1-2 | +Each layer is checked on the server; none implies the next. + +| Layer | Established by | Gives | |---|---|---| -| 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. | +| Authentication | a Supabase Auth session | nothing by itself | +| Email confirmation | `email_confirmed_at` | proves control of a mailbox; a precondition of every right below, never a proof of competence | +| Catalogue access | `private.can_read_official_catalog(uid)` (§5.3) | the catalogue list and the current published versions | +| Historical reads | the same predicate (O8) | published and deprecated versions by id, archived sheets included | +| Draft reads | a capability and `aal2` | drafts, rounds, verdicts, comments, history, drawings of drafts | +| Capabilities | `anatomical_catalog_grants` (§5.2) and `aal2` | edit, review, publish, per the matrix of §5.4 | +| Platform role | `profile_roles` | a precondition of `sheet_editor` and `sheet_publisher`; no catalogue right by itself | +| Professional status | plan Step 9, not built | none; never inferred from a right or a role | +| Workspace membership | V1-1 tables | none: no catalogue rule reads workspace tables and no V1-1 rule reads catalogue tables | -Who may hold a capability (proposal): +### 5.2 Capabilities (O1 A + D) -- `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. +Three explicit, independent capabilities: `sheet_editor`, `sheet_reviewer`, +`sheet_publisher`. They live in `anatomical_catalog_grants` (M4) with the +provisional catalogue access of §5.3, one row per grant: -`private.can_edit_sheet` is redefined for official sheets (M4): it requires -`sheet_editor` and `has_mfa()`; owner and admin without the capability lose +| Column | Meaning | +|---|---| +| `user_id`, `grant_kind` | the account and the right (`sheet_editor`, `sheet_reviewer`, `sheet_publisher`, `catalog_reader`) | +| `reason` | required motive, 1 to 1 000 characters | +| `verification_note` | required for the three capabilities: the qualification declared and what the owner verified, 1 to 1 000 characters (for `sheet_reviewer`, the professional elements the owner checked; never a certification) | +| `granted_by`, `granted_at` | the platform owner, the time | +| `expires_at` | optional end; later than `granted_at` | +| `revoked_by`, `revoked_at`, `revocation_reason` | set once by a revocation, reason required | + +- Writes: `grant_catalog_right(user_id, kind, reason, verification_note, + expires_at)` and `revoke_catalog_right(grant_id, reason)`, platform owner + with `aal2`, audited with every field. Rows are never updated otherwise and + never deleted; a renewal is a new row. One active row per account and kind. +- Active grant: not revoked, and no `expires_at` or `expires_at` in the + future, read at every request. +- Eligibility, checked at grant and at every use: active profile and + confirmed email for every kind; for the three capabilities, a verified TOTP + factor at grant time, so a capability is never handed to an account whose + first factor anyone holding its password could still enrol; an active + platform role owner or admin for `sheet_editor` and `sheet_publisher`. A + reviewer need not hold any platform role: partner veterinarians and + osteopaths are reviewers without being administrators. Losing the platform + role suspends an editor or publisher capability without deleting the grant + row. +- The owner grants itself at first use; no migration grants anything. +- Scope: every capability is global, over every official sheet. A reviewer + named for one species reads the drafts of all species. Rights scoped by + species or by sheet are deferred. The per-sheet controls of V1-2 are rules, + not grants: separation of duties per round (§5.5), the protected historical + sheet (§14.2), the frozen draft (§6.1), one draft per sheet. +- Expiry and revocation take effect at the next request: + - an editor loses draft reads and writes; the saves already made stay in + the author sets (history); + - a reviewer's acknowledgments and approvals count only while the reviewer + holds an active grant, checked at approval and at publication; a renewal + makes them count again; while they do not count, publication answers + `publish.approval.invalid` and the round stays `approved` until an editor + withdraws it or the grant is renewed; published versions are untouched; + - a publisher can no longer publish, deprecate or archive. +- The rights screen shows active, expiring (within 30 days), expired and + revoked grants with their reason and verification note. No e-mail in V1-2. + +Predicates (M4), kept apart so no check tests the wrong account: + +- `private.grant_active(uid, kind)`: the grant and its eligibility, without + any assurance level; used for stored actors (acknowledgers, approver). +- `private.caller_has(kind)`: `grant_active(auth.uid(), kind)` and + `has_mfa()`; used for the calling session. + +`private.can_edit_sheet` is redefined for official sheets (M4) on +`caller_has('sheet_editor')`: 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). +it inherits the change, and pgTAP proves « admin without capability +refused » for each RPC and policy (§15). -### 5.2 Matrix +### 5.3 Catalogue access (O21) -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. +Reading the published catalogue is a right of its own, distinct from +authentication, from email confirmation, from the capabilities and from any +platform role. -| 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) | +- Predicate `private.can_read_official_catalog(uid)`, provisional and + fail-closed: active profile, and confirmed email, and (an active + `catalog_reader` grant or an active capability). Anything unknown or + missing answers false. Platform roles grant nothing by themselves. +- `catalog_reader` grants follow §5.2 (owner only, reason required, + verification note and verified factor not required, expiry optional, + audited, no `aal2` needed to use them). +- Row predicate for readers, the same on sheets, versions, asset rows and + Storage objects: an official, non-deleted sheet with at least one published + or deprecated version, and `can_read_official_catalog`. The `visibility` + branch of `can_use_sheet` is dropped from every catalogue predicate. A sheet + that only has a draft, and an inactive species' id through it, are + invisible to readers. Reader column grants exclude `last_version_number`, + `updated_at` and `working_copy_source_version_id`. +- The predicate gates the catalogue list, the published and deprecated + versions by id, archived sheets included (O8), and their drawings. +- Definitive rights belong to the entitlement engine of plan Step 11 (offers, + `has_active_entitlement`), which does not exist. Nothing in V1-2 simulates + it. Switch conditions: Step 11 ships a catalogue capability (proposed name + `catalog.read`, added to the Step 11 capability catalogue); an owner + decision then sets the predicate to (entitlement or capability), says what + becomes of the provisional `catalog_reader` grants, and comes with its own + pgTAP matrix. If V1-3 needs every practitioner to load sheets before Step 11 + exists, V1-3 decides between provisional grants per practitioner and + building Step 11 first. +- Tests (pgTAP, §15): anonymous, authenticated unconfirmed, confirmed without + grant, expired and revoked `catalog_reader`, deactivated, platform admin, + moderator and support without grant: refused; `catalog_reader` and + capability holders: allowed; a draft-only sheet invisible to every reader. -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.4 Matrix -### 5.3 Separation of duties (proposal S1) +R = catalogue reader (§5.3, without capability), E = sheet editor, V = sheet +reviewer, P = sheet publisher, O = platform owner acting as owner (rights, +species activation and renaming). A person may hold several rights; the owner +acts on sheets only through capabilities it granted itself. Every operation +except the first two lines requires an `aal2` session (§5.6), in RPCs and in +the table and Storage policies alike. -- 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. +| Operation | R | E | V | P | O | +|---|---|---|---|---|---| +| List the catalogue, read the current published version | yes | yes | yes | yes | no | +| Read a published or deprecated version by id, archived sheet included | yes | yes | yes | yes | no | +| Read drafts, rounds, verdicts, comments, history, drawings of drafts | no | yes | yes | yes | no | +| List catalogue species, active and inactive | no | yes | yes | yes | yes | +| Create an inactive species, edit an inactive species' names and order | no | yes | no | no | no | +| Activate a species, correct an active species' names | no | no | no | no | yes | +| Create an official sheet, a working copy (§14.3), a draft; save; register and upload drawings; delete a draft without rounds | no | yes | no | no | no | +| Submit a draft, withdraw a submission | no | yes | no | no | no | +| Comment a round | no | yes | yes | yes | no | +| Acknowledge review groups, approve or request changes (never as an author, §5.5) | no | no | yes | no | no | +| Publish an approved round, deprecate a version, archive and restore a sheet | no | no | no | yes | no | +| Grant and revoke rights | no | no | no | no | yes | +| Create a personal sheet, fork, change visibility | closed in V1-2 (D5) | + +Moderator, support, unconfirmed, deactivated and anonymous accounts, and +platform admins without a right: nothing. Service role: only the worker RPCs +of §6.4, the upload confirmation and the narrow read RPC of the operator tool +(§9.5); no table privilege on any catalogue table (F12, §12.1). + +### 5.5 Separation of duties (O2 A) and the first publication + +- The author set of a draft is maintained by a trigger: the account that + created the draft version (new sheet, working copy or draft from a + published version) and every account that changed its content since. It is + frozen into the round at submission and checked on the server. +- No member of a round's author set acknowledges a group of that round or + approves it. +- A content write without an authenticated actor is refused for every sheet + except the historical sheet (§14.2), so no write escapes the 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. + bump), so an empty save cannot move authorship. +- Publication needs `sheet_publisher`; the publisher may be an author or the + approver. Two distinct people suffice: one who wrote the draft, one + habilitated to review and approve it. +- The review screen shows the author set, the acknowledgments and the + approver with the reason and verification note of each reviewer's grant. -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. +A sole owner cannot publish: as an author it can neither acknowledge nor +approve its own draft. The system offers no override. One residual remains: +the owner could create a second account and grant it `sheet_reviewer`; that +path is not silent, since the grant, its reason and verification note, and +every acknowledgment and decision are audited and shown on the round, but it +cannot be detected technically until professional verification exists +(plan Step 9). -### 5.4 Strong authentication (§17, O4) +First publication with one owner and one business reviewer (journey A0, then +A1 to A6): -- `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). +1. The owner enrols two TOTP factors, steps up, grants itself `sheet_editor` + and `sheet_publisher` with a reason. +2. The business reviewer signs up, confirms the e-mail address and enrols a + TOTP factor; the owner then grants `sheet_reviewer` with a reason, a + verification note and possibly an expiry. +3. The owner creates the sheet, edits, uploads, saves and submits; the worker + verifies the revision; the round opens. +4. The reviewer reads and comments, over as many rounds as needed (§6.3); the + owner applies the answers and marks the read groups; the reviewer + acknowledges every group, then approves with a note. +5. The owner publishes the approved round. + +### 5.6 Strong authentication (O4 A) + +- `private.has_mfa()` reads `(auth.jwt() ->> 'aal') = 'aal2'`. Through + `caller_has` it is required by every catalogue RPC except the reader RPCs, + by the capability branches of the version, round, comment, acknowledgment + and asset policies and of the Storage read, by the rights RPCs, by the + species RPCs and by the working copy. The reader branches never read it. +- Enrolment (V1-2.5, Mon compte, Sécurité): add a TOTP factor (QR code, the + secret shown once and never stored or logged by the application), verify + it with a code (a factor counts only once verified), name, list and remove + factors. Supabase requires an `aal2` session to remove a verified factor. + V1-2.5 proves that an `aal1` session of an account with a verified factor + cannot enrol another factor; if Supabase allowed it, the step stops for an + owner decision, since MFA would then be bypassable with the password alone. +- Step-up: entering `/app/admin` with an `aal1` session opens the challenge; + success upgrades the session; no admin data is requested before. +- Sessions: `aal2` belongs to the session. A token refresh keeps it, sign-out + ends it, a new sign-in starts at `aal1` (Supabase behaviour, proven by a + V1-2.5 browser test). The access token lives `jwt_expiry` (3 600 s in the + local configuration; V1-2.1 records the values of the sandbox and DEV). No + session time box or inactivity limit is configured, and V1-2 adds no + freshness window: a stolen `aal2` session stays usable until it ends + (residual, §13). V1-2.5 records what removing a factor does to the + account's other open sessions. +- Loss of a factor: Supabase Auth issues no recovery codes. The owner enrols + two factors on two devices before the first grant on any stack. Another + account that loses its factor keeps its `aal1` access (catalogue, rest of + the application) and loses the administration until recovery. +- Recovery is an operator procedure, never an application feature: no RPC, + screen or service path resets another account's factor, so recovery opens + no application back door. Steps: + 1. the owner confirms the requester's identity out of band and records the + reason; + 2. the owner revokes the account's capabilities (§5.2); + 3. an operator with server access signs out every session of the account + and deletes the factor (Supabase admin API with the service key on the + server, or SQL on the database container for DEV), and in the same + session writes the audit row `auth.mfa_factor_reset` through + `private.log_event` (null actor, subject, reason, operator named in the + detail); + 4. the person enrols a new factor; the owner grants the capabilities again. + The owner's own loss follows the same procedure, run by the owner at the + server. The runbook goes to `IDENTITY.md` and is rehearsed on the sandbox in + V1-2.9. +- Platform roles (O4-D): `grant_platform_role` and `revoke_platform_role` + require no `aal2`, and an owner may grant the owner role. The first revision + of this contract claimed that the catalogue stays closed without O4-D; the + security challenge of §19.3 showed it does not (an `aal1` owner session + grants owner to another account, which enrols its own factor and grants + itself every capability). O4-D was not ratified, so the contract does not + extend `aal2` to those RPCs: the choice is the open arbitration AR-1 + (§17.2). --- -## 6. Lifecycle, review and publication +## 6. Lifecycle, review, verification and publication ### 6.1 States -Versions keep their three statuses. Reviews are separate rows, so the version +Versions keep their three statuses. Rounds 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 + submit ──▶ verifying ──verdict passed──▶ open ──approve──▶ approved ──publish──▶ (version published) + │ └──request changes──▶ changes_requested + └──verdict failed, or unavailable──▶ verification_failed + verifying | 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. +- While a round is `verifying`, `open` or `approved`, the draft content is + frozen (trigger, every role, seed included). The terminal states + (`changes_requested`, `withdrawn`, `verification_failed`) unfreeze it; a + published round stays `approved` and is referenced by the version. +- One non-terminal round per draft at a time. 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. -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 and saving (O12 A) -### 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. +- A draft is created from the empty document (§7.4), from an earlier version + of the same sheet (`create_sheet_draft`), or by the working copy (§14.3). + Its base (`source_version_id`) is set only when the source is a + `published` version with a `published_review_id`, that is a version + published through a V1-2 round; any other source (deprecated, published + before M5, working copy, empty document) gives no base, and every group is + to cover (§6.3). +- Unsaved changes stay in the page. The leave guard of V1-1 protects them; + a local recovery copy, keyed by version and revision, is kept in the + browser with the report editor's persistence pattern and offered back after + a crash or an expired session, never sent automatically. +- Validation while editing: the page runs the core's checks and shows the + validation panel (§8.1). It is advisory; the server verdict decides (§6.4). +- Saving is explicit (« Enregistrer »): `save_sheet_draft(version_id, + expected_revision, document, change_note)`. The server checks the caller's + capability and `aal2`, that the version is a draft of an active official + sheet other than the historical sheet, that no round freezes it, the + revision, the structural guards of §12.2 (shape, serialised size at most + 2 MiB measured as `octet_length(content::text)`, species), and refuses an + unchanged document. It increments `revision`, the trigger adds the actor to + the author set, and the audit records `anatomical_sheet_version.saved` with + the revision. A draft may hold integrity errors while it is being written; + the verdict refuses them at submission. +- A trigger bumps `revision` on any content write, so no write slips under a + 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. + catalogue shows the published document's FR and EN texts (§10). The slug + is set at creation and never shown in routes. +- Concurrency: a stale `expected_revision` answers `draft_conflict`. The page + shows the server revision with its author and time and offers « recharger » + or « garder ma version »; the second saves the local document on the new + revision after an explicit confirmation naming what it replaces. Nothing is + overwritten silently. +- A per-actor write budget follows V1-1 D15 (thresholds in V1-2.1). -### 6.3 Review rounds +### 6.3 Review rounds, review groups and acknowledgments `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 | +| Column | Meaning | Set in | +|---|---|---| +| `version_id`, `round` | the draft and the round number | every state | +| `revision` | the revision submitted; with the freeze, `(version_id, revision)` is the « exact version » of D6 | every state | +| `authors` | the author set of §5.5, frozen at submission | every state | +| `submitted_by`, `submitted_at`, `submission_note` | the submitter | every state | +| `status` | §6.1 | every state | +| `attempts`, `lease_token`, `locked_at` | the verification job (§6.4) | while `verifying`; kept after | +| `verdict`, `verified_at`, `verified_with` | the server verdict for this revision, written by the worker RPC only | `open`, `approved`, `changes_requested`, and `verification_failed` with outcome `failed` | +| `failure_outcome`, `failure_code` | `failed` or `unavailable` and the closed code (§6.5) | `verification_failed` | +| `decided_by`, `decided_at`, `decision_note` | the approver or the reviewer who requested changes; the note is required | `approved`, `changes_requested` | +| `withdrawn_by`, `withdrawn_at`, `withdrawal_note` | the editor who withdrew | `withdrawn` | -`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. +Review groups. The verdict splits the document into groups: + +- `general`: names, description, scope disclaimer, attribution, references, + vertebral regions, annotation categories; +- `view:`: the view and the annotations located in it; +- `zone:`: the finding zone, its categories and nodes; +- removal groups: a `view:` or `zone:` group of the base absent from the + draft, whose content is « removed ». + +The equine draft has 30 groups (general, 2 views, 27 zones). Each group gets a +digest: the sha256 of the canonical JSON of its elements, statuses included, +with absent statuses written out; a removal group gets a digest of its +removal. + +Groups to cover (the one coverage rule): every group when the draft has no +base; for a derived version, every group whose digest differs from the base's +group of the same key, removal groups included. A group equal to its base +holds only elements the base's approved round covered. + +Acknowledgments (`anatomical_sheet_review_acknowledgments`, M5, append-only): + +- A reviewer outside the round's author set records « groupe lu » for one + group of an `open` round, against the verdict's digest of that group. A + group that still holds a `to_confirm` or `inherited` element cannot be + acknowledged: there is nothing to approve in it yet. +- An acknowledgment from an earlier round of the same draft carries to the + next round while the group's digest is unchanged and its reviewer is not an + author of the new round; the round screen shows it with its round and date. + SQL compares the stored digests; the worker needs no earlier data. +- Approval requires a current or carried acknowledgment of every group to + cover, each by a reviewer whose grant is active at that moment (§5.2). + +Progressive review. The reviewer reads groups and answers in comments; the +editor applies the answers, marks the read groups `reviewed` and resubmits; +the reviewer then acknowledges each finished group. Groups that do not change +afterwards keep their acknowledgments across rounds. The final approval is one +decision, resting on per-group acknowledgments that each carry a reviewer and a +time: no single action approves a whole structure unread. An anatomical +decision is applied by an editor only from a reviewer comment that names the +element; the reviewer's acknowledgment of the changed group is its validation. + +The change list (added, removed, changed and status-changed elements against +the base, a move appearing as removed plus added) is shown per group on the +review screen. It is a reading aid; coverage rests on the groups. + +Comments (`anatomical_sheet_review_comments`, M5, append-only): author, body +(at most 4 000 characters), optional group key, time. Element keys, when +needed, are written in the body. Editors, reviewers and publishers comment. + +Decision (O5 A): one decision, approve or request changes with a required +note, closes the round. The decision on the round, the acknowledgments per +reviewer and the audit keep enough trace for a future quorum, which would add +decision rows without changing the meaning of past rounds. 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. +revision, the historical sheet, an archived sheet and a draft that already +has a non-terminal round. -### 6.4 Server verdict and publication rules +### 6.4 Server verdict (O15 A) -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): +The verdict that approval and publication rely on is computed by the Rust +worker from data read on the server side. The browser is never a validation +authority: its validation panel is advisory, and no RPC accepts a verdict, a +fingerprint or a document hash from a page. -- 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. +Job. The round row is the job, with the avatar lease pattern of +`20261013100000_files_foundation.sql` (lease token, `locked_at`, fixed lease, +attempts below a limit), without backoff. Submission sets the round +`verifying`. Worker RPCs, service role only (M6): -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). +- `claim_sheet_verifications(limit)`: `for update skip locked` over rounds + `verifying` with no live lease; sets the token and `locked_at`, increments + `attempts`; returns round, version, sheet, revision and token. +- `get_sheet_verification_input(review_id, lease_token)`: the document at the + round's revision (frozen) and the base document, both as text; the drawings + the document references among the rows registered for the sheet (asset id, + sha256, byte size, object key). +- `complete_sheet_verification(review_id, lease_token, verdict)`: accepted + only while the round is `verifying`, the token is the live one, the verdict + names the round's sheet, version, revision and review, its group keys equal + `general`, the document's view and zone ids and the base's removed ones, and + its drawings equal the document's asset ids with the rows' sha256; anything + else answers `stale` or `malformed` and writes nothing. Moves the round to + `open` or to `verification_failed` (§6.5) and audits. +- `fail_sheet_verification(review_id, lease_token, code)`: a technical + failure; the round stays claimable until the attempt limit, then becomes + `verification_failed` with outcome `unavailable`. -Blocking rules at publication: +Processing. Verification runs as its own mode of the worker image (`run +--jobs sheet-verify`), in its own container under the `worker` compose +profile, so a fault in it never stops avatar or purge processing. The keyed +parent downloads the drawings and passes the document texts and drawing bytes +unparsed to the keyless sandboxed child, the only process allowed to parse +untrusted bytes. The child runs the core's verdict function (V1-2.2) and +returns a JSON verdict. The spawner takes its limits per command: about +13 MiB of input (document, base, four drawings of 2 MiB) and a verdict output +cap sized on the at-caps fixture; the RPC body cap of this mode is raised to +match. Memory and CPU limits and a wall-clock watchdog bound the child; the +seccomp profile is derived again for the new code path. -| Code (proposal) | Rule | Source | +Verdict content, bound to the round: `sheet_id`, `version_id`, `revision`, +`review_id`; the fingerprint `sha256-rfc8785-validated-v1` of the validated +document (absent when the document has an error); each reachable drawing +checked (asset id, sha256, byte size, result); issues (code, severity, path); +caps; completeness counts (statuses, vet referrals, uncited elements); the +groups and their digests; the change list; `verified_with` (core version). + +Core changes. A release that changes the SVG reader, the integrity rules, the +caps or the fingerprint ships a migration that withdraws every round in +`verifying`, `open` or `approved`, with the reason recorded; editors submit +again and the new worker verifies. The release replay (§15) runs before such a +release. + +Availability. Reviews and publications need a running, health-checked +verification worker on the stack where they happen. Without one, authoring +continues, submissions stay `verifying`, nothing is approved or published +(fail-closed), and the editor can withdraw at any time. The worker code +authorises nothing on DEV: starting it there is an operating checkpoint of its +own (§16.11), because a started DEV worker also processes the avatar upload +waiting since the V1-1 acceptance (AVATAR-01) and the due rows of the purge +queue. + +Rejected: a verdict computed in browsers (contrary to the owner's rule), a +synchronous HTTP verification service (a public endpoint holding the service +key, a sandbox to rebuild; not in the MVP), an operator command-line +verifier. + +### 6.5 Verdict failures (O23) + +Fail-closed: no round is approved and no version published while its verdict +is missing, failed, stale or in error. Two outcomes close a verification that +did not pass; the closed codes keep the categories apart. + +| Category | Example | Outcome | Retry | Exit | +|---|---|---|---|---| +| Business validation | integrity error, caps exceeded, annotation without geometry | `verification_failed`, outcome `failed`, codes `verification.validation.*` and the issues | no | fix the draft, submit again | +| Integrity | strict parse refused, drawing missing, size or sha256 mismatch, SVG refused or needing a removal, `object_conflict` | `verification_failed`, outcome `failed`, codes `verification.integrity.*` | no | fix or upload again; `object_conflict` follows §9.3 | +| Transient worker error | database or Storage unreachable, worker restart | stays `verifying`, code recorded | yes, up to the limit | automatic | +| Timeout or resource limit | child over its wall-clock or memory limit | stays `verifying`, code recorded | yes, up to the limit | reduce the document or the drawing if it repeats | +| Interruption | worker crash, lease expired | claimable again; counts as an attempt | yes, up to the limit | automatic | +| Stale result | completion with an old token, after a withdrawal, or naming another revision | nothing written, logged | no | none needed | +| Definitive failure | attempt limit reached (five, proposal, tuned in V1-2.3) | `verification_failed`, outcome `unavailable`, last code | no | submit again later | +| Core change | release that changes rules or reader | rounds withdrawn by the release migration | no | submit again | + +- Withdrawal is always available: the submitter or any editor withdraws a + round in `verifying`, `open` or `approved`, with a note; the draft + unfreezes. No round stays frozen without an exit. +- The round screen shows « vérification en attente depuis N min » with the + attempts and the last code. +- Every code maps to an FR and an EN message from a closed list; no stack + trace, internal path or database error reaches a page. +- Audit: submitted, verification passed or failed (outcome, codes), attempt + failed, withdrawn, decided, published. +- No partial publication: §6.8 is one transaction. + +### 6.6 Element statuses, keys and coverage (O3 B, O7 A) + +Three distinct notions (O7): + +- the draft's state: draft, revision, frozen or not by a round; +- the review marking of an element, a statement made by an editor: + `to_confirm`, `reviewed` or `inherited`; +- the business approval of the version: a reviewer outside the author set + approves a round after acknowledging its groups. + +A marking validates nothing by itself. An author who sets `reviewed` on an +element makes a statement that only an acknowledgment and an approval can +cover. + +Meanings: + +- `to_confirm` (« À confirmer »): a doubt, or content created and not yet + read. Every element created in the editor starts there. +- `inherited` (« Hérité, non relu »): carried over from the historical + import, never reviewed; an omitted status means `inherited`. No editor path + assigns it. It is never acknowledgeable, approvable or publishable, whatever + the base (C2). +- `reviewed` (« Relu »): marked by an editor; it counts only when covered. + +Keys: + +| Element | Key | Stable under | |---|---|---| -| `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 | +| Annotation | its id, unique in the document | label changes, geometry changes, moves between views | +| Finding zone | its id | label changes | +| Finding category or node | path key `//…` | label changes and reordering among siblings | +| View, reference, annotation category | id | label changes | +| Vertebral region | code | label and count changes | -Shown, never blocking: `inherited` elements kept from the base, uncited -elements, the two warning codes, the number of vet referral nodes. +Ids are generated by the page (§8.1), never derived from labels, never edited, +never reused. -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. +Rules of the core's edit commands: -### 6.5 Review statuses of elements (D2) +| Change | Key | Status | +|---|---|---| +| Create | new | `to_confirm` | +| Edit content: labels FR or EN, description, vet referral flag, cited references, geometry, laterality, view, annotation category, finding zone, region | same | `to_confirm` | +| Rename (labels only) | same | `to_confirm` | +| Reorder among siblings | same | unchanged; the group digest changes | +| Replace a view's drawing or crop | same | `to_confirm` for every annotation of that view | +| Edit a shared element (sheet texts, reference, region, annotation category) | same | unchanged; the `general` group digest changes | +| Status change | same | any element to `to_confirm`; `to_confirm` or `inherited` to `reviewed` only through « Marquer comme relu » on one element, one category or one finding zone, never the whole sheet; never to `inherited` | +| Delete | gone, with descendants | listed as removed; a removed zone or view becomes a removal group when a base exists | -- 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. +Moving a node to another parent is not offered in level 1 (§8.3): an editor +deletes and re-creates it, with new keys and `to_confirm` statuses. Comments +that named the old keys keep them in their body. + +Base and coverage: + +- The base is the version of §6.2 or none. The historical import is never a + base: a first publication rests on a real review of every element (C1). +- Coverage: every group to cover (§6.3) is acknowledged, and no element is + `to_confirm` or `inherited`. An element validated in an earlier published + version and left untouched keeps its validation through the base's approved + round, because its group's digest is unchanged; any change, move or status + change in the group re-opens it. +- The edit commands apply the status rules for the editor; the server does + not trust them. A page that saves a modified element still marked + `reviewed` changes its group's digest, so the group must be acknowledged + again; an `inherited` element anywhere blocks approval and publication. +- A version derived from a base copies its statuses; the base was published + through a V1-2 round, so it holds neither `to_confirm` nor `inherited`. + +### 6.7 Submission, approval and publication rules (C7) + +Four stages, each a superset of the previous: + +1. Structurally valid, that is submittable: the verdict passes the + submission rules below. Elements may still be `to_confirm` or `inherited`. +2. Approvable: structurally valid, publishable content, groups covered. +3. Approved: a reviewer outside the author set decided so. +4. Publishable: approved, with every binding still intact. + +| Rule | Submit | Approve | Publish | Code | +|---|---|---|---|---| +| Strict parse and the 19 error codes | yes | | | `verification.validation.*` | +| Caps of §1, all of them | yes | | | `verification.validation.caps` | +| Every annotation has a geometry | yes | | | `verification.validation.no_geometry` | +| Every reachable drawing present, size and sha256 equal to its row, read without removal | yes | | | `verification.integrity.*` | +| Fingerprint computed | yes | | | `verification.integrity.fingerprint` | +| Verdict passed, on the current revision | | yes | yes | `verdict.missing`, `verdict.failed`, `verdict.stale` | +| No `to_confirm` element (D2) | | yes | yes | `publish.to_confirm.open` | +| No `inherited` element, an omitted status counting as `inherited` (O3 B) | | yes | yes | `publish.inherited.present` | +| Scope disclaimer present in FR and EN, non-blank after trimming (O6) | | yes | yes | `publish.disclaimer.missing` | +| Every group to cover acknowledged by a reviewer outside the author set with an active grant | | yes | yes | `review.groups.uncovered` | +| Approver outside the author set, grant active | | yes | yes | `review.separation`, `publish.approval.invalid` | +| An `approved` round on the version's current revision | | | yes | `publish.review.missing` | +| Each drawing's row sha256 equal to the verdict's | | | yes | `publish.drawing.changed` | +| Sheet active, official, other than the historical sheet | yes | yes | yes | `sheet.inactive`, `sheet.historical_read_only` | +| Species active and other than `other` | | | yes | `publish.species.inactive`, `publish.species.other` | +| Caller capability (E, V, P) and `aal2` | yes | yes | yes | `rights.capability`, `rights.mfa` | + +- The rules of the first five lines come from the stored verdict. SQL checks + relations, states, rights, separation, the verdict's structure (§6.4), and + the declared defensive check of statuses on the stored document (§12.2). +- Shown, never blocking: uncited elements, the two warning codes, the number + of vet referral nodes. - Approval never changes the document. +- Approval does not check the species: an approved round of an inactive + species waits for its activation (§7.2). -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) +### 6.8 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 +round; check every publication rule of §6.7; 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 +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). +`guard_sheet_version_update` is extended in two ways, for every role: + +- a draft becomes `published` only with a `published_review_id` naming an + `approved` round of the same version and revision whose verdict passed, so + no direct UPDATE, even with a privileged key, publishes outside the gate; +- the deprecation transition cannot change any column added by V1-2 + (fingerprint, review link, revision, authors, base, working-copy + provenance). A wrong published version is repaired only by deprecating it and publishing a corrected one. -### 6.7 Deprecation, archive, deletion, historical reads (D8) +### 6.9 Deprecation, archive, deletion, historical reads (O8 A) -- A version that was ever published is never modified or deleted: M4 extends - the delete guard to `deprecated` for every role (F13). +- A version that was ever published is never modified or deleted physically: + 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). + confirmation names it. When none remains, the confirmation says that the + sheet leaves the catalogue list; `current_version_id` becomes null and the + versions stay readable by id. +- Archiving an official sheet removes it from the catalogue list; its + published and deprecated versions stay readable by id under catalogue + access (§5.3). Historical reads never bypass §5.3. - 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). + reader can see » needs the bilan table of V1-3 and is reviewed there. --- @@ -402,33 +825,60 @@ as is; §10 adds a load path without it), `NewReportRoute.DEFAULT_SPECIES_ID = curation pipeline (an equine tool), and the archive caps (4 drawings), which bind every species. -### 7.2 Species rows +### 7.2 Species rows (O9 C) -- 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). +- `create_species(id, name_fr, name_en, sort_order)`: sheet editor with + `aal2`, audited. Inserts the row with `active = false`. The id follows the + existing CHECK and is never renamed; an existing id gets one answer. +- `update_inactive_species(id, name_fr, name_en, sort_order)`: sheet editor + with `aal2`, inactive rows only, audited. +- `activate_species(id)`: platform owner with `aal2`, audited; the only way a + species becomes active. +- `rename_species(id, name_fr, name_en)`: platform owner with `aal2`, audited; + corrects an active species' names, never its id. +- No deactivation and no deletion in V1-2: an unused inactive species stays + invisible. +- The animal forms do not change. The policy `species_select_active` is not + widened, so `fetchSpeciesLabels`, `create_animal` and `update_animal` keep + seeing active species only, for every account, editors included. The admin + space lists species through `list_catalog_species()` (E, V, P, O, `aal2`), + which returns active and inactive rows with their state. Widening the + policy instead would show inactive species in an editor's own animal forms. +- Creating an official sheet accepts an active or an inactive species, never + `other`, and never activates a species. Publication refuses an inactive + species and `other` (§6.7). +- A species row holds an id, two names and an order. No vertebral formula, + zone, finding or drawing is generated for it. -### 7.3 Starting a sheet +Amendment of V1-1 N1 and §5.4 (ratified with O9, 2026-10-28): « The list of +species is no longer fixed by migration. A species is added by an audited RPC: +created inactive by a habilitated sheet editor, activated by the platform +owner. Its id never changes; an inactive species is invisible in the animal +forms; `other` stays refused for anatomical sheets. » The V1-1 contract +carries a pointer to this amendment; the table comment « no API write path » +changes with M5. -- 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). +### 7.3 Several official sheets per species (O10 A) + +Allowed. Each sheet has its own id, slug (unique among official sheets, which +share the null creator of the existing unique index), versions, rounds and +completeness. The catalogue lists every sheet with a published version under +its species, with its FR and EN names and description. Which sheet a bilan +uses, and whether a species gets a default sheet, is decided with V1-3. + +### 7.4 Starting a sheet + +- From the empty document of the core (`create_empty_sheet_document`): + species, FR and EN names, slug; everything else is entered in the editor. +- The copy of a finding catalogue from another sheet is deferred (O11), so no + finding of one species is ever reused automatically for another. The + working copy of the historical equine sheet (§14.3) is a distinct operation, + restricted to that sheet. - 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 +### 7.5 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. @@ -441,28 +891,27 @@ supplied; they are not invented. ### 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. +- The page holds the draft document as one JSON string, loaded in a + `PreviewSheet` handle (§10): drawings read once per sha256, the document + replaced and re-indexed after each change, `view.canvas` composing the view + on that handle as on `LoadedSheet`, and a draft with referential gaps still + drawn with its issues. +- Every change is a Rust core command (`sheet.edit`, V1-2.2): generic + primitives (insert, update, remove, reorder) over element keys, applying the + status rules of §6.6 and 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). +- Undo and redo: a stack bounded by size (8 MiB of document strings). +- Saving, leave guard, local recovery and conflicts: §6.2. - 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. + with FR and EN messages per code, a link to the element, the statuses per + group, and the serialised size against the 2 MiB server cap. ### 8.2 Level 1, in the MVP @@ -475,43 +924,53 @@ An editor can, from the application only: - 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; + the parent entered as numeric `view_box` values over the parent's preview), + rename, delete; +- upload and clean 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; + - place a point by clicking, set its radius in a field; + - draw a zone as a polygon by successive clicks, close it; correct, add or + remove vertices in the vertex list; - 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; + zone, vertebral region, colour and review marking; - 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; + references, set the review marking of one element or « Marquer comme relu » + on one category or one zone, reorder among siblings, 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. + report, submit, follow the round and its verification, 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. +can be replaced by a polygon), dragging vertices and drawing a crop rectangle +on the canvas, moving a finding node to another parent, 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 or on elements, 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 +### 8.4 What level 1 does not do, and narrow screens (O14 A) -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). +Level 1 never edits the drawing itself, accepts no raster image, draws no +curves and does not let two people edit one draft at the same time (one draft +per sheet, revision conflicts). + +| Surface | 1 024 px and wider | Narrower | +|---|---|---| +| Catalogue and sheet consultation (P1) | full | full, tested from 320 to 430 px | +| Preview (practitioner view, admin preview) | full | full, read-only canvas with zoom and pan | +| Draft editor, every tab, graphic and structured | full | read-only with a notice naming the 1 024 px minimum | +| Admin lists, overview, rights, species, review screen (read, comment, acknowledge, decide), publication confirmation, deprecation, archive | full | usable, tested at 375 px | --- @@ -520,70 +979,99 @@ editor shows the lists and the properties read-only with a notice (§17, O14). ### 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. + and a new object. A published version references its asset ids; an + asset-row trigger (M4) refuses any change of `sheet_id`, `sha256` and + `byte_size` and lets `uploaded_at` go only from null to a value, for every + role; no policy allows an UPDATE or DELETE of an object. - 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). + 2 MiB (M5). A sheet reaches at most 4 distinct drawings (§1). +- Row state stays the existing column: `uploaded_at` null means pending, set + means uploaded. No state column is added, so existing rows are not + rewritten. +- The application never creates signed URLs on this bucket; drawings are + downloaded under RLS (§9.4). - 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. + quarantine copy, no automatic replacement. Closed codes and the worker's + lease pattern are reused where they fit. -### 9.2 Preparing and uploading a drawing +### 9.2 Cleaning before upload (O19 A) -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. +The page reads the file with the core SVG reader before anything is stored. + +| Reader outcome | Treatment | +|---|---| +| Hard rejection (`too_large`, `doctype`, `malformed`, `not_svg`, `too_many_elements`, `too_deep`, `too_many_uses`, `too_complex`, `reference_cycle`) | refused, with the reason in FR or EN; no cleaning offered | +| Any removal of active or external content: `script`, `foreignObject`, event-handler attributes, `image`, animation elements, a reference that does not point inside the document (`href` or `url(…)` not starting with `#`), `@import` or `javascript:` values | refused (`svg_active_content`): such a file is hostile or incompatible; no cleaning offered | +| Any other removal (editor metadata and namespaces, `data-*` attributes, `