Skeleton for Osteo Report MVP. Build passes, 7 smoke tests green, real Horse.svg + Horse_head.svg in public/species/equine/. Zod schemas are the contract; store/anatomy/pdf modules are typed stubs throwing "not implemented" awaiting implementation. Spec: docs/superpowers/specs/2026-05-18-osteo-report-mvp-design.md Plan: docs/superpowers/plans/2026-05-18-osteo-report-mvp.md (23 phases, ~70 TDD tasks) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
16 KiB
Osteo Report — MVP Architecture Spec
Date: 2026-05-18 Status: Approved at validation gate #1.
Purpose
Single-praticien web app for veterinary osteopathy bilans. The praticien selects an animal species, clicks anatomical zones on an SVG schematic to build clinical observations (groups of zones sharing one problem), attaches pathologies (curated DB + free-text) and severity per observation, writes a conclusion + recommendations + next RDV, and exports the whole report as a self-contained A4 PDF whose JSON state is carried as a native PDF attachment. Re-importing the PDF restores the state for a follow-up.
Static SPA, no backend, no auth, no analytics. Deployed as a Docker image serving nginx behind a host nginx reverse proxy on Scaleway VPS. Identity strings (site name, brand, footer) come from env vars, never hardcoded. Open-source (MIT).
MVP species: equine only.
Stack
| Concern | Choice | Why |
|---|---|---|
| Build | Vite 7 + @vitejs/plugin-react-swc | Fast HMR, ESM-native, no Webpack tax. |
| UI | React 19 + TypeScript 5 strict | Editor complexity warrants components; React 19's automatic memo + concurrent rendering. |
| Styling | Tailwind v4 (CSS-first config) + design tokens in CSS | No PostCSS config, design tokens via @theme. |
| State | Zustand 5 | Lighter than Redux, simpler than Context for editor; selectors avoid re-render storms. |
| Validation | Zod 3 | Mirrors persisted JSON schema, gives import-time errors. |
| pdf-lib 1.17 | Pure-JS, supports native PDF attachments via attach(). |
|
| SVG raster | canvg 4 → canvas → PNG → embedPng |
A4 print quality at 2× scale. |
| Animation | motion 11 | Modal transitions, toasts, observation cards. |
| Tests | vitest 3 + happy-dom + RTL | Unit-first; no e2e for MVP. |
| Tooling | ESLint 9 flat config, Prettier, pnpm 9, Node 20 | Modern defaults. |
| Deploy | Multi-stage Docker → nginx:alpine | Static dist served; entrypoint injects env into runtime config. |
Folder tree
osteo/
├─ public/species/equine/{Horse,Horse_head}.svg
├─ src/
│ ├─ app/{App,routes/{Home,NewReport,Editor,NotFound}Route,providers/ConfigProvider}.tsx
│ ├─ config/env.ts
│ ├─ domain/
│ │ ├─ schema/{report,observation,practitioner,animal,pathology}.ts
│ │ └─ species/{registry,types,equine/{index,vertebrae,pathologies}}.ts
│ ├─ state/{reportStore,practitionerCache}.ts
│ ├─ anatomy/{svgLoader,svgConvention,types}.ts
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Toast}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal,ZoneTooltip}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationEditor,PathologyPicker,VertebraPicker,SeveritySelector,FreeTextPathologyInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/Brand.tsx
│ ├─ pdf/{export,import,attachment,fonts}.ts + pdf/render/{header,footer,observationPage,conclusionPage,svgToPng}.ts
│ ├─ lib/{dates,id,assert}.ts
│ ├─ styles/{index,tokens}.css
│ └─ main.tsx
├─ tests/unit/*.test.ts + tests/setup.ts
├─ docs/{ANATOMY-SVG-CONVENTION,ADDING-A-SPECIES,PDF-FORMAT}.md + docs/superpowers/specs/
├─ .claude/{tasks/TODO.md,memory/{decisions,learnings,blockers,journal,evals}.md,audits/.gitkeep}
├─ Dockerfile, docker-compose.yml, nginx.conf
├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json, .gitignore, .dockerignore
├─ eslint.config.js, index.html, package.json, tsconfig*.json, vite.config.ts, vitest.config.ts
└─ CLAUDE.md, README.md, LICENSE (MIT)
Data model
type Severity = 'légère' | 'modérée' | 'sévère';
type Vertebra = { region: 'C' | 'T' | 'L' | 'S' | 'Cd'; index: number };
type ObservationZone = {
boneId: string; // matches data-bone-id from SVG
detailSourceId?: string; // when this zone came from a detail pop-up SVG
vertebrae?: Vertebra[]; // when boneId is a spine-zone
};
type Observation = {
id: string;
zones: ObservationZone[];
pathologyIds: string[];
freeTextPathologies: string[];
severity?: Severity;
comment: string;
};
type Report = {
version: 1;
id: string;
createdAt: string; // ISO
date: string; // clinical date (ISO)
practitioner: { name: string; cabinet?: string; contact?: string; siret?: string };
animal: { speciesId: string; name: string; breed?: string; age?: string };
owner: { name: string };
observations: Observation[];
conclusion: string;
recommendations: string;
nextAppointment?:
| { kind: 'date'; date: string }
| { kind: 'period'; text: string };
};
type PathologyCategory =
| 'osseux' | 'articulaire' | 'musculaire' | 'tendino-ligamentaire'
| 'fascial' | 'visceral' | 'cranio-sacre' | 'nerveux' | 'autre';
type PathologyRef = {
type: 'manual' | 'journal' | 'database' | 'web';
citation: string; // human-readable
url?: string;
};
type Pathology = {
id: string; // stable kebab-case
labelFr: string;
description: string;
category: PathologyCategory;
speciesIds: string[]; // [] = applicable to all species
boneIds: string[]; // [] = applicable to all zones
sources: PathologyRef[]; // 1+
};
All JSON carries version: 1. Future migrations bump the version.
SVG convention (source of truth)
A clickable zone is any element carrying data-bone-id. Required data
attributes: data-bone-id, data-bone-fr, data-bone-en, data-category.
Optional: data-opens-detail="<id>".
Categories: articulation · charniere · spine-zone · os · os-overlay
· head · cadran-crane.
Two rendering patterns are tolerated in the SVG:
- hitbox + visible twin (articulation, charniere, os-overlay, head):
two elements share the same
data-bone-id. One hasclass*="hitbox", transparent fill,pointer-events: all. The other hasclass*="visible", colored fill,pointer-events: none. - single element (spine-zone, head zone): one polygon carries everything;
pointer-events: allandcursor: pointerdirectly.
Parser strategy (src/anatomy/svgConvention.ts):
- Walk all elements with
data-bone-id. - Group by
data-bone-id→ one logicalBone. - Bone fields:
id,fr,en,category,opensDetail?,hitboxEls[],visibleEls[]. - Validate: must have
data-bone-fr,data-bone-en,data-category(in the allowed enum). Throws structuredSvgConventionErroron missing attributes.
Click handling: a single delegated listener on the root <svg> walks up
from event.target to the nearest element with data-bone-id. If
data-opens-detail is present → open the detail modal mapped via the
species manifest. If the bone's category is spine-zone → open the
vertebra picker. Otherwise add the bone to the current observation.
Colorization: when the current observation contains a bone, all elements
matching that data-bone-id get a data-state attribute toggled by JS:
current (solid accent), linked (faded dashed border, "in another
observation"), multi (striped pattern, "in ≥2 observations").
MVP scope cut: hover tooltip listing the owning observations is deferred. Visual state classes alone communicate participation in v1.
Detail-popup mechanism
The mapping detailId → SVG path is held in the species manifest:
// src/domain/species/equine/index.ts
export const equine = {
id: 'equine',
mainSvg: '/species/equine/Horse.svg',
details: { head: '/species/equine/Horse_head.svg' },
vertebralFormula: { C: 7, T: 18, L: 6, S: 5, Cd: 18 }, // approx Cd cap
pathologies: () => import('./pathologies'),
};
When a zone with data-opens-detail="head" is clicked, the canvas
emits a requestDetail({id: 'head'}) event handled by DetailModal, which
loads /species/equine/Horse_head.svg and renders it inline. Clicks inside
the modal add zones with detailSourceId: 'head' to the current
observation. The "entry" zone (e.g. the head polygon itself) is never
persisted in the report.
Vertebra picker
Triggered when a clicked bone has data-category="spine-zone". Modal with
region tabs (Cervicales C1–C7, Thoraciques T1–T18, Lombaires L1–L6,
Sacrales S1–S5, Caudales Cd1–Cd18). Each region renders chips in a grid;
multi-select; ≥40 px touch targets; per-region "Tout cocher / décocher".
Stored as vertebrae: Vertebra[] on the ObservationZone (replaces the
global zone semantically: PDF prints precise vertebrae rather than the
bloc).
If a praticien clicks an individual vertebra (rendered under the same
bone-id as the bloc), it is treated identically to clicking the
spine-zone — opens the picker. Avoids duplicate UI paths.
Multi-observation zone overlay
A bone may belong to several observations. Visual states (data-state
attribute on matching SVG elements, styled via src/styles/index.css):
current— bone is in the active observation. Solid accent fill.linked— bone is in another observation (not current). Dashed border, faded accent fill.multi— bone is in ≥2 observations. Same fill + heavier stroke to signal sharing.
MVP scope cut: per-observation HSL accent cycling (6 clinical-warm tones) deferred to v1.1. v1 uses a single accent color across all states; PDF renders per-observation pages, so colour ambiguity does not bleed into the printed report.
PDF format
A4 portrait (595.28 × 841.89 pt). One pdf-lib document per export. Pages share a header drawer (praticien left block, animal+owner+date right) and a footer drawer (env-driven brand name, export date, page x/y).
Per observation: one page with
- the full main SVG rasterized at 2× scale with that observation's zones
colored (canvg writes to canvas → PNG →
embedPng); - if the observation includes detail-sourced zones (e.g. head): a second rasterization of the detail SVG with those zones colored, placed beside or below the main raster;
- a structured block beneath the schematic: zones (with precise vertebrae formatted as "T12, T15"), pathologies (selected + free-text), severity, comment.
MVP scope cut: source citations under each cited pathology are deferred to post-MVP. Pathology IDs/labels render without their
sources[]block.
Final page: conclusion, recommendations, next appointment.
JSON attachment: the full Report object is serialized and attached via
pdfDoc.attach(bytes, 'osteo-report.json', { mimeType: 'application/json', description: 'Osteo Report state v1', creationDate, modificationDate, afRelationship: 'Data' }). Bytes are pretty-printed JSON (UTF-8).
MVP fonts: pdf-lib standard Helvetica + Helvetica-Bold (body) + Times-Roman (headings). Inter Sans + Fraunces TTF bundling deferred to v1.1 to avoid shipping ~600KB of font assets in the initial Docker image.
PDF import
pdf-lib loadDocument() → walk catalog Names → EmbeddedFiles tree → find
an attachment whose filename starts with osteo-report and whose mime is
application/json (or, fallback, parse-then-validate). Extract the stream,
flate-decompress if needed (pako), parse JSON, validate with Zod. On
success: hydrate the store and route to /editor. On failure: throw
ImportError with the French message
"Ce PDF n'a pas été généré par Osteo Report (pas de données détectées)." and
show a toast.
Configurable identity
Env vars consumed at runtime:
| Name | Default | Use |
|---|---|---|
PORT |
8080 |
nginx listen port. |
APP_SITE_NAME |
Osteo Report |
<title>. |
APP_BRAND_NAME |
Osteo Report |
UI header, hero. |
APP_FOOTER_NAME |
Osteo Report |
PDF footer. |
APP_TAGLINE |
Bilans d'ostéopathie animalière |
Home tagline. |
Mechanism: Docker entrypoint templates index.html to inject a
<script>window.__APP_CONFIG__ = {...}</script> tag using container env
vars. src/config/env.ts reads window.__APP_CONFIG__ first, falls back
to import.meta.env.VITE_APP_* build-time values, then to defaults.
ConfigProvider exposes the resolved config via React context. No identity
string is hardcoded in any component.
Routes
/— Home. Two CTAs ("Nouveau bilan", "Importer un PDF"). Quick-resume card if a sessionStorage draft exists./new— New report form. Species select (equine only for MVP), praticien fields (prefilled fromosteo:lastPractitioner), animal (name + optional race/age), owner name, date (default today)./editor— Editor. Split layout: anatomy canvas + observation panel. Bottom bar: export button.*— NotFoundRoute.
State persistence
- Zustand store in memory.
- sessionStorage mirror (
osteo:draft) auto-restored on/editorif the user reloads accidentally; cleared after export. - localStorage (
osteo:lastPractitioner) caches the praticien block to prefill next "Nouveau bilan". - No long-term storage. PDF is the only durable artifact.
Test strategy
- vitest + happy-dom.
- TDD-first for: schema (Zod parse + reject malformed), store actions, id generator, anatomy convention parser (valid SVG → bones; bad SVG → structured error), pathology DB integrity (every entry validates + has ≥1 source), pdf attachment write+extract roundtrip on a fixture file.
- UI smoke test: AnatomyCanvas mounts a fixture SVG and emits click for a known bone.
- No e2e (no gstack plugin); manual QA in browser before commit.
Docker / deploy
Multi-stage Dockerfile:
- builder —
node:20-alpine.corepack enable && pnpm i --frozen-lockfile && pnpm build. - runner —
nginx:alpine. Copydist/to/usr/share/nginx/html, customnginx.conflistening on${PORT:-8080},entrypoint.shwrites/usr/share/nginx/html/env.jsfromAPP_*env vars, then runs nginx.
docker-compose.yml exposes ${PORT}:${PORT} and passes APP_* env vars
through env_file. The host nginx reverse-proxies any subdomain to that
port.
Open decisions resolved
| Decision | Resolution |
|---|---|
| SVG injection | Fetch text → DOMParser → inline render (consistent + CSS-controllable + sandboxing irrelevant since assets are local). |
| Vertebra picker UX | Region tabs + chip grid, multi-select, ≥40 px touch targets. |
| Multi-obs zone overlay | current / linked / multi states; striped pattern + tooltip. |
| Detail SVG trigger | data-opens-detail → modal with inline detail SVG, clicks add to current obs. |
| SVG → PDF | canvg → canvas @ 2× → PNG → embedPng. |
| Pathology sources in PDF | Abbreviated citation list below each obs, no raw URLs. |
| Brand env vars | Runtime window.__APP_CONFIG__ + Vite-define fallback. |
| MVP scope | Equine only. |
| Drag-reorder obs | ↑/↓ buttons, no DnD. |
| Practitioner default | localStorage cache. |
| State persistence | sessionStorage mirror + PDF for long-term. |
| Animation lib | motion 11. |
| License | MIT. |
Prerequisites / REMAINING
- Real anatomical SVGs delivered by user at repo root:
Horse.svg+Horse_head.svg. Moved intopublic/species/equine/by the scaffolder. - Pathology DB authoring — deferred to post-MVP. v1 ships with an
empty
EQUINE_PATHOLOGIES = []and a relaxed integrity test (length 0..100). Pathology picker shows the "aucune pathologie de référence" empty-state; praticien adds entries via free-text. Client osteo (or a Phase 2 multi-user authoring tool) will populate the curated DB once the long-term account architecture is decided. - Source citations in PDF — deferred to v1.1. Once the DB exists, re-enable the abbreviated-citation block on each observation page.
- Hover tooltip on canvas — deferred to v1.1. Visual state classes alone in v1.
- Per-observation HSL accent cycling — deferred to v1.1. Single accent in v1.
- Inter + Fraunces TTF bundling — deferred to v1.1. PDF uses standard Helvetica + Times-Roman in v1.
docs/ADDING-A-SPECIES.md— content to be authored from the observed SVG convention + species manifest pattern (placeholder file exists today).- Final brand name, domain, identity strings.
- Phase 2 (out of MVP): user accounts, server persistence, animal history, and curated pathology DB authoring tooling.