diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 1fcf7502..de7853a6 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -61,7 +61,15 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r - [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer - [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006 -- [ ] Step 4 — sheet model + importer (next, on validation; ∥ Step 3 per plan) +- [ ] Step 4 — canonical anatomical sheet model (2026-10-08, branch feature/step-04-anatomical-sheet-model). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md + - [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written + - [ ] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability + - [ ] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS + - [ ] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish + - [ ] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test + - [ ] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG + - [ ] 4.6 verify: pnpm check (typecheck, test:run, lint, build), db:reset + db:test on real stack, fresh verifier + security gate; capitalize BDR/LRN/EVAL +- [ ] Step 4b — legacy importer → official equine sheet as DRAFT (document.json + legacy-id-map + IMPORT-REPORT.md for business verification), publication after user validation --- diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md new file mode 100644 index 00000000..025a881b --- /dev/null +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -0,0 +1,270 @@ +# 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 | observation | 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`), which re-checks every error-level rule +except the two recursive ones (parent cycle, sibling uniqueness) and adds +"every `svg_asset_id` is an asset of this sheet". + +## 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) | +| `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 (`max + 1`) | +| `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'` | +| `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`); any other column change raises `42501`. A `deprecated` + row is frozen. +- **Deletion preconditions** (BEFORE DELETE): never a `published` row; never + the `current_version_id` of its sheet; never a version some sheet is + `based_on`; (reports: added when the table exists, §16). A `draft` has no + dependents and can be dropped by its editor. +- **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 the metadata +rows only. Deleting an asset referenced by a version is refused (FK restrict +is not possible on a JSONB reference, so the delete RPC checks every +version's views). + +### 3.1 Lifecycle (RPCs, security definer, audited) + +| RPC | Actor | Effect | +|---|---|---| +| `create_anatomical_sheet(species_id, name, slug, description, visibility, official, document)` | any active user; `official = true` needs platform admin | sheet + draft v1 | +| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, 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 any version has dependents | +| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | + +Direct table access for `authenticated`: SELECT through the policies below; +UPDATE of `content` / `change_note` on **own draft** rows (the future editor +autosaves with a PATCH); DELETE of own draft rows. Everything else is RPC. + +### 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` | none (RPC) | +| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` and DELETE on own drafts; INSERT via RPC | +| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | + +`anon` gets nothing. 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 editor, for a platform admin and for the owner 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. Decisions left to the user + +1. **Follow = permission to use a public sheet** (§2.9) is not yet modelled: + today every authenticated user can use any public active sheet. Grants + and follows will narrow `can_use_sheet` at the community step. +2. **Who may create sheets**: any active account for now. Should creation + wait for professional verification (Step 7)? +3. **Deprecation policy**: publishing v2 does not deprecate v1. Should it, + automatically, or stay a manual act? +4. **Table name `anatomical_sheet_assets` and the content-addressed Storage + layout** (`.svg`): confirm before the importer writes files. +5. **Official equine sheet owner**: platform-owned (`creator_user_id = null`, + `is_official = true`, edited by platform admins) or owned by the client's + account? +6. **Finding category kind naming**: `observation` collides with the report + "Observation" (OPEN_QUESTIONS C7). Alternative: `consultation_reason`.