Files
faunosteo/CLAUDE.md
T

597 lines
44 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Faunosteo — CLAUDE.md
# Generated by scaffolder 2026-05-18. Single source of truth for Claude in this repo.
# Global rules: ~/.claude/CLAUDE.md — this file extends or overrides them.
---
## Project overview
**Faunosteo** is the official, final product name (the SaaS, the application, the public site and its services); official domain **https://faunosteo.com** (production, separate VPS, the site present there is preserved until an explicit migration decision). Never propose another brand name; keep the logo, palette and validated mockups. Environments DEV / STAGING (`staging.faunosteo.com`, planned, not created) / PROD are isolated (`docs/development/ENVIRONMENTS.md`).
Single-praticien French web app for veterinary osteopathy bilans on animal anatomy SVGs.
Practitioner clicks anatomical zones, builds observations with pathologies/severity,
writes conclusion, and exports an A4 PDF. PDF carries the full JSON state as a native
attachment so importing it restores the session for a follow-up.
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`,
tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved the
application onto that model: the editor renders the bundled reference sheet (the
curated equine DRAFT, `SHEET_BUNDLE=draft`), writes Report v3 and imports v2 PDFs
through a generated migration map. Step 6 made the PDF an autonomous archive: the
`packages/pdf` engine renders from explicit inputs (report, sheet snapshot, branding,
labels, rasterizer) with no network and no DOM, and the attachment is an envelope v1
carrying the report, a lean sheet snapshot, the branding and the labels used, so an old
bilan is reproduced identically after any catalog, wording or logo change
(`docs/PDF-FORMAT.md`). Step 7 added identity: email/password sign-up with
confirmation, password recovery, OAuth buttons driven by config, the guarded
`/app` shell (dashboard, Mon compte with personal / professional / preferences /
security sections) on Supabase Auth + `profiles` + `profile_roles`, language
synced with `profiles.locale` (`docs/development/IDENTITY.md`). The local tool
routes stay unauthenticated. Step 8 (= Rust R1) added the files foundation: the
`assets` table as the authority over user files, seven private buckets (only
`avatars` open, through policies evaluated on `assets`), a quarantine upload path,
the Rust worker `crates/worker` (keyed job loop + keyless sandboxed decode child)
producing 512 × 512 WebP avatars, a deferred purge queue, and the profile photo in
Mon compte, the sidebar, the drawer and the top bar (`docs/development/STORAGE.md`).
Rust R2 moved the application's domain rules into `crates/core` (sheet, report and
archive contracts, integrity rules, sheet index, migration, rebase, snapshot, layered
archive reading, editor reducers, findings and vertebra rules, report operations),
reached through the wasm facade and `packages/core-wasm`, loaded lazily by the sheet
pages only (`docs/development/RUST.md` §8); `packages/domain` is frozen for the PDF
engine, the pipeline and the compare CLI.
MVP species: equine only. Open-source MIT.
---
## Stack
| Concern | Choice | Version |
|---|---|---|
| Runtime | Node.js | 24 LTS (`.nvmrc`, `engines` >=22.12 <25) |
| Package manager | pnpm | 10.13.1 (`packageManager`, root devDependency) |
| Build | Vite + @vitejs/plugin-react-swc | 7.x |
| UI | React | 19 |
| Language | TypeScript strict | 5.x |
| Styling | Tailwind CSS v4 CSS-first (no postcss config) | 4.x |
| State | Zustand | 5 |
| Validation | Zod | 3 |
| PDF | pdf-lib | 1.17 |
| SVG raster | native Image/canvas (no dependency) | — |
| Animation | motion | 11 |
| Tests | vitest + happy-dom + @testing-library/react | 3.x |
| Backend | Supabase (PostgreSQL 17, GoTrue, PostgREST) — CLI pinned as root devDependency | CLI 2.120 |
| DB client | @supabase/supabase-js (packages/supabase) | 2.x |
| SQL tests | pgTAP under supabase/tests, run by `supabase test db` and by PGlite (Dockerless) | PGlite 0.3 |
| Deploy | Docker multi-stage → nginx:alpine | — |
| Rust (core, wasm facade, worker) | Rust pinned by `rust-toolchain.toml`, edition 2024; native user-level rustup on the Ubuntu development machine (`pnpm rust:check`, `pnpm wasm:build`, plain `cargo`), the builder image `docker/rust-builder.Dockerfile` as the reproducible alternative (`:docker` scripts), never on the VPS | 1.99.0 |
| WASM glue | wasm-bindgen crate = CLI version (locked in `scripts/wasm-build.sh`), `ts-rs` types committed under `packages/core-wasm/types` | 0.2.129 / 12 |
| Worker image | `crates/worker/Dockerfile`: `rust:1.99.0-alpine3.24` (musl, libwebp via `cc`) → `distroless/static:nonroot`; sandbox tests + seccomp derivation in the `test` stage | — |
---
## Build commands
pnpm workspace: `apps/app` = the private application, `packages/domain` = pure
Zod domain model (anatomical sheet document), `packages/supabase` = Supabase
access layer (see `docs/development/WORKSPACE.md`). Every command
below runs from the repository root and delegates to the packages.
```bash
# Development (DEV origin = this machine's LAN address, scripts/dev-env.sh; tests run from other devices)
pnpm dev # Vite on http://<FAUNOSTEO_DEV_HOST>:5173 wired to the local stack (needs pnpm db:start)
pnpm dev:offline # the local tool without backend
pnpm dev:gateway # Mailpit behind basic auth on FAUNOSTEO_DEV_HOST:54325; dev:gateway:stop
pnpm dev:net-check # allowed / refused probes from a distinct Docker network
# Production build (typecheck + vite build)
pnpm build
# Type-check only (no emit)
pnpm typecheck
# Preview production build
pnpm preview
# Tests (watch)
pnpm test
# Tests (CI / single run)
pnpm test:run
# Lint (0 warnings allowed)
pnpm lint
# Format
pnpm format
# Supabase local stack (Docker) — docs/development/SUPABASE.md; every CLI call goes through
# scripts/supabase.sh (exports the DEV origin that config.toml reads with env()); `pnpm supabase <args>`
pnpm db:start # start stack, apply migrations + seed; FAUNOSTEO_DEV_HOST=<ip> to pick another address
pnpm db:reset # replay from zero
pnpm db:test # pgTAP on the real stack
pnpm db:types # regenerate packages/supabase/src/database.types.ts
pnpm db:types:check # CI diff
# Reference sheet in the app: the dev server bundles the curated draft; a build does not
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
pnpm preview:draft # same, then serves it
pnpm import:equine # regenerate legacy-import/ and draft/ (document, migration map, review drawings)
pnpm report:compare <pdf|dir>... # archive check: attachment vs its v3 reading, unresolved items flagged (docs/PDF-FORMAT.md)
# Rust (docs/development/RUST.md) — native toolchain (user-level rustup, channel of rust-toolchain.toml) first
pnpm rust:check # scripts/rust-check.sh: fmt --check, clippy -D warnings, cargo test (core, wasm, worker unit), ts-rs export, cargo deny
pnpm wasm:build # scripts/wasm-build.sh: crates/wasm → packages/core-wasm/pkg (git-ignored); then the core-wasm vitest proofs run
pnpm check:all # scripts/check-all.sh: the whole pre-merge gate (rust:check, types drift, wasm:build, check, app image, worker:test, worker:image)
pnpm rust:builder # build docker/rust-builder.Dockerfile once (faunosteo_rust_builder:1.99.0), the reproducible alternative
pnpm rust:check:docker # the same rust-check.sh inside the builder image
pnpm wasm:build:docker # the same wasm-build.sh inside the builder image
pnpm worker:test # Docker only: crates/worker/Dockerfile stage test, sandbox tests + seccomp derivation on the musl binary
pnpm worker:image # Docker only: runtime image faunosteo_worker:dev (distroless/static, `run --check`)
pnpm e2e:avatar # scripts/avatar-e2e.sh: worker container against the local stack + packages/supabase/tests/e2e (real-stack avatar flow)
```
## Docker commands
```bash
# Build image
docker build -t faunosteo .
# Build an image that embeds the reference DRAFT sheet (preview only, never the default)
docker build --build-arg SHEET_BUNDLE=draft -t faunosteo .
# Run with compose (reads .env for APP_* vars)
docker compose up --build
# Stop
docker compose down
```
Naming convention: every Docker resource Faunosteo owns is prefixed `faunosteo_`
when the name is configurable (container `faunosteo_app`, Compose project
`faunosteo`); the Supabase CLI imposes `supabase_<service>_faunosteo`, documented
as a limit in DEPLOY.md "Docker resource naming". Never rename a resource that
holds data without keeping its volume.
Note: no global pnpm needed. `corepack enable` once (reads `packageManager`),
or call `corepack pnpm <cmd>`. Root scripts resolve `node_modules/.bin/pnpm`.
---
## Test commands
```bash
pnpm test:run # vitest run — all tests, single pass, CI-safe
pnpm test # vitest watch — dev loop
```
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. The 612 legacy catalog leaves run through the v2 → v3 migration
in both `packages/anatomy` (against the draft document) and the app (sheet index + PDF roundtrip). Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Suites run on the bundled reference sheet (`tests/helpers/sheet.ts`); frozen v2 fixtures under `tests/fixtures/`.
SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts`
on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack.
---
## Lint / format commands
```bash
pnpm lint # ESLint 9 flat config — max-warnings 0
pnpm format # Prettier write
```
---
## Folder structure
```
faunosteo/
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset)
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
├─ src/
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
│ │ ├─ routes/auth/{Login,Signup,ForgotPassword,ResetPassword,AuthCallback}Route.tsx
│ │ ├─ routes/app/{Dashboard,Account}Route.tsx ← behind RequireAuth, inside AppLayout
│ │ ├─ guards/{RequireAuth,RedirectIfSignedIn,SessionLoading}.tsx
│ │ └─ providers/{ConfigProvider,AuthProvider}.tsx ← AppConfig context; session + locale sync start
│ ├─ auth/{validation,redirects,useAuthFailureMessage}.ts ← Zod schemas (i18n keys), safe next path, failure phrasing
│ ├─ account/{validation,useProfileForm}.ts ← account section schemas + one-save form hook
│ ├─ config/env.ts ← runtime config resolution
│ ├─ sheets/{provider,useSheet}.ts ← raw bundled payload; useSheet loads it into the core (ready / none / core_unavailable / invalid_sheet + retry), useSheetAvailability without the core
│ ├─ core/{runtime,sheetOps,reportOps}.ts ← the page's CoreRuntime (Vite asset URLs, lazy), typed sheet-bound and free core operations
│ ├─ services/
│ │ ├─ sheetIndex.ts ← SheetIndex class: reads the core's SheetIndexData (ids, never labels) + `ops`
│ │ └─ localeSync.ts ← profiles.locale ↔ localeStore (account wins on sign-in)
│ ├─ i18n/
│ │ ├─ types.ts ← Locale type + Dict type
│ │ ├─ fr.ts + en.ts ← translation dicts (flat key → string)
│ │ ├─ index.ts ← getDict(locale)
│ │ └─ useT.ts ← useT() hook (reads localeStore)
│ ├─ state/
│ │ ├─ authStore.ts ← session, user, profile, roles, recovery flag (onAuthStateChange)
│ │ ├─ reportStore.ts ← Zustand store (Report v3, core-built reports, actions answer { ok }) + persistence.ts (raw texts, quarantine keys)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
│ ├─ components/
│ │ ├─ ui/{Button,ButtonLink,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Icon,FormField,Notice}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel}.tsx
│ │ ├─ brand/{Brand,AppHeader,Footer,LanguageSwitcher,HomeSpaceLink}.tsx
│ │ ├─ auth/{AuthLayout,OAuthButtons,PasswordField,UnavailableNotice,AuthLink}.tsx
│ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx
│ │ └─ account/{SectionCard,SaveRow,AvatarSection,PersonalInfoForm,ProfessionalInfoForm,PreferencesForm,SecurityPanel,RoleBadges}.tsx
│ ├─ account/avatarTransport.ts ← magic-byte sniff (never SVG), createImageBitmap → canvas ≤ 1024 px → JPEG transport blob
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
│ └─ main.tsx
├─ tests/
│ ├─ setup.ts
│ └─ unit/*.test.ts
├─ docker/
│ ├─ entrypoint.sh ← injects env.js at container start
│ └─ nginx.conf ← SPA fallback + PORT envsubst
├─ docs/
│ ├─ ANNOTATION-RENDERING.md ← annotation layer contract (attributes, styles, colours)
│ ├─ PDF-FORMAT.md
│ ├─ design/ ← VALIDATED graphic references (README.md + faunosteo-etape7-maquettes-validees.png); follow before proposing UI
│ ├─ faunosteo-audit/ ← audit of the current system (frozen at 83e40af)
│ ├─ development/ ← SaaS implementation plan, WORKSPACE.md
│ └─ history/superpowers/{specs,plans}/ ← 2026-05 design records (docs/superpowers is purged by gitflow finish)
├─ eslint.config.js, index.html, package.json (@faunosteo/app)
├─ tsconfig*.json, vite.config.ts, vitest.config.ts
│ (end of apps/app)
├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only): anatomical-sheet (document, integrity rules, sheet-index), report (v3, v2 migration, rebase), archive (sheet snapshot, envelope v1, branding, labels, layered reader)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, pure annotation-layer renderer + view composer (`./render`)
├─ packages/pdf/ ← @faunosteo/pdf: browser-free PDF engine — src/{export,read,text,branding}.ts, attachment/, svg/{parse,sanitize,view}.ts, render/, i18n/; tests reproduce the Step 6 goldens
│ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts
│ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft
│ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts
├─ packages/supabase/ ← @faunosteo/supabase
│ ├─ src/{index,client,database.types,anatomical-sheets,assets}.ts ← typed client, generated types, publish gate, avatar flow (closed AssetFailure kinds)
│ ├─ tests/e2e/avatar-flow.e2e.ts + vitest.e2e.config.ts ← real-stack end-to-end (`pnpm e2e:avatar`), skipped without the stack env
│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test
├─ supabase/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs)
│ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
│ │ ├─ curation/{changes,references}.json ← AUTHORED changeset + references registry (never generated)
│ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, sheet-ref, report-migration-map, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ packages/core-wasm/ ← @faunosteo/core-wasm: CoreRuntime (lazy, poison, recovery) + Node source, pkg/ shipped and pkg-proofs/ (built, git-ignored, BUILD_STAMP), ts-rs types (committed), frozen N-1 reader (tests/n-1), tests
├─ crates/ ← Rust workspace (Cargo.toml, rust-toolchain.toml, deny.toml, clippy.toml, .cargo/config.toml at the root)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing); tests/{oracles,conformance,fixtures} frozen from the TypeScript; no I/O, no clock (lint-enforced)
│ ├─ wasm/ ← faunosteo-wasm: wasm-bindgen facade (core_version, call, SheetHandle; trap exports in the proofs build only)
│ └─ worker/ ← faunosteo-worker: plain main; `decode` sandboxed child (rlimits, seccomp allowlist, image → libwebp), parent Spawner + RIFF check; R1 `run` loop: config, log (JSON lines, allowlist), keys, backend trait + http (ureq, PostgREST rpc + Storage objects), job, sweep, watchdog; Dockerfile, scripts/derive-seccomp.sh
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e}.sh, wasm-stamp.mjs ← native Rust gate, wasm build (pkg + pkg-proofs + stamp), the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e
├─ scripts/{dev-env,supabase,dev}.sh ← the DEV origin (LAN address) in one place; CLI wrapper; `pnpm dev` on that origin
├─ docker-compose.yml ← `app` service; `worker` service under the `worker` profile (read-only, cap_drop ALL, external Supabase network, `.env.worker`)
├─ docker/rust-builder.Dockerfile, rust-run.sh, csp-proof/ ← reproducible Rust builder (alternative) + the CSP proofs (R0 module, R2 app image: app-image.sh)
├─ .gitea/workflows/ci.yml ← PREPARED, never executed (no runner): rust job (builder image, scripts/rust-check.sh, types drift, wasm), install, typecheck, test, lint, build, docker (app + worker test stage + runtime)
├─ .gitea/workflows/{rust-advisories,release-images}.yml ← nightly RustSec advisories; manual digest-tagged image publication (no deploy)
├─ .claude/{tasks/TODO.md,memory/,audits/}
├─ Dockerfile, docker-compose.yml, docker/
├─ .env.example, .editorconfig, .nvmrc, .node-version, .npmrc, .prettierrc.json
├─ package.json (workspace root), pnpm-workspace.yaml, pnpm-lock.yaml
├─ CLAUDE.md, README.md, DEPLOY.md, CHANGELOG.md, LICENSE
```
---
## Architecture
```
User interaction
→ React routes (BrowserRouter)
→ Zustand store (reportStore)
→ Components read store via selectors (no prop drilling)
Sheet loading (Rust core, RUST.md §8)
→ useSheet(speciesId) → SheetProvider (bundled: virtual:faunosteo-sheet, SHEET_BUNDLE=draft) → raw payload
→ coreRuntime().ready() (lazy; core_unavailable + retry on failure) → SheetHandle(payload): strict parse of the
document and migration map, index → index_data → SheetIndex (tables only) + ops (sheet-bound core calls)
SVG interaction
→ AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document; TS until R3)
→ delegated click on [data-anno-id] → sheet.ops.zoneClick(observation, id) (one core call: decision + new observation)
→ open_view → DetailModal (same drawing, view_box crop, or the view's own asset)
→ open_vertebra_picker (initial selection from the core) / open_laterality_picker (sides present) → pickers
→ vertebra.select per tap, vertebra.sync / zone.add_sides on confirm → updateObservation() in store
→ toggle / remove_both_sides → the core's observation → updateObservation(); findings picker → finding.toggle
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportReportToPdf(report, index, { locale })
→ index.ops.snapshot(report) (core: archive.snapshot) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
→ { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF import
→ readAttachment(bytes) → engine byte scan for the EmbeddedFile stream (TS until R4; no pdf-lib parse on untrusted
bytes, BLK-009): named osteo-report* first, capped native inflation, JSON depth pre-scan
→ loadSheetIndex (core loads here) → importAttachment(data, index) → core archive.import: layered reading (report:
v3 as is, v2 migrated, else incompatible_version; envelope metadata tolerant, snapshot/branding/labels strict →
archive kept or snapshotRejected) + rebase on the loaded sheet (unresolved flags, labels kept), one call
→ hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → navigate /editor
Identity (Step 7, docs/development/IDENTITY.md)
→ AuthProvider: authStore.start() = client.auth.initialize() (PKCE code in URL) + onAuthStateChange
→ signed_in → fetchOwnProfile + fetchOwnPlatformRoles; localeSync applies profiles.locale, saves switches
→ /login /signup /forgot-password /reset-password /auth/callback (packages/supabase auth wrappers, AuthFailure kinds)
→ RequireAuth guards /app/* (→ /login?next=), AppLayout (sidebar / top bar / drawer), Dashboard, Account (updateOwnProfile)
→ no Supabase configured: status unavailable, auth screens show a notice, local tool unchanged
Files and avatar (Step 8 / R1, docs/development/STORAGE.md)
→ AvatarSection: pick → avatarTransport (sniff jpeg/png/webp, bitmap → canvas ≤ 1024 → JPEG) → preview (no request)
→ save: rpc begin_avatar_upload (row pending_upload, server-built keys) → storage upload at the quarantine key (INSERT policy)
→ rpc confirm_asset_upload (uploaded) → poll own assets row 1 s ≤ 30 s → clean: download under the SELECT policy → blob URL in authStore
→ worker (container faunosteo_worker, service key): claim_avatar_jobs (lease token) → GET quarantine → decode child (sandbox, 512² WebP)
→ POST clean object (upsert) → complete_avatar_job (previous clean → deleted, enqueued 48 h) → DELETE quarantine → mark_quarantine_purged
→ refusals: reject_avatar_job(closed code); sweeper: expire_pending_uploads, claim_purges/ack_purge, claim_quarantine_leftovers
→ remove_avatar: rows → deleted, objects purged after the grace; a deleted / superseded row never completes (status + token guards)
Runtime config
→ Docker entrypoint writes env.js (window.__APP_CONFIG__)
→ index.html loads env.js before bundle
→ src/config/env.ts reads window.__APP_CONFIG__ → VITE_APP_* → defaults
→ ConfigProvider exposes via React context
→ appConfig.supabase (url + anon key) or null → lib/supabase.ts lazy client
Database (Supabase)
→ schemas: public (exposed, RLS on every table) / private (helpers, triggers) / audit (append-only)
→ auth.users insert → private.handle_new_auth_user() → public.profiles row
→ platform roles: public.profile_roles written only by grant_platform_role / revoke_platform_role
(security definer, actor checked via private.is_platform_*; every call logged by private.log_event)
→ tests: supabase/tests/*.sql (pgTAP) via PGlite in CI check job and `supabase test db`
```
---
## Project conventions
### Language split
- UI strings: bilingual FR/EN — all user-facing text goes through the i18n system (see below)
- Code: English (variable names, function names, comments, docs)
- Never mix: no French variable names, no raw French/English string literals in JSX — use `useT()`
### i18n
- All user-facing strings live in `src/i18n/fr.ts` and `src/i18n/en.ts` (flat `Record<string, string>`)
- Key convention: `<area>.<key>` — e.g. `common.cancel`, `home.new_report.title`, `pdf.subject`
- Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV
- Get the translate function in any component: `const t = useT()` then `t('common.cancel')`
- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match; while signed in, `services/localeSync.ts` writes it to `profiles.locale` and applies the account locale on sign-in
- Form validation messages are i18n keys returned by the Zod schemas (`src/auth/validation.ts`, `src/account/validation.ts`), translated next to the field; GoTrue messages never reach the screen (`auth.failure.*`)
- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
- PDF static labels (section headings, metadata) live in the engine (`packages/pdf/src/i18n`, `defaultPdfLabels`, 25 keys) and are archived in the envelope; the app dicts hold no `pdf.*` key
### Identity strings
- NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE
- Always read from ConfigProvider via useConfig()
- src/config/env.ts is the only place with defaults
### Design references
- `docs/design/` holds the owner-validated mockups (Step 7 file = target for the whole SaaS shell: sidebar entries, dashboard tiles, Mon compte tabs, mobile tab bar). Any new screen follows them; elements they show that no step has built yet are listed in `docs/design/README.md` with their owning step. A redesign needs a new validated file there first.
### Annotation rendering
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws
the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there
- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
and annotations); no graphic redesign without prior validation
### Schemas
- The data contracts live in Rust since R2 (`crates/core/src/domain/{sheet,report,archive}`, Zod semantics
reproduced: strict where Zod was strict, optional absent, nullable required, Zod schema field order);
`packages/domain` is frozen (no new logic) for the PDF engine, the pipeline and the compare CLI until R4/R5,
and its Zod copy under `packages/core-wasm/tests/n-1` is the permanent N-1 reader. Never change a contract
without bumping the version on a breaking change (additive optional fields keep it); a change touches the
Rust struct, the regenerated ts-rs types and the N-1 test
- Every report entering the store comes from the core (new report, draft restore, import, reducer outputs);
form values are plain assignments (D-R7)
- Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
`mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
(`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
v1 and unknown versions are refused with a typed error
### Stores
- No direct store mutation outside Zustand actions
- No business logic in components — delegate to store actions
- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded, by the core) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits); osteo:quarantine:{draft,archive} (an unreadable text set aside, a draft with its archive, an occupied slot never replaced, never dropped) and osteo:quarantine:draft-pre-rebase (the raw draft of a rebase that flagged items); a text whose set-aside fails is held in place (resolution panel, no new session over it), never removed or overwritten implicitly
- localStorage key: osteo:lastPractitioner (practitioner prefill cache)
### PDF
- A4 portrait: 595.28 × 841.89 pt
- No raw URLs in PDF output — abbreviated citations only
- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report
- The engine (`packages/pdf`) has no DOM lib, no fetch, no Node-only global (lint-enforced); rasterisation is an injected adapter; every SVG it receives is sanitised by allowlist with caps
- Page layout is frozen by the Step 6 goldens: any visible change needs a user decision and a golden regeneration
- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
### Anatomical sheet content
- The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content
change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section)
- The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically
validated and a production build carries no sheet unless that flag is set on purpose
### Database (Supabase)
- The auth session lives in the Supabase client (localStorage, PKCE); the app reads it through `state/authStore.ts` only. Profile columns the user may edit are the column grants in the profiles migrations; never widen them from the client.
- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
statuses (practitioner/student/professor come from verification, cabinet roles from
organization_members). Never add a professional status to `platform_role`.
- Every `public` table: RLS enabled, `revoke all` from API roles then exact grants,
separate policies per command, no `using (true)` for anon/authenticated (test-enforced).
- Writes that change privileges or sensitive state go through a security-definer RPC
that checks `auth.uid()` and calls `private.log_event()`. Never a direct table policy.
- Helpers in `private` are `security definer`, `set search_path = ''`, EXECUTE revoked
from public and granted only to the roles that evaluate them.
- A migration is never edited once applied. Each migration ships its pgTAP file with
allowed AND denied cases, and a regenerated `database.types.ts`.
- The browser holds the anon key only. The `service_role` key value never appears in env.js, .env.example or code;
operator scripts under `packages/*/scripts/` read it from the environment and are never bundled.
- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
### Environments and LAN access (docs/development/ENVIRONMENTS.md)
- The owner tests from other devices of the private network, never on the Ubuntu machine: every test surface
(app, Supabase API, Mailpit, Studio) is addressed by the DEV origin (`scripts/dev-env.sh`, `FAUNOSTEO_DEV_HOST`),
never by `127.0.0.1` / `localhost`, never hard-coded in a source. The Supabase CLI runs only through
`scripts/supabase.sh` (`pnpm db:*`, `pnpm supabase`): config.toml reads the origin with `env()`.
- Exposure (least privilege, `pnpm dev:net-check`): LAN gets Vite 5173, the Supabase API 54321 and Mailpit
behind basic auth through the DEV gateway (`pnpm dev:gateway`, nginx, `faunosteo_dev_gateway`, 54325). The CLI
forces 0.0.0.0 on 54322 PostgreSQL, 54323 Studio, 54324 raw Mailpit: closed on the LAN interface by host UFW
rules (owner action, ENVIRONMENTS.md §3.2); SSH tunnel for Studio; the worker publishes no port. Nothing is exposed to the Internet; no production infrastructure
is touched from this repository. Rust is built natively; Docker runs services, the worker, sandbox tests and images.
### Files and Storage (migration 20261013100000, docs/development/STORAGE.md)
- `public.assets` is the authority over every user file: status, owner, keys, lease. Every write is an RPC; the browser
reads its own rows through an explicit column list (`select=*` is refused: lease columns are not granted).
- Object keys are server-built from uuids (`profiles/<owner>/<id>/avatar.webp`, `quarantine/<owner>/<id>/upload`);
policies on `storage.objects` compare whole strings through `assets` and pin one bucket literal each (census test).
A quarantine object is never readable by an API role; a final key is never writable by the browser.
- New buckets stay closed (row only, no policy) until their step writes the rules; `anatomical-sheet-assets` keeps its own policy.
- The worker holds the service key; the decode child has an empty environment, no file, no network, and is the only
process that decodes untrusted bytes. The parent checks the container header only. Rejections are closed codes.
- Deletions are row-driven: terminal rows enqueue their keys (48 h / 1 h grace), the sweeper serves the queue and the
quarantine leftovers; a clean row's object is never deleted. Backups: dump first, files within 48 h.
- Avatar UI follows the validated mockup: photo in Mon compte (Informations personnelles), sidebar, drawer and top bar
link to Mon compte; JPEG / PNG / WebP only, never SVG; no signed URL for the owner-only avatar (download under RLS).
### Anatomical sheet model (packages/domain + migration 20261008110000)
- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs.
- 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 `validateSheetDocument` (TS) and
`private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table.
- 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`, never edit `legacy-import/` or `draft/` by hand;
the golden test fails on drift). 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 `<sha256>.svg`; uploads are an operator task
(`pnpm assets:upload <seed dir>` with the service key in env), never from the browser.
### Component stubs
- Scaffold stubs render <div>ComponentName placeholder</div>
- Replace stub body entirely when implementing — no partial edits on stubs
---
## Exceptions to global rules
- **React SPA**: explicit exception — this is a practitioner tool, not a public website.
No indexing needed. SPA is correct. (See BDR-001)
- **No API versioning**: no hand-written HTTP API. Supabase exposes tables/RPC through
PostgREST; breaking changes are handled by new migrations and RPC names, not URL versions.
- **80-char line limit**: relaxed to 100 for TypeScript generics and long Zod chains.
---
## Rust by default (rule adopted 2026-10-12, BDR-043)
Study and roadmap: `docs/development/RUST_ARCHITECTURE_REVIEW.md` (validated with
the amendments of Annex C). Done: R0, R1 (worker), R2 (domain core used by the app,
`docs/development/RUST.md` §8). Next: R3 (anatomy core), R4 (PDF core), R5
(pipeline); release 0.2.0 unaffected.
- Any logic that can run in Rust with no significant loss (features, UX,
graphics, data compatibility, security, reliability, useful performance,
resources, portability, maintainability, operations) is written in Rust:
native for services, jobs and tools, WebAssembly for the browser.
Equivalence suffices; "already in TypeScript", "more work" and "no
performance gain" are never reasons to keep TypeScript.
- Kept as is: React + TypeScript for UI, DOM, routing, Zustand stores,
display formatting and vendor-SDK glue (supabase-js); UI form schemas
(Zod, i18n keys) and dictionaries; Tailwind; PostgreSQL/SQL + RLS;
Supabase Auth and Storage; Vite/ESLint tooling. A component kept in
TypeScript needs the concrete constraint recorded in the review's
exception table (Part II).
- New business logic (rules, data transformations, parsers, validators,
jobs, services, rule mirrors of SQL) is designed in `crates/` first and
reached from TypeScript through the wasm facade; Edge Functions are not
used. Boundary rules: "Rust computes, TypeScript reads" (review Part
III.3: coarse calls, JSON strings, sheet handle, closed error kinds, ids
and time injected, no call in a render path).
- Existing code migrates along the review's phases (R0–R5), each with
oracles frozen with the old code before the switch and a consumer-driven
deletion of the TypeScript it replaces; two implementations never outlive
the phase that switches the last consumer.
---
## Key dependencies
| Package | Purpose |
|---|---|
| react 19 | UI framework, automatic memo + concurrent rendering |
| react-dom 19 | DOM renderer |
| react-router-dom 7 | Client-side routing (BrowserRouter) |
| vite 7 | Build tool, HMR, ESM-native |
| @vitejs/plugin-react-swc | Fast React transform via SWC |
| typescript 5 | Type safety, strict mode |
| tailwindcss 4 | CSS-first utility framework |
| zustand 5 | Lightweight global state |
| zod 3 | Schema validation + type inference |
| pdf-lib 1.17 | Pure-JS PDF generation + native attachments |
| motion 11 | Animations (modals, toasts, observation cards) |
| vitest 3 | Test runner |
| happy-dom | DOM environment for tests |
| @testing-library/react | Component testing utilities |
| @testing-library/jest-dom | Custom DOM matchers |
| eslint 9 | Linting (flat config) |
| @supabase/supabase-js 2 | Typed client (packages/supabase) |
| supabase (CLI) 2.120 | Local stack, migrations, pgTAP runner, type generation |
| @electric-sql/pglite 0.3 | PostgreSQL 17 in WASM: runs the pgTAP suite without Docker |
| prettier 3 | Code formatting |
---
## Workflow expectations
- Run `pnpm typecheck && pnpm test:run` before every commit; after any change under `crates/core` or `crates/wasm`,
`pnpm wasm:build` first (the suites refuse a missing or stale module: BUILD_STAMP).
- Contract changes (`crates/core/src/domain`) require the ts-rs types regenerated and committed, all callers updated,
the N-1 reader test green, and a version bump if breaking. `apps/app/src` never imports `@faunosteo/domain` (ESLint).
- Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first.
- Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the
importer's input (the user's historical files).
- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet`, and to their Rust ports (`crates/core/src/domain/{archive/read,report/rebase,report/read,session}.rs`) — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Import never parses untrusted PDF object graphs: the attachment is located by byte scan and inflated under the 16 MiB cap (BLK-009). Opening the import to external users is gated by `docs/development/PDF_IMPORT_HARDENING.md` §5 (BDR-040).
- After PDF roundtrip tests fail: check attachment bytes, then the layered reader (report first, envelope metadata, snapshot/branding/labels), then DecompressionStream inflation. Goldens under `apps/app/tests/fixtures/goldens/step6` are never regenerated without a user decision.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- Rust: native on the Ubuntu development machine (user-level rustup, never a global package, never on the VPS); `pnpm rust:check` and `pnpm wasm:build` run natively, the `:docker` variants reproduce them in the builder image. Before every Rust commit: `pnpm rust:check` green, `pnpm worker:test` green when `crates/worker` changed (Docker only: the sandbox tests and the seccomp derivation never run natively), the ts-rs types under `packages/core-wasm/types` committed, `Cargo.lock` committed. Before a merge: `pnpm check:all`. No CI runs on the forge: a workflow file is never cited as a passed check. The core takes ids, time and bytes as inputs (clippy `disallowed_methods`); the worker child is the only process that decodes untrusted bytes.
- Storage or worker change: `pnpm e2e:avatar` (worker container against the local stack, `packages/supabase/tests/e2e`) in addition to `pnpm worker:test`; `docker compose --profile worker` serves the worker from `.env.worker` (never the app `.env`).
- SQL change: `pnpm --filter @faunosteo/supabase test:run` (PGlite) before commit; `pnpm db:reset && pnpm db:test`
on the real stack when Docker is available; regenerate types (`pnpm db:types`).
## Commit message convention
Conventional Commits format. Subject ≤72 chars, imperative mood, no trailing period.
Allowed scopes: `schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`, `config`, `species`, `i18n`, `docker`, `docs`, `tests`, `chore`, `app`, `workspace`, `ci`, `supabase`, `domain`, `worker`, `public-web`.
Examples:
- `test(schema): cover Report version literal`
- `feat(store): implement addObservation`
- `feat(anatomy): parse data-anno-id from SVG`