# Anatomical sheet model (Step 4) Status: Step 4 deliverable, 2026-10-08. Source of truth for the canonical "fiche anatomique": the JSON document, its validation rules, the PostgreSQL tables that persist it, and the lifecycle rules (versions, copies, deletion). Decisions it applies: business architecture §2.6–§2.9, §7, §16, §17.3, §23.2; `OPEN_QUESTIONS.md` C1, C2, C8, C9, Q3, Q5, Q9 as decided on 2026-10-08 (equine only, two SVG assets, import anomalies land in a draft, 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. ## 1. Two layers | Layer | Where | Role | | ------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | | 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 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. ## 2. Canonical document (schema_version 1) Every id is a **stable id**: `^[a-z0-9][a-z0-9_-]{0,63}$`, never derived from a label, never changed by a translation. Vertebral region codes are the one exception: `^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$`, because the practitioner reads them as-is (`C`, `T`, `L`, `S`, `Cd`). Labels are `LocalizedText` objects `{ fr, en }` (both required) or `LocalizedOptionalText` `{ fr?, en? }`. Adding a locale later means adding an optional key, not a new field family. ```text AnatomicalSheetDocument ├─ schema_version: 1 ├─ species_id: stable id (row of public.species) ├─ name: LocalizedText display name of the sheet ├─ description: LocalizedOptionalText ├─ scope_disclaimer: LocalizedOptionalText legal scope text shown once per session and in the PDF ├─ attribution: { authors: string[], license: string | null, notes: string | null } ├─ vertebral_config: { regions: VertebralRegion[] } ORDERED; codes free (C/T/L/S/Cd for the horse) │ VertebralRegion = { code, name: LocalizedText, count ≥ 1 } ├─ categories: AnnotationCategory[] { id, name: LocalizedText, color: '#rrggbb' | null } ├─ views: SheetView[] │ main: { id, kind: 'main', name, svg_asset_id: uuid | null, view_box: ViewBox | null } │ detail: { id, kind: 'detail', name, parent_view_id, svg_asset_id: uuid | null, view_box: ViewBox | null } │ ViewBox = { min_x, min_y, width > 0, height > 0 } ├─ annotations: Annotation[] │ common: { id, view_id, category_id, laterality, geometry: Geometry | null } │ point | zone: + { name: LocalizedText, finding_zone_id: id | null, vertebral_region_code: code | null } │ detail_trigger: + { name: LocalizedText | null, opens_view_id } │ laterality ∈ unpaired | bilateral | left | right │ Geometry = circle { cx, cy, r } | polygon { points: [x, y][] ≥ 3 } | path { d } └─ finding_zones: FindingZone[] FindingZone = { id, name: LocalizedText, categories: FindingCategory[] } FindingCategory = { id, kind: dysfunction | consultation_reason | anamnesis | custom, name, description?, children: FindingNode[] } FindingNode = { id, name, description?, requires_vet_referral?, sources?, children? } (recursive) SourceRef = { type: manual | journal | database | web, citation, url? } ``` Why these shapes: - **Views are a tree**, not a `details.head` field. A detail view names its parent; a `detail_trigger` annotation in the parent opens it. Nesting depth is free (§7.3). `svg_asset_id` is nullable on a detail view: null means "render the parent's asset with this `view_box`" (C9). The equine seed will keep two assets (Q5), so both forms are exercised. - **Laterality is explicit** on every annotation. `bilateral` = one drawing stands for both sides, the report picks the side (today's behaviour); `left` / `right` = the drawing shows one side; `unpaired` = no side. Absence of attribute no longer carries meaning. - **Spine regions are data.** `vertebral_config.regions` is an ordered list with free codes (C1, Q3). An annotation that opens the vertebra picker carries `vertebral_region_code`; no label parsing (`regionFromLabel` stays in the importer). - **Annotation → findings is one explicit field**, `finding_zone_id`. No FR/EN matching at runtime (§23.2). Several annotations may share a zone; a `detail_trigger` never has one (it is navigation, not an observation). - **Finding categories carry a `kind`** so the three business buckets (dysfonctions ostéopathiques, observations / motifs de consultation, anamnèse / facteurs rapportés) are typed, and creators may add `custom` ones (§7.4). Node ids are unique among siblings; a finding is referenced by `(finding_zone_id, path[])` exactly as `Finding.path` does today, so the Step 5 report adapter is a rename, not a re-keying. - **Tree nodes are lean on input, total on output**: `description`, `requires_vet_referral`, `sources`, `children` are optional in the JSON and defaulted by the parser (612 leaves would otherwise carry four empty keys each). Structural records (views, annotations) use explicit `null`. - The parser is **strict**: unknown keys are rejected. A canonical document must not silently carry fields no version of the schema defines. ### 2.1 Validation tiers | Tier | Function | When | | ---------- | ------------------------------------------ | ----------------------------------------------------------------------------- | | Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | | Integrity | `validateSheetDocument(doc): SheetIssue[]` | 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 path names the offending field (`annotations[0].category_id`), the later entry for a duplicate, the item itself for `view.unreachable` and `finding_zone.unreferenced`. Integrity rules (error unless stated): | Code | Rule | | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `view.main.count` | exactly one `main` view | | `view.id.duplicate` | view ids unique | | `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | | `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | | `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | | `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | | `annotation.view.missing` | `view_id` exists | | `annotation.category.missing` | `category_id` exists | | `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | | `annotation.finding_zone.missing` | `finding_zone_id` exists | | `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | | `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | | `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | | `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | | `finding_zone.unreferenced` (warning) | zone no annotation points to | A draft may be saved with errors. Publishing a document with errors is refused in TypeScript (`assertPublishable`) and in SQL: `private.sheet_document_issues` re-checks every error-level rule except the two recursive ones (parent cycle, sibling uniqueness) 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`. ## 3. Relational model ```text public.species reference data, seeded by the migration (equine) public.anatomical_sheets identity, owner, visibility, status, provenance, current version public.anatomical_sheet_versions numbered versions, status draft | published | deprecated, content jsonb public.anatomical_sheet_assets SVG files, content-addressed (sha256), per sheet audit.audit_logs every lifecycle event (private.log_event) ``` ### `species` `id text` (stable id), `name_fr`, `name_en`, `sort_order`, `active`. Read by any authenticated user; no write path through the API (platform step later). ### `anatomical_sheets` | Column | Notes | | ------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `id uuid` | | | `species_id` | FK species | | `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | | `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | | `is_official boolean` | only a platform admin can create one; editable by platform admins | | `visibility` | enum `sheet_visibility`: `private` \| `public` | | `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | | `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | | `current_version_id` | latest published version (nullable while draft-only) | | `last_version_number` | monotonic counter: a deleted version's number is never reused | | `archived_at`, `deleted_at`, `created_at`, `updated_at` | | ### `anatomical_sheet_versions` | Column | Notes | | ----------------------------------------------------------- | --------------------------------------------------------------------------- | | `id uuid`, `sheet_id` | | | `version_number int` | unique per sheet, assigned by the server from the sheet's monotonic counter | | `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | | `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | | `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB | | `change_note text` | what changed in this version | | `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | | `published_at`, `deprecated_at`, `created_at`, `updated_at` | | Rules enforced by triggers (every role, including the table owner): - **One draft per sheet** (partial unique index, C8). - **Published rows are immutable**: the only accepted UPDATE on a `published` row is the transition to `deprecated` (status, `deprecated_at`, `deprecated_by`); a change to any compared column (content, schema version, number, sheet, note, authorship, timestamps) raises `42501` for every role, table owner included. Through the API the row is simply invisible to UPDATE (zero rows touched). A `deprecated` row is frozen. - **Deletion preconditions** (BEFORE DELETE): never a `published` row; never the `current_version_id` of its sheet; never a version a non-deleted sheet is `based_on`; (reports: added when the table exists, §16). A `draft` has no dependents and is dropped by its editor through `delete_sheet_version`. - **Document ↔ row**: `content->>'species_id'` equals the sheet's species. ### `anatomical_sheet_assets` `id uuid`, `sheet_id`, `sha256 text` (64 hex), `byte_size int`, `content_type text` (`image/svg+xml` only for now), `file_name text`, `created_by`, `created_at`. Unique `(sheet_id, sha256)`. Assets are immutable and **content-addressed**: the bytes live in Storage under `anatomical-sheet-assets/.svg` (bucket and policies arrive with the importer step; until then the path is a convention, not a row). Two sheets with the same SVG share one object; a copy of a sheet copies only the metadata rows its copied version references. Deleting an asset referenced by a version is refused (FK restrict is not possible on a JSONB reference, so `delete_sheet_asset` checks every version's views). Asset rows follow the sheet's visibility, drafts included: the future Storage policy must authorise through the sheet, never through a sha256 alone. ### 3.1 Lifecycle (RPCs, security definer, audited) | RPC | Actor | Effect | | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `create_anatomical_sheet(species_id, name, slug, document, description, visibility, official)` | any active account; `official = true` needs platform admin | sheet + draft v1 | | `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft (next counter value), content copied from `from_version_id` (default: current version); refused if a draft exists | | `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | | `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | | `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | | `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | | `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | | `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while a non-deleted copy derives from the sheet | | `set_sheet_visibility(sheet_id, visibility)` | editor | private ↔ public, audited (sharing is sensitive state) | | `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | | `delete_sheet_asset(asset_id)` | editor | refused while any version references the asset | Direct table access for `authenticated`: SELECT through the policies below; UPDATE of `name` / `slug` / `description` on own sheets and of `content` / `change_note` on **own draft** rows (the future editor autosaves with a PATCH; the autosave itself is not audited, the publication is). Everything else is RPC. Every RPC takes its actor from `auth.uid()`, refuses a deactivated profile, checks `can_edit_sheet` before reading anything else (unknown and foreign ids get the same `42501`), and calls `private.log_event`. ### 3.2 Access helpers (`private`, security definer) | Helper | True when | | ------------------------------- | --------------------------------------------------------------------------------------------------------- | | `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | | `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`), grants and follows plug in here at the community step | Policies: | Table | SELECT | INSERT / UPDATE / DELETE | | --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | | `species` | authenticated, `active` rows | none | | `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | UPDATE `name`, `slug`, `description` for editors; everything else RPC | | `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` on own drafts; INSERT and DELETE via RPC | | `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | `anon` gets nothing. Every `private` function has EXECUTE revoked from PUBLIC; `authenticated` executes only the policy predicates (the two above plus the five platform-role predicates of Step 3); pgTAP 001 keeps a census. Public discovery views for the public site come with the community step (§17.4). ## 4. What the model guarantees (acceptance criteria) | Criterion | Where it is proven | | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | A sheet with several views and annotations explicitly linked to findings | `packages/domain/tests/fixtures/horse-slice.ts` (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 | | 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 | | Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | | Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | | Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | | Previous tests pass | root `pnpm check` | ## 5. Business decisions (user, 2026-10-09) The open points of Step 4 were decided as follows. Each line names where the decision lands; only the naming one is implemented in this document. | # | Decision | Where it lands | | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | Public sheets are readable according to their visibility, but **using** a community sheet for a report requires following its author. Official Faunosteo sheets need no follow. | `can_use_sheet` gains the follow predicate at the community step; official sheets (`is_official`) bypass it. Until then every active account may use any public sheet. | | 2 | Any account may prepare private drafts; **community publication** is reserved to authorised, verified accounts. Student and professor roles keep their own rules. | `publish_sheet_version` + `set_sheet_visibility('public')` gain a verification check at the identity / verification step. | | 3 | A new publication becomes the current version; older versions are **not deprecated automatically** and stay readable under the access rules. | Already the behaviour of `publish_sheet_version`; deprecation stays a manual act. | | 4 | Official sheets are **platform-owned**, administered by authorised accounts. | Already the model: `creator_user_id = null`, `is_official = true`, platform admins edit. | | 5 | Name anatomical findings apart from the observations typed during a report. | Finding category kind `observation` renamed **`consultation_reason`** (`dysfunction` / `consultation_reason` / `anamnesis` / `custom`). The report-side object keeps the name Observation. | | 6 | Server-side validation and integrity for every publication; the frontend is never a security boundary. | SQL already re-checks references, sizes and species. The full shape check (Zod) moves server-side before community publication: plpgsql shape rules or an Edge Function gate, decided at the community step. | | 7 | Account deletion handles dependencies and transfers explicitly (RGPD); no dependency may block the erasure of personal data forever. | Retention step (§16): published versions get their `created_by` / `published_by` anonymised through a dedicated system path (the immutability guard will allow that single transition), personal sheets are transferred or archived, `creator_user_id` keeps `on delete restrict` only as the backstop that forces the explicit path. | ## 6. Official equine sheet: import (Step 4b) `packages/anatomy` holds a one-off, deterministic importer (`pnpm import:equine`) that reads `Horse.svg`, `Horse_head.svg` and `pathologies.json` and writes `supabase/seed/anatomical-sheets/equine/v1/`: the canonical `document.json`, `legacy-id-map.json` (every legacy `data-anno-id`, category slug and view key → new id), `assets.json` and the byte-identical SVG copies, `IMPORT-REPORT.md` (French, for the osteopath: volumes in / out, every mapping, every anomaly to validate) and `equine_v1.sql`, the idempotent seed that creates the platform-owned sheet `faunosteo-cheval` (private, official) with its two asset rows and draft v1. Rules of the import: - ids are explicit and stable: annotation id = catalog zone key when FR and EN names match exactly (26 / 26), finding zone id = catalog key, views `main` and `head`, trigger `head-trigger`; nothing matches by label at runtime; - no medical correction: catalog ids and labels are kept verbatim (`ssb-dysfunctions` under `sphenoid` included) and every doubt is an entry of the report; only technical slugs (degraded category ids) are normalised, and the report says so; - no publication: the seed inserts a draft through `private.insert_sheet_draft` (audited with a null actor) and never calls `publish_sheet_version`; only a platform admin can publish it, after the business review of the report (pgTAP 007 pins both); - the source files under `apps/app/public/species/equine/` stay untouched and keep serving the current application. Storage: bucket `anatomical-sheet-assets` (private, SVG only, 20 MiB cap), objects `.svg`, read policy `anatomical_sheet_assets_read` through `private.can_read_sheet_asset_object`: the asset row must be **confirmed** (`uploaded_at`, set only by `confirm_sheet_asset_upload` with the service role once the bytes are in the bucket) and either edited by the caller or referenced by a non-draft version of a usable sheet. A hash a user registers on their own sheet therefore opens nothing. No API writes (operator upload, `SUPABASE.md` §3.1).