Files
faunosteo/.claude/memory/decisions.md
T

25 KiB
Raw Blame History

Decisions Registry

Format: BDR-XXX | Date | Title | Rationale | Alternatives | Status


BDR-001 | 2026-05-18 | React SPA exception for tool app

Tool is practitioner-only, no public indexing needed → SPA valid per CLAUDE.md rule. Alt: Next.js SSR rejected — no server, static deploy only. Status: closed.


BDR-002 | 2026-05-18 | SVG inline via DOMParser, not img/object

Inline SVG = full CSS control, pointer-events, data-* access. img/object = sandboxed, no DOM access, no click delegation. Status: closed.


BDR-003 | 2026-05-18 | PDF attachment via native pdf-lib attach()

Native EmbeddedFiles (afRelationship:Data) = proper PDF spec, survives re-save in Acrobat. Alt: custom metadata → rejected (non-standard, stripped by some viewers). Status: closed.


BDR-004 | 2026-05-18 | Runtime identity via window.APP_CONFIG

Build-time VITE_APP_* → baked into bundle; runtime injection via entrypoint.sh → no rebuild needed for brand changes. Order: runtime > build-time > defaults. Status: closed.


BDR-005 | 2026-05-18 | Vertebra picker: region tabs + chip grid

≥40px touch targets, multi-select, per-region toggle. Alt: flat list → too long for 54 total vertebrae. Status: closed.


BDR-006 | 2026-05-18 | Drag-reorder: up/down buttons, not DnD

DnD on mobile unreliable; ↑/↓ buttons accessible + simple. Status: closed.


BDR-007 | 2026-05-18 | pnpm 11 used instead of pnpm 9

pnpm@9 not available on host; corepack resolved 11.1.3. Package.json engine constraint set to >=9 for Docker (Docker uses corepack latest). Status: closed — deviation accepted.


BDR-008 | 2026-05-19 | PDF page layout — branded heading pattern

Each PDF page leads with bold-uppercase accent eyebrow (size 9), Times 22 title, 2pt × 48pt accent rule under title. Section labels follow same eyebrow style (uppercase bold accent) above their values. Observation severity rendered as filled color-coded pill (sage / amber / red) next to the obs number. Alts: plain text titles only — rejected (overlapped header rule + read unstyled). Status: closed.


BDR-009 | 2026-05-20 | Findings JSON keeps snake_case in TS, observation snapshot uses camelCase

JSON catalog fields (name_fr/name_en/description_fr/requires_vet_referral/...) stay snake_case in TS types/Zod schema — no transform layer. Domain-expert authored, reads natural in JSON, zero remap cost. Observation Finding snapshot uses camelCase (labelFrSnapshot/labelEnSnapshot/requiresVetReferral) per app convention. Alt: Zod transform to camelCase everywhere — rejected (extra layer, hides JSON shape, no real upside for a static catalog). Status: closed.


BDR-010 | 2026-05-20 | Observation findings snapshot labels at selection time

Finding stores labelFrSnapshot + labelEnSnapshot copied from leaf at click time. Exported reports remain readable years later even if catalog renames/restructures leaves. Path[] still carried for future re-link/migration. Alt: lookup labels on render via path — rejected (breaks already-exported PDFs if catalog edits). Status: closed.


BDR-011 | 2026-05-20 | v1 PDF import — hard-fail with version-specific FR message

