Files
faunosteo/CLAUDE.md
T

405 lines
19 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
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`). The UI does not use
the client yet (local-only flows unchanged).
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 | — |
---
## 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
pnpm dev
# 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
pnpm db:start # start stack, apply migrations + seed
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
```
## Docker commands
```bash
# Build image
docker build -t faunosteo .
# Run with compose (reads .env for APP_* vars)
docker compose up --build
# Stop
docker compose down
```
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/`. Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Characterisation suite: files prefixed `char.`.
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/
│ ├─ species/equine/{Horse,Horse_head}.svg ← real anatomy SVGs
│ └─ pathology-editor.html ← standalone JSON editor (served as static file)
├─ src/
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,Editors,SvgEditor,NotFound}Route.tsx
│ │ └─ providers/ConfigProvider.tsx ← AppConfig context
│ ├─ config/env.ts ← runtime config resolution
│ ├─ domain/
│ │ ├─ schema/ ← Zod schemas (source of truth)
│ │ │ ├─ report.ts
│ │ │ ├─ observation.ts
│ │ │ ├─ practitioner.ts
│ │ │ ├─ animal.ts
│ │ │ └─ findings.ts
│ │ └─ species/
│ │ ├─ types.ts ← SpeciesManifest interface
│ │ ├─ registry.ts ← getSpecies(), getAllSpecies()
│ │ └─ equine/{index,vertebrae,pathologies}.{ts,json}
│ ├─ 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/
│ │ ├─ reportStore.ts ← Zustand store
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/
│ │ ├─ types.ts ← Bone, BoneCategory, BoneState
│ │ ├─ svgConvention.ts ← parseSvgBones()
│ │ ├─ svgLoader.ts ← loadSvg()
│ │ └─ labels.ts ← boneLabel(bone, locale, fallback)
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/
│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts
│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts
│ ├─ lib/{dates,id,assert,zoneMatch,spineZones,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens,svg-editor}.css ← Tailwind v4 CSS-first + SVG editor styles
│ └─ main.tsx
├─ tests/
│ ├─ setup.ts
│ └─ unit/*.test.ts
├─ docker/
│ ├─ entrypoint.sh ← injects env.js at container start
│ └─ nginx.conf ← SPA fallback + PORT envsubst
├─ docs/
│ ├─ ANATOMY-SVG-CONVENTION.md ← SVG data-* contract
│ ├─ ADDING-A-SPECIES.md
│ ├─ PDF-FORMAT.md
│ ├─ 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)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/supabase/ ← @faunosteo/supabase
│ ├─ src/{index,client,database.types,anatomical-sheets}.ts ← typed client, generated types, publish gate
│ └─ 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
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
├─ .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)
SVG interaction
→ AnatomyCanvas fetches SVG text via loadSvg()
→ parseSvgBones() walks DOM → Bone map
→ delegated click listener → getBoneIdFromEvent()
→ if spine-zone → VertebraPicker modal
→ if data-anno-opens-detail → DetailModal (loads detail SVG)
→ else → updateObservation() in store
PDF export
→ exportReportToPdf(report, { locale })
→ pdf-lib PDFDocument
→ embedFonts (Helvetica body + TimesRoman heading — WinAnsi StandardFonts; TTF Inter/Fraunces planned)
→ for each observation: addObservationPage (rasterize SVG → PNG)
→ addConclusionPage
→ attachReportJson (native EmbeddedFiles)
→ Uint8Array → browser download
PDF import
→ importReportFromPdf(bytes)
→ extractReportJson → Zod validate
→ hydrateReport() → navigate /editor
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
- Finding leaf labels (zone names shown in PDF) are resolved at export time via SVG `data-anno-name-fr` / `data-anno-name-en` attributes — not from the dict
- PDF static labels (section headings, metadata) come from the dict via `getDict(locale)` in `exportReportToPdf`
### 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
### SVG convention
- docs/ANATOMY-SVG-CONVENTION.md is the source of truth
- Every clickable element must have: data-anno-id, data-anno-name-fr, data-anno-name-en, data-anno-category
- SvgConventionError thrown on any missing required attribute
- Never rely on element id or className for click targeting — always data-anno-id
### Schemas
- domain/schema/*.ts are the data contracts — never change without bumping version
- All user-provided data goes through Zod parse before hitting the store
- ReportSchema.version = 2 (v1 attachments rejected at import with a typed error); future breaking changes → version 3
### Stores
- No direct store mutation outside Zustand actions
- No business logic in components — delegate to store actions
- sessionStorage key: osteo:draft (auto-saved on every observation change)
- 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
- 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 `⚠`).
### Pathology DB
- All entries must pass PathologySchema.parse()
- Each entry needs ≥1 source with citation
- boneIds: [] = all zones; speciesIds: [] = all species
- Source types: manual | journal | database | web
### Database (Supabase)
- 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. `service_role` never appears in env.js, .env.example or code.
- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
### 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`.
### 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.
---
## 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.
- Domain schema changes (domain/schema/*.ts) require updating all callers + bumping version if breaking.
- SVG convention changes require updating docs/ANATOMY-SVG-CONVENTION.md first.
- Never modify anatomy SVGs in public/species/ — they are source assets from the user.
- Pathology DB entries must be source-cited before commit; client review required for MVP batch.
- Ask before any change to importReportFromPdf or extractReportJson — these handle user data.
- After PDF roundtrip tests fail: check attachment bytes, then Zod validation, then DecompressionStream inflation.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- 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`