diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index 6a53bc66..340544fe 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -1,10 +1,28 @@ +--- +format: 2 +type: blockers_registry +entry_prefix: BLK +schema: + id: BLK-XXX + date: YYYY-MM-DD + friction: string (what was blocked) + real_cause: string (root cause, not symptom) + solution: string (workaround or fix) + status: [open | resolved | upstream] +rules: + - Open a blocker as soon as friction > 15 min wasted. Close it with a real cause, not "moved on". + - Link to upstream issue / PR / commit when applicable. + - If cause is a bug in a dependency, set status upstream with a pointer to the tracker. + - Entries in English, caveman format (BDR-009): drop articles + filler, fragments OK, technical terms exact. +--- + # Blockers Registry Format: BLK-XXX | Date | Friction | Root cause | Solution | Status --- -## BLK-001 | 2026-05-18 | pnpm not on PATH +## BLK-001 — pnpm not on PATH (2026-05-18) pnpm command not found on shell start. Root: corepack shim broken on Node 20.20.0 (ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING). @@ -13,7 +31,7 @@ Status: resolved. --- -## BLK-002 | 2026-05-18 | Pathology DB empty — pending content review +## BLK-002 — Pathology DB empty — pending content review (2026-05-18) 40-60 equine entries needed; source-cited from Merck Vet Manual, IMAIOS, PubMed, EVJ, WikiVet, LCAO. Client osteo will review post-scaffold. @@ -21,7 +39,7 @@ Status: resolved 2026-05-21 — superseded by hierarchical v2.0 catalog, 26 zone --- -## BLK-003 | 2026-05-19 | Detail-popup zone clicks silently dropped +## BLK-003 — Detail-popup zone clicks silently dropped (2026-05-19) Friction: clicks on head detail SVG zones did nothing. Root: EditorRoute.onZoneClick looked up id in main-SVG bones map only → detail ids (point-*) undefined → early return. @@ -30,7 +48,7 @@ Status: resolved. --- -## BLK-004 | 2026-05-19 | PDF text loop assumed one line per array entry +## BLK-004 — PDF text loop assumed one line per array entry (2026-05-19) Friction: long zone string collided with following lines (pathologies, sévérité, commentaire). Root: pdf-lib maxWidth wraps glyph drawing but caller advanced cursor by `i * 14` based on block index — wrapped lines invisible to layout. @@ -39,7 +57,7 @@ Status: resolved. --- -## BLK-005 | 2026-05-21 | Docker build crash — ERR_UNKNOWN_BUILTIN_MODULE node:sqlite +## BLK-005 — Docker build crash — ERR_UNKNOWN_BUILTIN_MODULE node:sqlite (2026-05-21) Friction: VPS `docker compose up --build -d` crashed on pnpm install (fresh cold build). Root: `node:20-alpine` (Node 20.20.2) cannot load pnpm 11.x — pnpm 11 itself imports `node:sqlite` from `../store/index/lib/index.js`, and `node:sqlite` is a Node 22.13+ built-in. Crash: `ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite`. Local dev was deceptive — host runs Node 20 too, but `pnpm install` never ran on host (lockfile already resolved); `pnpm run typecheck` / `pnpm run test` only spawn child scripts and never load the store-index module. @@ -52,7 +70,7 @@ Status: resolved (commit 990c8e7). --- -## BLK-006 | 2026-10-08 | Docker socket permission denied → no local Supabase stack for Claude +## BLK-006 — Docker socket permission denied → no local Supabase stack for Claude (2026-10-08) Friction: `supabase start` → "permission denied … /var/run/docker.sock"; daemon up (`docker info` client OK), user not in `docker` group. No psql/postgres on host either. Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude). @@ -61,7 +79,7 @@ Status: resolved 2026-10-08 (same day) — user added docker group; `supabase st --- -## BLK-007 | 2026-10-08 | Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE +## BLK-007 — Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE (2026-10-08) Friction: Step 4 verifier + security gate both found every `private.*` function executable by `authenticated` (incl. definer helpers taking a caller-supplied actor: assign_platform_role, insert_sheet_draft). Root: foundation ran `alter default privileges in schema private revoke execute on functions from public`; PostgreSQL adds per-schema defaults on top of the built-in PUBLIC EXECUTE, a per-schema REVOKE cannot remove it. Nothing reachable via API (PostgREST exposes public only, anon no USAGE on private) but the rule "EXECUTE revoked from public" was false. @@ -70,33 +88,33 @@ Status: resolved (commit on feature/step-04-anatomical-sheet-model). --- -## BLK-008 | 2026-10-10 | Schema v2 CHECK migration fails on a database holding a v1 draft +## BLK-008 — Schema v2 CHECK migration fails on a database holding a v1 draft (2026-10-10) Migration 20261010100000 replaces the CHECK with `document_schema_version = 2` without rewriting rows → errors on any DB seeded before 4c (dev only today). Cause: schema bump shipped as constraint change, not as data migration. Solution: before real data, data migration lifting stored documents (add `references: []`, `review_status` defaults) then CHECK; rule from user: incremental non-destructive migrations, never a reset. Documented ANATOMICAL_SHEET_MODEL.md §6. Status: open (no real data yet; treat before Step 7+ persistence of user reports). --- -## BLK-009 | 2026-10-11 | pdf-lib inflates PDF object streams without cap at `PDFDocument.load` (import path) +## BLK-009 — pdf-lib inflates PDF object streams without cap at `PDFDocument.load` (import path) (2026-10-11) Security audit Step 6 (MEDIUM, pre-existing since Step 1 import): `PDFDocument.load` decodes every `/ObjStm` and xref stream eagerly with its own uncapped FlateStream; measured 408 KB PDF → 400 MB in 1.4 s, 468 MB RSS; `MAX_PDF_BYTES` 50 MiB allows ~50 GB. Attachment cap (16 MiB) covers the attachment only. Impact: tab freeze/OOM for the practitioner on a crafted PDF, no code execution. Cannot refuse `/ObjStm` (pdf-lib `save()` emits object streams in our own PDFs). Options: parse in a Web Worker (bounded blast radius), or locate the attachment by scanning bytes without a full load, or a capped custom decoder. pdf-lib 1.17.1 unmaintained since 2021 (LOW in the same audit). Status: MITIGATED on the browser import path 2026-10-11 (60ee712: byte-scan attachment reader, no `PDFDocument.load` on untrusted bytes, export without object streams; ObjStm bomb read in 5 ms, +0.5 MiB RSS). Then 3a6e926: inflater fed in 16 KiB slices (Chromium read-ahead defeated the cancel: 4 GiB bomb +2.2 GB → +192 MB measured), shared 16 MiB candidate budget, bounded endstream search; final loop: candidates sorted by offset, JSON depth pre-scan. Audits ×3 PASS; worst measured costs on crafted files: +192 MB single bomb, ~0.5 s / ≤0.4 GB for 32 failing inflations, ~1 s deep JSON (before the pre-scan). GATE STILL OPEN before any external-user import (BDR-040): Firefox/Safari inflater read-ahead unmeasured (no browser test runner), Worker/server import with time+memory budget, pdf-lib replacement decision (unmaintained), report collection caps on read, `` nesting budget, low-end phone measurement. Plan: docs/development/PDF_IMPORT_HARDENING.md §5. Never close on passing tests alone. -## BLK-010 | 2026-10-14 | Agent worktrees created on a stale base; their cleanup refused by the classifier +## BLK-010 — Agent worktrees created on a stale base; their cleanup refused by the classifier (2026-10-14) Friction: the three `isolation: worktree` forks of R2 started at 605ee7c (an old develop merge), not at the feature branch HEAD 22fea87; each fork noticed and moved its own temp branch (`git reset --hard` / `checkout -B` on the empty worktree, flagged by the classifier as a security warning). After merging their diffs by hand, `git worktree remove --force` + `git branch -d worktree-agent-*` refused by the auto-mode classifier. Root cause: harness side (base commit of the agent worktree), not reproducible from the repo; the removal refusal is the destructive-command policy. Solution: forks briefed with the exact base commit and told to verify `git log -1`; diffs collected uncommitted and copied by literal paths. Leftover: `.claude/worktrees/agent-{a0cefd439bff650a2,a3f684449d0776ad1,af6ebe79b8f742039}` (3.2 GB) + 3 local temp branches at 22fea87 (merged), owner removes them (`git worktree remove --force `, `git branch -d `). Status: resolved 2026-10-14 — after R2 merged into develop (c3f28d8): 66 files checked blob by blob (60 identical to branch history, 6 = fork stub / merged mod lists / lifted `#[ignore]`), no process or agent on them, tip 22fea87 in develop → `git worktree remove --force` ×3 + `gitflow.sh delete` ×3 accepted this time. Harness base-commit cause stays upstream. -## BLK-011 | 2026-10-16 | Stopped-engine message promised "bilan conservé" with draft unsaved; dead "Réessayer" paths +## BLK-011 — Stopped-engine message promised "bilan conservé" with draft unsaved; dead "Réessayer" paths (2026-10-16) Friction: 0279953 picked `core.stopped` from `CoreRuntime.stopped` alone: with sessionStorage full, reload restored older draft, edits lost silently; save banner advised PDF export (needs core). CoreUnavailable, export, import, new report still offered retry after stop; failed recovery below cap = dead end (nothing called `retry()` in editor; canvas button only rebuilt). Root cause: terminal-state message not bound to persistence status (`saveFailed` existed, unread); retry labels audited only on the 8 alerts + canvas the patch touched, not every failure surface; runtime exit from `unavailable` only via explicit `retry()` called by useSheet alone. Solution: 6371523 (BDR-055): `isUnsaved` selector drives variant + copy; CoreStoppedNotice on all core pages; runtime self-restart below cap; FAILED not held; ESLint census. Verifier CONFORME 12/12 (pass 2), security PASS 2 LOW. Status: resolved 2026-10-16. Residuals: saveFailed also on refused archive (over-warns); offline restart never stops (copy on banner); beforeunload only in editor; trap-every-load draft → reload loop; GC finalizer of trapped-instance SheetHandle throws "memory access out of bounds" later (harmless, tests retain handles). -## BLK-012 | 2026-10-17 | Rescue copy not restorable; trapping draft stuck tab; work loss outside editor +## BLK-012 — Rescue copy not restorable; trapping draft stuck tab; work loss outside editor (2026-10-17) Friction: JSON copy (6371523) had no in-app restore (Home picker PDF only; devtools only). Draft trapping `draft.restore` → CoreUnavailable reload each load, New report/Import FAILED, every re-read spent a recovery. beforeunload only in editor; New report / Import replaced bilan in progress (memory or slot) silently. Root cause: copy shipped without restore path (round trip never tested in app); `internal` from draft read treated as transient core failure, no memory of trapping input; guard scoped to one route; session replacement unguarded since MVP. diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 00c3c7f0..cfaedf79 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1,10 +1,30 @@ +--- +format: 2 +type: decisions_registry +entry_prefix: BDR +schema: + id: BDR-XXX + date: YYYY-MM-DD + title: string (<= 80 chars) + decision: string (what was chosen) + why: string (motivation, context) + alternatives: list of strings (what was rejected + why) + status: [proposed | accepted | deprecated | superseded] + supersedes: BDR-XXX (optional) +rules: + - Append-only. Never rewrite past entries - add a new one with status superseded if needed. + - One entry per non-trivial choice. Trivial = reversible in under 10 min with no cross-file impact. + - Capture why more carefully than what - the what rots, the why lasts. + - Entries in English, caveman format (BDR-009): drop articles + filler, fragments OK, technical terms exact. +--- + # Decisions Registry Format: BDR-XXX | Date | Title | Rationale | Alternatives | Status --- -## BDR-001 | 2026-05-18 | React SPA exception for tool app +## BDR-001 — React SPA exception for tool app (2026-05-18) Tool is practitioner-only, no public indexing needed → SPA valid per CLAUDE.md rule. Alt: Next.js SSR rejected — no server, static deploy only. @@ -12,7 +32,7 @@ Status: closed. --- -## BDR-002 | 2026-05-18 | SVG inline via DOMParser, not img/object +## BDR-002 — SVG inline via DOMParser, not img/object (2026-05-18) Inline SVG = full CSS control, pointer-events, data-* access. img/object = sandboxed, no DOM access, no click delegation. @@ -20,7 +40,7 @@ Status: closed. --- -## BDR-003 | 2026-05-18 | PDF attachment via native pdf-lib attach() +## BDR-003 — PDF attachment via native pdf-lib attach() (2026-05-18) Native EmbeddedFiles (afRelationship:Data) = proper PDF spec, survives re-save in Acrobat. Alt: custom metadata → rejected (non-standard, stripped by some viewers). @@ -28,7 +48,7 @@ Status: closed. --- -## BDR-004 | 2026-05-18 | Runtime identity via window.__APP_CONFIG__ +## BDR-004 — Runtime identity via window.__APP_CONFIG__ (2026-05-18) Build-time VITE_APP_* → baked into bundle; runtime injection via entrypoint.sh → no rebuild needed for brand changes. Order: runtime > build-time > defaults. @@ -36,7 +56,7 @@ Status: closed. --- -## BDR-005 | 2026-05-18 | Vertebra picker: region tabs + chip grid +## BDR-005 — Vertebra picker: region tabs + chip grid (2026-05-18) ≥40px touch targets, multi-select, per-region toggle. Alt: flat list → too long for 54 total vertebrae. @@ -44,14 +64,14 @@ Status: closed. --- -## BDR-006 | 2026-05-18 | Drag-reorder: up/down buttons, not DnD +## BDR-006 — Drag-reorder: up/down buttons, not DnD (2026-05-18) DnD on mobile unreliable; ↑/↓ buttons accessible + simple. Status: closed. --- -## BDR-007 | 2026-05-18 | pnpm 11 used instead of pnpm 9 +## BDR-007 — pnpm 11 used instead of pnpm 9 (2026-05-18) pnpm@9 not available on host; corepack resolved 11.1.3. Package.json engine constraint set to >=9 for Docker (Docker uses corepack latest). @@ -59,7 +79,7 @@ Status: closed — deviation accepted. --- -## BDR-008 | 2026-05-19 | PDF page layout — branded heading pattern +## BDR-008 — PDF page layout — branded heading pattern (2026-05-19) 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). @@ -67,7 +87,7 @@ Status: closed. --- -## BDR-009 | 2026-05-20 | Findings JSON keeps snake_case in TS, observation snapshot uses camelCase +## BDR-009 — Findings JSON keeps snake_case in TS, observation snapshot uses camelCase (2026-05-20) 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). @@ -75,7 +95,7 @@ Status: closed. --- -## BDR-010 | 2026-05-20 | Observation findings snapshot labels at selection time +## BDR-010 — Observation findings snapshot labels at selection time (2026-05-20) 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). @@ -83,7 +103,7 @@ Status: closed. --- -## BDR-011 | 2026-05-20 | v1 PDF import — hard-fail with version-specific FR message +## BDR-011 — v1 PDF import — hard-fail with version-specific FR message (2026-05-20) 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). @@ -92,7 +112,7 @@ Status: closed. --- -## BDR-012 | 2026-05-20 | Species auto-discovery via Vite import.meta.glob +## BDR-012 — Species auto-discovery via Vite import.meta.glob (2026-05-20) `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 `, 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. @@ -101,7 +121,7 @@ Status: closed. --- -## BDR-013 | 2026-05-20 | SVG↔JSON zone bridge via fuzzy FR/EN label match +## BDR-013 — SVG↔JSON zone bridge via fuzzy FR/EN label match (2026-05-20) 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. @@ -110,7 +130,7 @@ Status: closed. --- -## BDR-014 | 2026-05-20 | PDF locale = render preference, not Report schema field +## BDR-014 — PDF locale = render preference, not Report schema field (2026-05-20) 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. @@ -119,7 +139,7 @@ Status: closed. --- -## BDR-015 | 2026-05-20 | Typed ImportError discriminant (kind + foundVersion) over localized messages +## BDR-015 — Typed ImportError discriminant (kind + foundVersion) over localized messages (2026-05-20) 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. @@ -128,7 +148,7 @@ Status: closed. --- -## BDR-016 | 2026-05-21 | pathologies.json v2.0 — boolean source of truth, generic vet description_fr purged +## BDR-016 — pathologies.json v2.0 — boolean source of truth, generic vet description_fr purged (2026-05-21) 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. @@ -138,7 +158,7 @@ Status: closed. --- -## BDR-017 | 2026-05-22 | SVG editor: vanilla JS wrap over React rewrite +## BDR-017 — SVG editor: vanilla JS wrap over React rewrite (2026-05-22) 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. @@ -146,7 +166,7 @@ Status: closed. --- -## BDR-020 | 2026-05-22 | Pathology editor: standalone HTML, not React route +## BDR-020 — Pathology editor: standalone HTML, not React route (2026-05-22) 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. @@ -155,7 +175,7 @@ Status: closed. --- -## BDR-021 | 2026-05-22 | Port zoneMatch.ts inline into pathology editor +## BDR-021 — Port zoneMatch.ts inline into pathology editor (2026-05-22) 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. @@ -164,7 +184,7 @@ Status: closed. --- -## BDR-018 | 2026-05-27 | Vertebra picker confirm — target region replaces, other regions union +## BDR-018 — Vertebra picker confirm — target region replaces, other regions union (2026-05-27) 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. @@ -174,7 +194,7 @@ Status: SUPERSEDED by BDR-019 (same session) — additive-union model dropped on --- -## BDR-019 | 2026-05-27 | Vertebra picker = unified full-spine editor, authoritative confirm +## BDR-019 — Vertebra picker = unified full-spine editor, authoritative confirm (2026-05-27) 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. @@ -188,7 +208,7 @@ Status: closed. --- -## BDR-022 | 2026-06-13 | Keep pathology-editor standalone — asymmetry vs svg-editor intentional +## BDR-022 — Keep pathology-editor standalone — asymmetry vs svg-editor intentional (2026-06-13) 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). @@ -200,7 +220,7 @@ Status: closed. --- -## BDR-023 | 2026-10-08 | Monorepo: apps/app + pnpm workspace, packages extracted on demand only +## BDR-023 — Monorepo: apps/app + pnpm workspace, packages extracted on demand only (2026-10-08) 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. @@ -209,7 +229,7 @@ Status: closed (user validated 2026-10-08). --- -## BDR-024 | 2026-10-08 | Node 24 LTS + pnpm 10.13.1 pinned, engine-strict +## BDR-024 — Node 24 LTS + pnpm 10.13.1 pinned, engine-strict (2026-10-08) 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. @@ -219,7 +239,7 @@ Status: closed. --- -## BDR-025 | 2026-10-08 | Design records live in docs/history/superpowers, not docs/superpowers +## BDR-025 — Design records live in docs/history/superpowers, not docs/superpowers (2026-10-08) 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. @@ -227,7 +247,7 @@ Status: closed. --- -## BDR-026 | 2026-10-08 | platform_role enum = owner/admin/moderator/support only; professional statuses excluded +## BDR-026 — platform_role enum = owner/admin/moderator/support only; professional statuses excluded (2026-10-08) 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. @@ -235,7 +255,7 @@ Status: closed (user instruction), name `profile_roles` open to rename if user p --- -## BDR-027 | 2026-10-08 | Role writes RPC-only + audited; column-level GRANT protects profiles.active / phone_verified_at +## BDR-027 — Role writes RPC-only + audited; column-level GRANT protects profiles.active / phone_verified_at (2026-10-08) 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`. @@ -243,7 +263,7 @@ Status: closed. --- -## BDR-028 | 2026-10-08 | pgTAP single source of SQL tests; PGlite runner in vitest beside `supabase test db` +## BDR-028 — pgTAP single source of SQL tests; PGlite runner in vitest beside `supabase test db` (2026-10-08) 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). @@ -251,14 +271,14 @@ Status: closed. --- -## BDR-029 | 2026-10-08 | database.types.ts hand-written in `supabase gen types` format + schema↔types test +## BDR-029 — database.types.ts hand-written in `supabase gen types` format + schema↔types test (2026-10-08) 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 +## BDR-030 — Step 4 split: model + persistence now, importer → official equine DRAFT next (2026-10-08) 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). @@ -266,7 +286,7 @@ Status: closed (plan note added under Step 4). --- -## BDR-031 | 2026-10-08 | Canonical sheet document shape (schema_version 1) +## BDR-031 — Canonical sheet document shape (schema_version 1) (2026-10-08) 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. @@ -274,7 +294,7 @@ Status: closed; category kind `observation` vs report Observation collision (C7) --- -## BDR-032 | 2026-10-08 | Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets +## BDR-032 — Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets (2026-10-08) 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 `.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). @@ -282,7 +302,7 @@ Status: closed; names (`anatomical_sheet_assets`, storage layout, official owner --- -## BDR-033 | 2026-10-09 | User decisions on the Step 4 open points (sheets: follow, verification, versions, official, naming, server validation, erasure) +## BDR-033 — User decisions on the Step 4 open points (sheets: follow, verification, versions, official, naming, server validation, erasure) (2026-10-09) 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. @@ -291,7 +311,7 @@ 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 +## BDR-034 — Equine import = generated seed, draft only; assets content-addressed in a private bucket read through the sheet (2026-10-09) 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, `.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). @@ -299,7 +319,7 @@ Status: closed; publication of v1 = explicit user decision after report review. --- -## BDR-035 | 2026-10-09 | Docker resources prefixed `faunosteo_` (multi-SaaS VPS) +## BDR-035 — Docker resources prefixed `faunosteo_` (multi-SaaS VPS) (2026-10-09) User rule: every Faunosteo Docker resource (container, network, volume, image, future worker/self-hosted Supabase) named `faunosteo_*` when configurable → cohabitation on one VPS without collision. Applied: compose `name: faunosteo` + `container_name: faunosteo_app` (was `faunosteo-web`, stateless, no volume → rename safe). Supabase CLI hard-codes `supabase__` → suffix `faunosteo`, documented limit, no wrapper. Rule for future persistent volumes: keep volume name across renames. Alt rejected: wrapping `supabase start` to rename containers (fragile, breaks CLI status/stop). @@ -307,7 +327,7 @@ Status: closed (DEPLOY.md "Docker resource naming", SUPABASE.md §3, CLAUDE.md). --- -## BDR-036 | 2026-10-10 | Sheet document schema v2 + curation changeset as data (Step 4c) +## BDR-036 — Sheet document schema v2 + curation changeset as data (Step 4c) (2026-10-10) Schema v2: document `references` registry (id, type, citation, url|doi), `reference_ids` + `review_status` (inherited|reviewed|to_confirm) on finding nodes/categories/annotations, `count_range` on vertebral regions; rules `reference.id.duplicate`, `finding.reference.missing`, `region.count_range.invalid` on TS + SQL (jsonpath `**` descent); CHECK `document_schema_version = 2`. Curation = authored JSON changeset (`curation/changes.json`: CHG-nnn, level A|B|C, kind, FR/EN title, rationale, reference_ids, priority, question required for C; ops set/rename/add/remove/move/cite over string targets) applied by a deterministic pipeline to the 4b baseline → `draft/` (document, one cleaned SVG, head view = view_box crop, CHANGELOG with before/after per elementary edit, 10-section REVIEW-REPORT, `review/annotations-.svg` before/after drawings, converging seed). Legacy baseline kept generated under `legacy-import/`, `v1/` removed. Nothing publishes. Alt rejected: editing `document.json` by hand (no traceability, golden test); TS code per change (reviewers read data, not code); per-node inline sources (792 copies → registry + ids); PNG renders in git (operator artifact, renderer-dependent). @@ -315,14 +335,14 @@ Status: closed; content awaits professional review (REVIEW-REPORT §10, 9 questi --- -## BDR-037 | 2026-10-10 | Step 4c validated: reference draft, review semantics, migration rule +## BDR-037 — Step 4c validated: reference draft, review semantics, migration rule (2026-10-10) User decisions: curated equine draft = reference draft of the app until published (no publication without professional review); technical integrity ≠ medical validation (`inherited` / `reviewed` / `to_confirm` stay visible, REVIEW-REPORT the hand-off doc for the osteopath, 11 open questions → next changeset); future schema changes = incremental non-destructive migrations (BLK-008); legal scope text re-read on consolidated Légifrance texts before publication; head view preserved as crop, per-view assets still possible. Docker `faunosteo_` rule permanent; `.env.example` change documented in DEPLOY.md (file denied to Claude). SaaS development continues without waiting for medical validation. Status: closed. --- -## BDR-038 | 2026-10-10 | Step 5: app on the canonical sheet — bundled sheet, layer renderer, Report v3, migration map +## BDR-038 — Step 5: app on the canonical sheet — bundled sheet, layer renderer, Report v3, migration map (2026-10-10) Sheet source: `SheetProvider` interface; Step 5 implementation = Vite virtual module `virtual:faunosteo-sheet` built from the seed draft (`vite/sheet-bundle.ts`), mode `SHEET_BUNDLE=draft|none`, default draft for dev server, none for builds/CI/Docker (`--build-arg SHEET_BUNDLE=draft` = explicit preview) → unvalidated draft never ships by accident (D2). Markers: pure renderer `@faunosteo/anatomy/render` (element tree, no DOM) reproduces legacy look (hitbox r + twin r−12, opacities 0.65/0.5, spine 0.3, trigger 0.06 dashed); colours = document data (`categories[].color`, additive `annotations[].color` for the head shades, schema_version stays 2 for additive optional fields); same renderer feeds `draft/review/app-.svg` for visual checks. Report v3 in packages/domain: `(annotationId, viewId)` zones with label snapshots, `(findingZoneId, path)` findings, severity codes, `sheet {sheetId, versionId|null, documentSha256}`, `unresolved: true` for what migration cannot place, `localAnnotations: []` reserved. Migration map generated by the pipeline from applier records (replay renames/moves/removals + unique re-homing): 792 nodes → 571/180/7/34. Interaction = pure service + reducers (BDR-019 kept); store = v3 + persistence adapter (v2 draft migrated on restore). D4 applied: registry, matchers, SVG parser, editors, pathology-editor, public species assets deleted; legacy sources moved to `supabase/seed/.../legacy-sources/` (importer input). Alt rejected: copying the draft into apps/app (duplication, drift); runtime fetch of `/sheets/*.json` (still public, no gain); UUID annotation ids (BDR-031); converting v3→v2 for attachments (lossy); per-view colour table in the app (horse knowledge in generic code). @@ -330,7 +350,7 @@ Status: closed; awaiting user validation of Step 5. --- -## BDR-039 | 2026-10-11 | Step 6: autonomous PDF archives — lean-document snapshot, envelope v1, archived branding + labels, explicit rebase +## BDR-039 — Step 6: autonomous PDF archives — lean-document snapshot, envelope v1, archived branding + labels, explicit rebase (2026-10-11) User-validated design (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II). Attachment = envelope v1 `{format, envelopeVersion, exportedAt, locale, report v3, sheetSnapshot, branding, labels}` in one `osteo-report.json`, SVG inline as text. Snapshot = `{status, ref, document, assets}` where document = valid lean `AnatomicalSheetDocument` (all views/annotations/categories/regions, finding zones kept by id, trees pruned to used paths with ancestor labels, references emptied) → reuses sheet index, layer renderer, 21 integrity rules; no dedicated schema. Branding (logos base64/svg, credits, URLs) + label dict (fr+en) archived so future logo/wording changes never alter a re-render (user D7 adjustment). Engine `packages/pdf`: explicit inputs `{report, sheet, branding, labels, locale, rasterizer, exportedAt}`, no DOM lib, xmldom composition promoted from curation app-review, Rasterizer adapter (browser Image/canvas; resvg devDep for tests), per-view/per-logo degradation, export-side validation (caps, integrity, sheet invariant). Read = layered: report first (v3/v2 existing dispatch), envelope metadata tolerant, snapshot strict → `snapshotRejected` enum, report never lost; `attachment_stripped` via Info.Keywords stamp. Session: imported archive kept immutable (`osteo:archive`), working copy rebased explicitly on the loaded sheet (`rebaseReportOnSheet`, unresolved flags + labels from archived snapshot) (user D8 adjustment); re-export of the kept archive = technical support only, UX submitted after step. No CLI, no page change, no original v2 JSON re-embedded. Alt rejected: dedicated SheetSnapshotSchema (rewrites lookups, loses integrity rules); separate embedded files per asset (first-EmbeddedFile reader, stripping risk); pruning views/annotations (saves ~0 KB, breaks trigger titles); snapshot discarded on import (user: keep for faithful re-read); crypto hash check of assets (self-referential; sha copied from catalog manifest as provenance pointer instead). @@ -338,171 +358,171 @@ Status: closed (Step 6 validated by user 2026-10-11; D8 finalised in BDR-040). --- -## BDR-040 | 2026-10-11 | Step 6 closure: no "re-export the original archive" button, visible rebase, BLK-009 gate +## BDR-040 — Step 6 closure: no "re-export the original archive" button, visible rebase, BLK-009 gate (2026-10-11) User decisions after manual validation (logos and picker text confirmed OK on their side; Step 6 VALIDATED). (1) Re-export of the imported archive from the UI REFUSED permanently: the practitioner already holds the original PDF; no second button, no dedicated UX flow. Keep the archived snapshot, its integrity and the autonomy tests (engine `exportFromEnvelope` stays as the proof + future server use); the UI exports only the open working report. Do not propose this feature again. (2) Rebase on draft restore shown to the user (`editor.draft_rebased`) approved; import messages approved on principle with an explicit "full restoration" vs "partial recovery" headline. (3) BLK-009 treated now: byte-scan attachment extraction without pdf-lib load on import + export without object streams; remaining risks (worker/server import, pdf-lib replacement, read caps) stay an explicit BLOCKER gate before any external user import; never declared solved by passing tests alone. Alt rejected: a re-export action on the home screen after import (same objection); a toast system for import feedback (no component, alert pattern kept). Status: closed. -## BDR-041 | 2026-10-11 | Step 7 scope: zustand auth store (no TanStack), professional fields on profiles, MFA = documented gap, config-driven OAuth buttons, local tool stays open +## BDR-041 — Step 7 scope: zustand auth store (no TanStack), professional fields on profiles, MFA = documented gap, config-driven OAuth buttons, local tool stays open (2026-10-11) Step 7 brief (UX validated by user with external mockups, not versioned). Choices: (1) no TanStack Query: one profile read/update per section, zustand `authStore` + `localeSync` enough; query layer deferred to the first list screens. (2) `practice_name`, `professional_title`, `siret` added to `profiles` as declared free text (CHECKs, column grants), verification stays the Professional Verification domain (Step 11). (3) MFA: foundations had TOTP disabled, no `has_mfa()`, no admin table → TOTP enabled server-side, enforcement + enrolment UI documented as gap (IDENTITY.md §4), Security section shows a note, no fake UI. (4) OAuth buttons listed by `APP_AUTH_PROVIDERS` / `VITE_AUTH_PROVIDERS`; config.toml providers read `env()` ids, `enabled = false` until ids exist; `platform_invitations` not written. (5) Local tool routes untouched + unauthenticated (`LocalToolShell`, catch-all), Home header entry only when Supabase configured; `/app` guard sends to `/login?next=` with same-origin check. (6) Account locale wins over device locale once per sign-in; switches while signed in persist to `profiles.locale`. Alt rejected: TanStack now (YAGNI); MFA enrolment screen (unvalidated UI, nothing to protect); `/register` naming (`/signup` kept); nested `