importReportFromPdf detects data.version !== 2 BEFORE strict Zod parse, throws IncompatibleReportVersionError, wrapped into ImportError with explicit "v{n}, incompatible avec v2, réexportez..." message. No retro-compat shim (no prod PDFs in the wild). Alt: silent generic ImportError — rejected (user can't tell why import failed). Alt: v1→v2 migration adapter — rejected (no install base to justify cost). Status: closed.


BDR-012 | 2026-05-20 | Species auto-discovery via Vite import.meta.glob

src/domain/species/registry.ts uses import.meta.glob('./*/index.ts', { eager: true }) and registers every module that default-exports a SpeciesManifest. Drop-folder onboarding: scaffold writes index.ts with export default <id>, no registry edit needed. Duplicate id → warn + first wins. Missing default export → silently skipped. Alt rejected: hardcoded SPECIES_REGISTRY map — forced edits in two places, broke "single source of truth" per species folder. Alt rejected: explicit registerSpecies() runtime helper — extra import boilerplate per species, no compile-time check that registration runs. Status: closed.


BDR-013 | 2026-05-20 | SVG↔JSON zone bridge via fuzzy FR/EN label match

SVG data-anno-id values stay opaque generator strings (point-mpb..., zone-...). JSON catalog keys are stable human zone names (sphenoid, atm). Bridge runs at observation render: matchZoneFindings normalizes both sides (lowercase + NFD-strip accents + alphanum-only) and scores EN-exact → FR-exact → substring → Levenshtein within max(2, floor(maxLen*0.25)) tolerance. EN first because no accent normalization edge cases. Alt rejected: rename SVG data-anno-id to JSON keys — couples opaque SVG generator output to human-meaningful catalog, brittle across SVG re-exports. Alt rejected: add new data-anno-finding-zone attribute on every hitbox — forces SVG edit per species, double-source for the same info already in name_fr/en. Status: closed.


BDR-014 | 2026-05-20 | PDF locale = render preference, not Report schema field

exportReportToPdf takes explicit { locale } option read from localeStore at call site. Locale lives outside Report — never persisted in schema. Rationale: Finding snapshots already carry labelFrSnapshot+labelEnSnapshot (per BDR-010), so render-time locale picks the correct snapshot; no schema bump needed; re-imported PDF can be re-exported in either locale without data migration; embedded JSON byte-identical between locale variants of the same Report. Alt rejected: store locale field on Report schema — would force v3 bump, complicate re-export ergonomics, duplicate state already in store. Alt rejected: default locale to 'fr' in export — caller is route layer, has store, easy to pass; explicit arg makes tests + API surface clean. Status: closed.


BDR-015 | 2026-05-20 | Typed ImportError discriminant (kind + foundVersion) over localized messages

ImportError carries kind: 'invalid_pdf' | 'incompatible_version' | 'no_attachment' + optional foundVersion. Message field collapses to internal sentinel. UI layer (HomeRoute) resolves user-facing string via i18n dict using err.kind, with {version} template substitution. Rationale: review caught hardcoded FR in pdf/import.ts + pdf/attachment.ts leaking to EN UI; original "throw with localized message" coupled domain layer to one locale; typed discriminant moves message authoring to the UI layer where i18n lives. Alt rejected: keep FR messages, translate via err.message string match — brittle (any rewording breaks the lookup), spreads i18n knowledge into the catch site. Alt rejected: pass t() into domain layer — wrong direction; domain should not know about React hooks or current locale. Status: closed.


BDR-016 | 2026-05-21 | pathologies.json v2.0 — boolean source of truth, generic vet description_fr purged

Catalog bumped v1.2→v2.0. requires_vet_referral: true boolean = sole source of truth for vet flag. Generic "orienter vers vétérinaire" descriptions purged on 25 leaves where boolean alone sufficed. description_fr kept on 16 leaves carrying differential cue (cause neuro/sinusale/ligamentaire/rotulienne/etc.). Horse coverage extended placeholder 3 zones → full 26 zones (9 head + 17 body), 792 nodes, 612 leaves, 41 vet-referral leaves. Schema_version "2.0". Why: v1.2 had textual fallback (description_fr.includes('vétérinaire')) + boolean coexisting → redundant + ambiguous. v2.0 collapses to one signal. How to apply: Any new species JSON authored at v2.0 — boolean on vet leaves only, description_fr only when it adds clinical differential beyond "see vet". Consumers MUST use boolean check, never textual scan. Alt rejected: keep dual signal — wastes maintainer attention, drift risk between text and boolean. Status: closed.


BDR-017 | 2026-05-22 | SVG editor: vanilla JS wrap over React rewrite

editor.html = ~1630-line standalone SVG annotation tool (DOM manipulation, drag/drop, polygon editing, zoom, categories, export). Integrated into React app via useRef + useEffect mounting all vanilla JS logic into container refs. Only CSS restyled to Faunosteo tokens. Alt rejected: full React rewrite (convert all state to Zustand/useState, all DOM ops to React) — massive effort ~10x, high risk of subtle behavior differences in drag/polygon/zoom interactions. Status: closed.


BDR-020 | 2026-05-22 | Pathology editor: standalone HTML, not React route

pathology-editor.html = standalone tool at project root, same pattern as SVG editor integration. Vanilla JS/CSS, no build step, no deps. Decoupled from React app entirely — zero imports from src/. Why: tool for domain experts editing JSON, not practitioners using main app. No shared state needed. Standalone = deployable anywhere, no Vite required. Alt rejected: React route with Zustand store — unnecessary coupling, heavier DX for a JSON editing tool. Status: closed.


BDR-021 | 2026-05-22 | Port zoneMatch.ts inline into pathology editor

Fuzzy matching logic (normalizeLabel, levenshtein, scorePair, matchZone) duplicated inline in pathology-editor.html rather than imported from src/lib/zoneMatch.ts. Why: standalone HTML cannot import TS modules. Keeping identical algorithm ensures matching consistency between main app and editor. Alt rejected: extract to shared .js file — adds dependency management for a tool that should be zero-dep. Status: closed.


BDR-018 | 2026-05-27 | Vertebra picker confirm — target region replaces, other regions union

VertebraPicker anchored on clicked spine zone but lets user switch region tabs. On confirm, distributeVertebraeToZones spreads picks across one spine zone per region. Target region (clicked zone) = REPLACE (picker seeded with its full set → unchecking deselects). Other regions = UNION with any pre-existing zone (picker didn't display them → side-tab pick must be purely additive, never wipe). Region with no SVG spine zone → fold verts back onto target (nothing lost). Why: picking verts in a non-target tab must behave as if that zone was also clicked — highlight + findings picker both flow from observation.zones. Replace-everywhere would silently wipe a cervical zone selected earlier when reopening lumbar picker. Alt rejected: seed picker with full-spine union of all zones → forces handling deselection-to-zero per region (remove zone + orphan its findings); bigger scope, destructive. Additive-only matches user request. Alt rejected: keep dumping all verts on clicked zone (old bug) — other zones never highlight, no findings picker. Status: SUPERSEDED by BDR-019 (same session) — additive-union model dropped once picker shows full spine.


BDR-019 | 2026-05-27 | Vertebra picker = unified full-spine editor, authoritative confirm

User asked picker to SHOW selections from all regions when switching tabs. Once it displays + edits every region, additive-union confirm (BDR-018) breaks: unchecking a side-tab vert can't stick (union re-adds from existing zone). So model flipped to unified + authoritative. Seed: collectSpineVertebrae(zones, bones, clickedBoneId) = union of all spine-zone verts, clicked zone first. Confirm: syncSpineZones(zones, verts, bones) — per region: REPLACE existing zone verts (deselect sticks); PRUNE spine zone whose region → 0; SPAWN zone for newly picked region. Non-spine zones + order preserved. targetIndex dropped — each vertebra carries its own region, no anchor needed. Tab: clicking zone ALWAYS opens its region — initialRegion now beats initial[0].region in VertebraPicker (was reverse). Updated the test that asserted old precedence. Why: picker as whole-spine editor is the only coherent model when all regions visible + editable; partial/additive semantics contradict what user sees. Known wart (accepted): pruning a region orphans its findings (findings keyed by tree zoneId, not boneId; sync works in boneId space). Parity with existing ✕ remove-zone button — neither cleans findings. Follow-up if needed. Confined to spine: picker only opens for special==='vertebral-precision'; sync/collect/find all gate on it; non-spine zones pass through. Tests cover. Alt rejected: keep additive (BDR-018) + only change seeding — deselection in non-clicked tab silently fails. Status: closed.


BDR-022 | 2026-06-13 | Keep pathology-editor standalone — asymmetry vs svg-editor intentional

After 404 fix (moved pathology-editor.html root→public/, LRN-029), considered unifying it with svg-editor pattern (React route, vanilla wrapped in useEffect, BDR-017). Rejected. Two editors differ by COUPLING, not accident:

  • svg-editor REUSES app internals (getAllSpecies registry, useLocaleStore+getDict, AppHeader) → React route earns its keep (BDR-017).
  • pathology-editor = zero src/ imports by design (BDR-020/021): own inline i18n (76 keys), own zoneMatch copy. Isolated on purpose. Why keep standalone: editor PRODUCES the prod pathologies.json the live app reads (fetches /species/equine/{pathologies.json,Horse.svg,Horse_head.svg} — same bytes as app). Tool touching prod data = minimal-change zone. Wrapping ~1700 lines of imperative DOM in a useEffect to chase cosmetic parity risks the JSON export path for no functional gain. The svg-editor wrap (1832-line useEffect) is the WORSE of the two patterns, not the target to copy. Alt rejected: pathology→React route (BDR-017 style) — propagates the dubious pattern over 1700 lines, regression risk on drag/tree-edit/SVG-sanitize/fuzzy-match. Alt rejected: both→standalone public/ (de-wrap svg) — cleaner unification but svg now coupled to species registry + locale store; de-wrapping costs + loses language sync. Status: closed.

BDR-023 | 2026-10-08 | Monorepo: apps/app + pnpm workspace, packages extracted on demand only

App moved to apps/app (@faunosteo/app, git mv, 144 pure renames). Root package.json delegates (pnpm -r). packages/ = README only; a package is created when it has a clear owner + real code (plan Steps 3/4/6). apps/public-web, apps/worker, supabase/ created by the step needing them. Why: root one-word commands, Docker filtered build, lockfile v9 already workspace-capable; moving later (after packages + 2nd app) costs more. Empty packages = config to maintain for nothing. Alt rejected: app kept at root beside apps/public-web (special-cased configs); single Next.js app (rewrite, SSR useless behind auth). Status: closed (user validated 2026-10-08).


BDR-024 | 2026-10-08 | Node 24 LTS + pnpm 10.13.1 pinned, engine-strict

Node 24 (.nvmrc, .node-version, engines >=22.12 <25, Dockerfile node:24-alpine, CI). pnpm 10.13.1 via packageManager + root devDependency (scripts find node_modules/.bin/pnpm under corepack or any install) + engines <11. .npmrc engine-strict=true. Why: Node 20 EOL 2026-04-30; dev host on 24; all checks ran on 24. pnpm 11 needs Node ≥22.13 and rewrites lockfile; 10.13.1 = Dockerfile-validated pin (BLK-005). Lockfile rewritten by 10.13.1 (libc fields from earlier pnpm 11 dropped) → coherent with pin. Alt rejected: keep Node 20 (EOL); global pnpm (user rule: no global install). Risk: Docker build on node:24 not run locally (no daemon) → CI docker job / manual build before deploy. Status: closed.


BDR-025 | 2026-10-08 | Design records live in docs/history/superpowers, not docs/superpowers

gitflow lib purges docs/superpowers/{specs,plans} at every finish (BDR-065, fixed path list). Step 1 finish deleted 9 design docs (8f217d8). Restored from history under docs/history/superpowers/ (not purged); refs updated (CLAUDE.md, migration map, plan). Audit docs keep old path (frozen). Alt rejected: revert in place → purged again next finish; editing the lib list → global change for one repo. Status: closed.


BDR-026 | 2026-10-08 | platform_role enum = owner/admin/moderator/support only; professional statuses excluded

Business arch §4.1 lumps 7 values in profile_roles.role (practitioner/student/professor + 4 platform). User rule: never confuse platform roles with professional statuses. Table name kept profile_roles (plan + helper names unchanged), enum platform_role 4 values. practitioner/student/professor → verification outcome (identity step); cabinet roles → organization_members. Hierarchy for checks: owner ⊇ admin ⊇ moderator; support separate (§17.3). Deactivated profile (active=false) → all helpers false. Alt rejected: 7-value enum per arch doc → self-declared "practitioner" row readable as verified status. Status: closed (user instruction), name profile_roles open to rename if user prefers platform_roles.


BDR-027 | 2026-10-08 | Role writes RPC-only + audited; column-level GRANT protects profiles.active / phone_verified_at

No INSERT/UPDATE/DELETE policy on profile_roles; only grant_platform_role / revoke_platform_role (security definer, actor = auth.uid(), self-target refused, owner any role / admin moderator+support) → private.assign/withdraw_platform_role → private.log_event. Bootstrap first owner: assign_platform_role(null, uid, 'owner') from privileged SQL. Last active owner cannot be revoked. profiles: grant update (display_name, first_name, last_name, phone, locale, timezone) instead of a protect-columns trigger → active, phone_verified_at raise 42501 for API role, server functions untouched. Alt rejected: BEFORE UPDATE trigger checking auth.uid() → blocks future server RPC acting for the caller; column grants declarative, visible in has_column_privilege. Status: closed.


BDR-028 | 2026-10-08 | pgTAP single source of SQL tests; PGlite runner in vitest beside supabase test db

Docker socket denied to user on dev host (BLK-006). PGlite 0.3.16 (PG17 WASM) ships pgtap extension → packages/supabase/tests/db/ applies supabase-shim.sql (API roles, auth.users, auth.uid(), Supabase default privileges) + migrations, runs every supabase/tests/*.sql, fails on not ok / plan mismatch. Same files run by supabase test db on real stack (CI supabase job). Shim replicates permissive default privileges so a missing revoke fails. Alt rejected: TS-only RLS tests (duplicate harness, drift); waiting for Docker (no executed proof). Status: closed.


BDR-029 | 2026-10-08 | database.types.ts hand-written in supabase gen types format + schema↔types test

CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). schema-types.test.ts: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no using(true) for every future public table. CI db:types:check diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit. Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed.


BDR-030 | 2026-10-08 | Step 4 split: model + persistence now, importer → official equine DRAFT next

User brief: no full equine import yet; first official horse sheet = draft, business content verified before publication. Plan Step 4 bundled model + importer. Split: Step 4 = packages/domain document + validation + migration + pgTAP + docs; Step 4b = legacy importer → draft + IMPORT-REPORT, publish on user go. packages/anatomy created at 4b. Alt rejected: importer in same step → publishes seed v1 immutable before expert review (contradicts brief). Status: closed (plan note added under Step 4).


BDR-031 | 2026-10-08 | Canonical sheet document shape (schema_version 1)

Labels { fr, en } objects (one LocalizedText, new locale = optional key) instead of name_fr/name_en pairs. Strict Zod objects (unknown key rejected). Structural records explicit null; finding tree nodes lean on input, .default() fills description/sources/children/requires_vet_referral (612 leaves). Views = tree (parent_view_id), detail svg_asset_id nullable = crop parent via view_box (C9). Annotation discriminated union point|zone|detail_trigger; laterality 4 values explicit (unpaired/bilateral/left/right); spine = vertebral_region_code → ordered vertebral_config.regions with free codes (C1/Q3); findings link = inline finding_zone_id (no separate map, no label matching); finding categories carry kind dysfunction|observation|anamnesis|custom; node ids unique among siblings so (zone, path[]) addressing survives Step 5. Two tiers: shape (Zod, every save) vs integrity (validateSheetDocument, 17 coded rules, publish gate). Alt rejected: name_fr/name_en flat (BDR-009 catalog style) → no locale extension; annotation_finding_map array → extra structure for a 1:N field; UUIDs as in-document ids → unreadable, legacy paths re-keyed. Status: closed; category kind observation vs report Observation collision (C7) flagged to user.


BDR-032 | 2026-10-08 | Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets

Tables species / anatomical_sheets / _versions / _assets. Published immutable via BEFORE UPDATE trigger (every role incl. owner; only published→deprecated with stamps); deprecated frozen; BEFORE DELETE trigger = preconditions (never published, never current, never base of active fork; reports join later) → no session flags, RPC just deletes. One draft per sheet (partial unique index, C8). Document↔row: CHECK content->'schema_version' = to_jsonb(document_schema_version), trigger species match. private.sheet_document_issues(jsonb) re-checks the non-recursive error rules at publish + unknown asset ids → defense in depth, same codes as TS (BACKEND_ARCH "SQL doesn't re-implement Zod" kept for shape). Assets content-addressed (sha256, unique per sheet), Storage path <sha256>.svg by convention, fork = metadata copy + remap_document_assets. Draft autosave = column-level UPDATE (content, change_note) policy on own draft (unaudited by design); identity (name/slug/description) column policy; visibility via audited set_sheet_visibility RPC and draft deletion via delete_sheet_version after gate review (sharing + deletion = sensitive state); last_version_number counter (no number reuse); content ≤ 2 MiB, byte_size ≤ 20 MiB, reason ≤ 500; require_actor refuses deactivated profiles; authz before lookup (unknown id = same 42501); fork copies only referenced assets. can_use_sheet = active ∧ (public ∨ editor) until grants/follows. Official sheet = creator null + is_official, platform admins edit. Alt rejected: session-flag delete bypass (hacky); Zod-equivalent validation only in TS (browser not a boundary); per-sheet asset storage copy on fork (needs worker job). Status: closed; names (anatomical_sheet_assets, storage layout, official ownership) listed for user confirmation.


BDR-033 | 2026-10-09 | User decisions on the Step 4 open points (sheets: follow, verification, versions, official, naming, server validation, erasure)

User validated Step 4 and ruled: (1) public read by visibility, USE of a community sheet requires following its author, official sheets exempt → can_use_sheet + follow at community step; (2) private drafts for anyone, community publication only for authorised + verified accounts, student/professor keep own rules → gate in publish/set_visibility at verification step; (3) new publication = current, no auto-deprecation (current behaviour); (4) official sheets platform-owned, admin-run (current model); (5) finding kind observation → consultation_reason (done, packages/domain); (6) server-side validation mandatory for publication, frontend never a boundary → Zod shape check server-side before community step; (7) account deletion handles dependencies/transfer explicitly, nothing may block erasure forever → retention step anonymises authorship via a system path. Scope guard from user: implement along the planned steps, keep 4b (equine import) free of community/account features. Status: closed (recorded in ANATOMICAL_SHEET_MODEL.md §5).


BDR-034 | 2026-10-09 | Equine import = generated seed, draft only; assets content-addressed in a private bucket read through the sheet

Importer (packages/anatomy, one-off, deterministic) emits supabase/seed/anatomical-sheets/equine/v1: document.json, legacy-id-map.json, assets.json + SVG copies, IMPORT-REPORT.md (FR, for the osteopath), equine_v1.sql (idempotent: official platform-owned sheet faunosteo-cheval private + 2 asset rows + draft v1 via private.insert_sheet_draft(null,…)). Golden test = committed artifacts equal a fresh run. Ids: annotation = catalog zone key on exact FR+EN match (26/26), views main/head, trigger head-trigger, asset/sheet uuids derived from sha256 (uuid v5-like). No medical correction: ssb-dysfunctions kept + anomaly; only degraded slugs normalised and declared; 12 anomalies to validate, 6 informative. Seed listed in config sql_paths (every env) and applied by the PGlite harness (seed/**, never seed.sql). Storage: bucket anatomical-sheet-assets private, <sha256>.svg, SELECT policy via private.can_read_sheet_asset_object (published reference of usable sheet, or editor), no API writes, operator upload script with service key from env. Alt rejected: data migration for the sheet (immutable file for a draft meant to be edited); TS seeding via PostgREST (needs service key in a committed path); fuzzy zoneMatch at import (26/26 exact, strict equality + report suffices). Status: closed; publication of v1 = explicit user decision after report review.