141 Commits
Author SHA1 Message Date
bchanot f8d9425d34 chore(memory): TODO 6.10 + journal — release/0.2.0 prepped, awaiting go 2026-10-11 17:34:19 +02:00
bchanot dac75ab06c chore(release): 0.2.0 — version.txt + CHANGELOG 2026-10-11 17:33:59 +02:00
bchanot c746952d7f Merge feature/step-06-pdf-archives into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-11 17:32:15 +02:00
bchanot 62b2b9d86a fix(pdf): candidates sorted by data offset, JSON depth pre-scan before parse, budget wording; chore(memory): BLK-009 mitigated with gate, EVAL-014, journal, TODO, CLAUDE.md import notes 2026-10-11 17:31:07 +02:00
bchanot 3a6e92625a fix(pdf): inflater fed in 16 KiB slices (browser memory bound), shared 16 MiB candidate budget, monotonic bounded endstream search, JSON object pre-check 2026-10-11 17:08:56 +02:00
bchanot 6adc38b027 docs: hardening §4 commit pointer 2026-10-11 16:42:46 +02:00
bchanot 60ee71208f fix(pdf): bounded attachment extraction by byte scan — no pdf-lib parse on import, export without object streams (BLK-009) 2026-10-11 16:42:45 +02:00
bchanot 62b8a43e09 feat(home): import messages open with a full-restoration or partial-recovery headline; BDR-040 recorded 2026-10-11 16:31:37 +02:00
bchanot de2bd0437e chore(memory): BLK-009 attachment scan contract 2026-10-11 16:29:15 +02:00
bchanot 6688c3c60e chore(memory): journal + TODO 6.8 after the first manual-test round 2026-10-11 16:16:14 +02:00
bchanot e8f1734424 feat(editor): tell the practitioner when a restored draft was rebased on a different sheet 2026-10-11 16:15:13 +02:00
bchanot 5ed4a4b620 docs: PDF import hardening analysis (BLK-009) — byte-scan reader and object-stream-free export now, worker and parser replacement before external users 2026-10-11 16:12:22 +02:00
bchanot 293a6e0b36 fix(pdf): bundle the branding assets into the app (no fetch at export), export returns its warnings and the editor reports missing elements 2026-10-11 16:09:39 +02:00
bchanot 80e95ca61d docs(pdf): PNG budget wording (pixel cap bounds decoder memory); chore(memory): EVAL-013, journal, TODO 6.6 closed and 6.8 awaiting user 2026-10-11 15:06:12 +02:00
bchanot cb95627a11 fix(pdf): PNG gate inflates IDAT natively against the exact raw size, validates IHDR fields, refuses zero dimensions and interlace (UPNG inflateRaw spin) 2026-10-11 14:52:03 +02:00
bchanot 0ceb357b18 fix(pdf): PNG chunk allowlist and mandatory empty IEND — text and profile chunks refused (UPNG nextZero spin) 2026-10-11 14:29:56 +02:00
bchanot 3a26c61119 fix(pdf): link URIs as ASCII hex (readable by poppler), PNG budget walks the chunk list (second IHDR and APNG refused) 2026-10-11 14:14:10 +02:00
bchanot dfd04e0bd7 chore(memory): step 6 security fix 2 contract 2026-10-11 14:07:19 +02:00
bchanot 1cc92f664b chore(memory): security-fix contract — oracle of criterion 1 corrected, evidence recorded 2026-10-11 13:58:26 +02:00
bchanot 1f417b21fd fix(pdf): security hardening — hex-encoded link URIs, strict branding URL schema, branding and labels re-validated at export, PNG dimension budget, CSS escape and parenthesis rules in the sanitiser, finite raster size, file size checked before read 2026-10-11 13:54:18 +02:00
bchanot 4930704d8a chore(memory): BLK-009 pdf-lib uncapped object-stream inflation on load 2026-10-11 13:43:30 +02:00
bchanot 51eb7da4a3 chore(memory): step 6 security fix contract 2026-10-11 13:43:06 +02:00
bchanot f2a64bcb0a chore(memory): step 6 verify contract — oracles of criteria 6/7 fixed, scope widened, deleted tests authorised with replacements, docker evidence 2026-10-11 13:40:55 +02:00
bchanot 83115b484d docs: CLAUDE.md on the Step 6 pipeline (architecture, conventions, folder map); TODO 6.4-6.5; LRN-046 2026-10-11 13:33:59 +02:00
bchanot 9bd5173a9c feat(app): export and import through @faunosteo/pdf — snapshot, archived branding and labels, browser rasterizer, imported archive kept in session, explicit rebase with messages; legacy PDF modules removed 2026-10-11 13:32:14 +02:00
bchanot 20dafc0b00 chore(memory): step 6 whole-step verification contract 2026-10-11 13:12:37 +02:00
bchanot 9e681232cf docs: step 6 sync — README layout and docs list, WORKSPACE package rule, DEPLOY rollback note, CHANGELOG entry 2026-10-11 13:11:44 +02:00
bchanot ad48758f8c docs(pdf): PDF-FORMAT.md written for real — pages, archive envelope v1, snapshot, layered reading, rebase, limits, compare tool 2026-10-11 13:11:04 +02:00
bchanot c17956031d feat(pdf): @faunosteo/pdf engine — explicit inputs, envelope v1 attachment, layered reader, xmldom composition, allowlist SVG sanitiser, WinAnsi guard, rasterizer adapter; goldens reproduced 2026-10-11 13:09:17 +02:00
bchanot e7419cb4cb chore(memory): TODO step 6 phases 0-2 done 2026-10-11 12:31:15 +02:00
bchanot cdc0943f35 feat(domain): archive contracts — sheet snapshot (lean document, caps, integrity), envelope v1 layered reader, branding and label schemas, report rebase, sheet index moved from the app; bundle carries asset hashes 2026-10-11 12:30:57 +02:00
bchanot 8b86b926c8 test(pdf): step 6 phase 0 freeze — demo report, bare v3 PDF, 39 goldens (text, images, links, views) and route characterisation tests 2026-10-11 12:13:36 +02:00
bchanot 694092610d feat(anatomy): composeViewSvg with tree-level highlight and halo, review drawing on the shared composer 2026-10-11 12:05:56 +02:00
bchanot 4c6c5151f8 docs: step 6 implementation contract (types, envelope v1, read, rebase, session, messages, goldens) + BDR-039 2026-10-11 11:59:08 +02:00
bchanot 72f19521d3 Merge chore/step-06-pdf-archive-analysis into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-11 11:52:14 +02:00
bchanot 81342009fe docs: step 6 autonomous PDF archives analysis and plan (snapshot content, envelope v1, compatibility, limits, tests) 2026-10-10 23:17:23 +02:00
bchanot 072d761261 chore(memory): LRN-045 permanent will-change blurs composited text
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-10 22:43:11 +02:00
bchanot 91131713b1 Merge feature/step-05-app-on-canonical-sheet into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-10 22:16:24 +02:00
bchanot 271a8b6515 chore(memory): journal + TODO 5.11/5.12 + contract — hotfix findings picker blur, Step 5 validated 2026-10-10 22:16:18 +02:00
bchanot 1f0b710b6e fix(editor): drop the permanent will-change on the findings list, its text blurred on screen 2026-10-10 22:15:09 +02:00
bchanot 9cedaccbb3 chore(memory): EVAL-012, LRN-044, journal, TODO 5.8-5.10 closed 2026-10-10 16:06:00 +02:00
bchanot 388e209ea9 fix(pdf): report:compare --diff follows the privacy default, generic reason on a malformed attachment, Unicode control and format characters escaped, regular files only 2026-10-10 16:01:12 +02:00
bchanot b1b3e4927e fix(pdf,tests): report:compare escapes control characters, prints names and free text only with --full, stats before read, missing file as a per-file failure; inferRegionCode regression test; import.ts JSDoc reattached 2026-10-10 15:53:07 +02:00
bchanot dc78a00835 feat(pdf): archive check tool pnpm report:compare (attachment vs its v3 reading, unresolved items flagged, --diff/--summary/--identity); readAttachedDocument split out of extractReportJson; stale scaffold:species script removed; docs 2026-10-10 15:44:20 +02:00
bchanot 1e0491f3bc test(anatomy,app): every legacy catalog leaf (612) and annotation (27) through the v2 to v3 migration against the draft document, the sheet index and a PDF roundtrip 2026-10-10 15:44:20 +02:00
bchanot e7f4167ada fix(domain,app): own-key lookups for untrusted ids in the v2 migration, attachment and PDF size caps; EVAL-011, journal, TODO 2026-10-10 12:23:03 +02:00
bchanot 17a6d9b323 test(app): former PDF, observation card, route and schema assertions restored on v3; foreign JSON attachment reported as no_attachment; doc counts 2026-10-10 12:21:19 +02:00
bchanot 06a2e86f3c test: replacement coverage for the deleted legacy suites (v3 schema rejections, appointment kinds, i18n keys and placeholders, pickLocaleLabel, region mapping, new report route); importer comment 2026-10-10 12:06:59 +02:00
bchanot 09d8b01a54 fix(app): editor route split into dialogs and pickers components, canvas without lint suppression, findings picker coverage restored; golden test pins every generated draft file; stale doc lines 2026-10-10 11:55:57 +02:00
bchanot 0476276a8f docs(chore): step 5 — annotation rendering contract, CLAUDE.md map and conventions, README, DEPLOY SHEET_BUNDLE, PDF format v3, spec §6 migration map, plan/changelog/strategy notes; BDR-038, LRN-043, TODO 2026-10-10 11:41:55 +02:00
bchanot ce2ec26112 feat(app): application on the canonical sheet — report v3 store with v2 draft migration, bundled SheetProvider (SHEET_BUNDLE), annotation layer rendered from the document, zone interaction service, pickers and cards on the sheet index, PDF v3 export with v2 archive import; legacy registry, matchers, editors and assets removed 2026-10-10 11:36:14 +02:00
bchanot 0a17e390cf feat(anatomy): report migration map and sheet reference generated by the pipeline, pure annotation-layer renderer (legacy marker look) shared with the app, app review drawings, marker colours as document data 2026-10-10 11:17:34 +02:00
bchanot 70bf992017 feat(domain): report document v3 (annotation ids, sheet ref, severity codes, unresolved findings), v2 schema as input, v2→v3 migration with map; annotation colour override 2026-10-10 11:11:25 +02:00
bchanot cce0bdcd9c test(app): freeze golden v2 PDFs exported by the current pipeline (step 5.0, synthetic reports) 2026-10-10 11:06:53 +02:00
bchanot 199e328298 Merge chore/step-05-migration-analysis into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-10 11:04:23 +02:00
bchanot 734c0d91fd docs: step 5 migration analysis (report v3, adapter + migration map, sheet provider, annotation layer, service/store split, risks, tests, decisions D1–D8); TODO plan; plan note 2026-10-10 10:54:04 +02:00
bchanot ce3d9634b3 Merge feature/step-04c-equine-curation into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-10 10:33:04 +02:00
bchanot 866e84f75b docs(chore): step 4c validated — head view check, migration limit BLK-008, review semantics, .env.example expected change, BDR-037, TODO follow-up 2026-10-10 10:32:57 +02:00
bchanot c0c17fcf5f feat(supabase): SQL gate reports non-http(s) reference urls (reference.url.scheme), pgTAP 008 cases; EVAL-010, journal, TODO 4c 2026-10-10 10:10:45 +02:00
bchanot 34be7e23df docs: schema v2 migration listed, one cleaned asset in the draft, curation file list; CHG-021 rationale names no uncited author 2026-10-10 10:05:29 +02:00
bchanot ed3c70df59 fix(species): JSAVA 2018 citation completed (Le Roux & Carstens, DOI), access dates on undated web references; DEPLOY.md log path uses faunosteo_app 2026-10-10 09:57:21 +02:00
bchanot 6034909674 fix(anatomy): B/C changes leave every touched finding and annotation at to_confirm (applier rule, reviewed refused), typed test reads, docs numbers 2026-10-10 09:03:00 +02:00
bchanot 37550c29a5 fix(species): B-level head changes marked to_confirm instead of reviewed, question on the legal scope text 2026-10-10 02:02:16 +02:00
bchanot 55bd83d09c chore(memory): BDR-036 schema v2 + changeset, LRN-042 authoring and SVG audit, journal, TODO 4c 2026-10-10 01:53:12 +02:00
bchanot c8ebcde913 docs: step 4c curation layout, review drawings, plan and changelog entries 2026-10-10 01:53:11 +02:00
bchanot 4ba937b02f feat(species): equine curation changeset — 44 research-backed changes, 48 references, draft regenerated (811 nodes, carpus zone, 9 points relocated) 2026-10-10 01:53:10 +02:00
bchanot 1a96a1555c feat(anatomy): before/after review drawings per view, questions of every level in the report, tests on the real changeset 2026-10-10 01:53:10 +02:00
bchanot 6870d87910 feat(anatomy): curation pipeline — changeset schema, applier with before/after records, cleaned single asset, draft seed, changelog + review report generators; seed layout legacy-import/curation/draft 2026-10-09 16:50:08 +02:00
bchanot 3dbbfdf1df feat(domain): sheet document schema v2 — references registry, review_status, vertebral count_range; SQL gate + pgTAP 008 2026-10-09 16:30:58 +02:00
bchanot 6c5b2b7754 chore(docker): faunosteo_ naming convention for Docker resources (compose project + container), documented CLI limit 2026-10-09 16:26:06 +02:00
bchanot 584b165bfa Merge feature/step-04b-equine-import into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-09 16:13:50 +02:00
bchanot dee4ce43d9 fix(supabase): confirmed uploads gate asset reads (hash claim), seeds-listed test, Dockerfile workspace manifests; importer declares every authored label, real in=out control 2026-10-09 00:50:36 +02:00
bchanot bbfb8d6203 chore(chore): capitalize Step 4b — BDR-034, LRN-041, journal, TODO 2026-10-09 00:39:44 +02:00
bchanot e5a0445b19 test(supabase): equine seed + storage pgTAP on both engines; docs for Step 4b; upload script resolves from caller dir 2026-10-09 00:38:49 +02:00
bchanot 52bfc11553 feat(domain): equine legacy importer (packages/anatomy) + generated official equine sheet seed as draft 2026-10-09 00:38:48 +02:00
bchanot f4682cdba5 feat(supabase): sheet asset Storage bucket + read policy through the sheet, shim storage tables, seeds in the PGlite harness, upload script 2026-10-09 00:28:34 +02:00
bchanot 12f0b21fdf feat(domain): finding kind observation → consultation_reason; Step 4 business decisions in spec + memory (BDR-033) 2026-10-09 00:24:22 +02:00
bchanot 1cc70c3589 Merge feature/step-04-anatomical-sheet-model into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-09 00:23:08 +02:00
bchanot 5d32bed829 docs(docs): sheet model spec matches the hardened code (counter, SQL-only codes, census, migration list) 2026-10-09 00:05:39 +02:00
bchanot d3fa65af29 fix(supabase): revoke PUBLIC EXECUTE on private helpers, audited visibility RPC, input caps, authz-first RPCs, +32 pgTAP checks 2026-10-08 23:59:39 +02:00
bchanot 6966c54a2e docs(docs): Step 4 sheet model in CLAUDE.md, SUPABASE.md, WORKSPACE, README, plan note, changelog 2026-10-08 23:45:01 +02:00
bchanot 8cac8b1a68 feat(supabase): regenerated types, row aliases, publishSheetVersion gate, schema test 2026-10-08 23:42:44 +02:00
bchanot f4ceaf68f9 feat(supabase): anatomical sheets, immutable versions, assets, lifecycle RPCs, RLS + pgTAP 2026-10-08 23:42:43 +02:00
bchanot 36812f4625 feat(domain): canonical anatomical sheet document, integrity rules, tests 2026-10-08 23:42:42 +02:00
bchanot aea8902711 docs(docs): anatomical sheet model spec (Step 4) + TODO plan 2026-10-08 23:42:42 +02:00
bchanot da444309ae Merge chore/supabase-cli-gitignore into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-08 23:19:14 +02:00
bchanot 7891e36bdb chore(chore): mark Step 3 validated in TODO + journal 2026-10-08 23:19:08 +02:00
bchanot e5f81a4ebe chore(supabase): ignore Supabase CLI local state (.branches, .temp) 2026-10-08 23:15:54 +02:00
bchanot 7ea0b1f905 Merge feature/step-03-supabase-foundation into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
2026-10-08 23:15:14 +02:00
bchanot fcdcfb53b2 docs(docs): real-stack verification notes; BLK-006 resolved, EVAL-007, LRN-037 2026-10-08 23:04:22 +02:00
bchanot 8b233e5cf0 chore(supabase): adopt CLI-generated database.types.ts; db:types scripts pipe through prettier 2026-10-08 23:04:21 +02:00
bchanot a2e33fe4a2 test(supabase): make pgTAP counts seed-agnostic (real stack carries seed accounts) 2026-10-08 23:04:20 +02:00
bchanot d5a5a720a1 chore(chore): capitalize step 3 — BDR-026..029, LRN-035/036, BLK-006, EVAL-006, journal, TODO 2026-10-08 22:48:17 +02:00
bchanot 1e7d0327cc fix(supabase): no USAGE on schema private for anon; pin it and RPC EXECUTE in pgTAP 2026-10-08 22:47:20 +02:00
bchanot 1dd45a3109 docs(docs): SUPABASE.md runbook + CLAUDE/README/DEPLOY/WORKSPACE updated for the Supabase foundation 2026-10-08 22:46:38 +02:00
bchanot 5511a2158a ci(ci): supabase job — start stack, pgTAP on the real image, generated types diff 2026-10-08 22:46:37 +02:00
bchanot ab04b2e43d style(supabase): prettier pass on the new TypeScript files 2026-10-08 22:46:37 +02:00
bchanot d239374d81 feat(app): optional Supabase connection in runtime config + lazy typed client
- env.ts: supabase: SupabaseConnection | null resolved from env.js
  (supabaseUrl/supabaseAnonKey), VITE_SUPABASE_*, else null; half config refused
- lib/supabase.ts: getSupabaseClient() null when unconfigured, one client per URL
- entrypoint.sh writes the two public values; .env.example placeholders
- Dockerfile copies packages/supabase manifest for the install layer
- no UI change; 7 new tests (278 app)
2026-10-08 22:43:18 +02:00
bchanot ce76c6597a feat(supabase): @faunosteo/supabase package with PGlite harness and typed client
- tests/db: PGlite (PostgreSQL 17 WASM) applies the Supabase shim + migrations and
  runs supabase/tests/*.sql through pgTAP without Docker
- schema-types test pins tables, columns, enums, RPC args, RLS-on, no using(true)
- database.types.ts in supabase gen types format; createBrowserClient (PKCE)
- Supabase CLI pinned as root devDependency; db:* root scripts
2026-10-08 22:20:54 +02:00
bchanot 2d5ff0c33e feat(supabase): foundation migrations (audit, profiles, platform roles) + pgTAP suite
- schemas private/audit, set_updated_at, append-only audit.audit_logs, private.log_event
- profiles created by auth.users trigger; own-row RLS; column-level UPDATE grant
- platform_role enum (owner/admin/moderator/support), profile_roles history table,
  is_platform_* helpers, grant/revoke RPCs audited; writes only via RPC
- config.toml (public schema only, strong passwords, no edge runtime), local seed
- 79 pgTAP checks: allowed and denied paths for every policy
2026-10-08 22:20:54 +02:00
bchanot 62c5a3ac86 chore(chore): plan step 3 Supabase foundation in TODO 2026-10-08 22:06:37 +02:00
bchanot d9a7bd70b8 chore(chore): refresh gitflow post-commit/post-merge hooks (fail-closed autopush)
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
2026-10-08 22:06:19 +02:00
bchanot ab8451210b chore(chore): capitalize step 2 decisions, learning and journal
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
2026-10-08 21:57:05 +02:00
bchanot 49596022c9 Merge feature/step-02-monorepo-workspace into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
2026-10-08 21:56:42 +02:00
bchanot 02052f3622 docs(docs): restore 2026-05 design specs and plans under docs/history
Purged from docs/superpowers by the gitflow finish of step 1 (BDR-065);
that path is purged at every finish, so the records live under
docs/history/superpowers/ instead. References updated.
2026-10-08 21:51:13 +02:00
bchanot 8673475293 chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates
dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and
pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager,
root devDependency, engine-strict). Dockerfile builds @faunosteo/app on
node:24-alpine and copies apps/app/dist; nginx and runtime config
unchanged. CI workflow for Gitea Actions. packages/ reserved (README only).
Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan.
271/271 tests, typecheck, lint, build green from the root.
2026-10-08 21:51:13 +02:00
bchanot c8d48ab4cc Merge feature/step-01-characterisation-tests into develop 2026-10-08 21:41:52 +02:00
bchanot 8f217d8103 chore: purge transient planning artifacts (BDR-065) 2026-10-08 21:41:51 +02:00
bchanot e9047a99d2 chore(chore): capitalize step 0-1 learnings, eval and journal 2026-10-08 21:41:40 +02:00
bchanot e84cbaf884 test(tests): add characterisation suite of the current app (step 1)
Seven files, 91 cases, on the real SVGs and catalog: catalog invariants,
SVG <-> catalog mapping table, pathology-editor matcher parity, click chain
through the DOM, full PDF export/import, schema and persistence, i18n and
species. Two golden Report v2 fixtures. No application file changed.
Report: docs/development/CHARACTERIZATION_REPORT.md. 271/271 green.
2026-10-08 21:41:39 +02:00
bchanot b0cce2cd8c docs(docs): add SaaS implementation plan and architecture docs (step 0)
Eight documents under docs/development/ confronting the approved business
architecture with the audited code: 27-step plan, repository migration map,
domain map, frontend/backend architecture, migration and test strategy,
open questions. Reference document placed at the repository root.
2026-10-08 21:41:39 +02:00
bastien 2ae1e48b7e chore(chore): refresh gitflow hooks (gitleaks backstop, auto-push, ref protection)
pre-commit gains a gitleaks secret scan on every branch, a per-repo
gitflow.protect opt-out, and exempts .githooks/** like .claude/**.
Adds the generated post-commit, post-merge and reference-transaction
hooks from the gitflow lib.
2026-10-06 23:53:24 +02:00
bastien 021569f44c Merge chore/anatomical-audit into develop 2026-10-06 23:52:45 +02:00
bastien e471d41c6b docs(docs): add anatomical audit of existing SVG, catalog and report systems
Read-only technical audit before the SaaS redesign: 13 reports,
a logical anatomical-sheet JSON built from real horse data, verbatim
copies of the 52 relevant source files, and a self-contained ZIP.
2026-10-06 23:51:35 +02:00
Bastien Chanot 83e40af99b Merge chore/tour-2026-07-12 into develop 2026-07-18 01:18:19 +02:00
Bastien Chanot cbf62ff5c2 docs(tour): mark BUGS-FOUND B-1..B-6 fixed with commit refs 2026-07-12 17:54:23 +02:00
Bastien Chanot d702e9fb45 chore(pdf): decompose addObservationPage (context object + sub-functions) 2026-07-12 17:52:50 +02:00
Bastien Chanot fe307e1d8d chore(editor): split onZoneClick into per-behavior handlers 2026-07-12 17:05:32 +02:00
Bastien Chanot 0ec1b27d1f chore(pdf): extract shared render constants module 2026-07-12 17:02:45 +02:00
Bastien Chanot a5849113e5 chore(i18n): extract shared pickLocaleLabel helper 2026-07-12 17:00:07 +02:00
Bastien Chanot d7c9d39b13 chore: apply reconcile suggestions — CLAUDE.md drift + TODO sync
REC-1: registry cross-ref ranges (22 BDR / 31 LRN / 5 BLK).
REC-2: env-var identity checked with tour evidence.
REC-3: draft mirror note — restore landed f58a49f.
REC-4: CLAUDE.md factual drift — canvg→native raster, svgToPngDataUrl→
loadSvg, version 1→2, pako→DecompressionStream, pnpm path, folder tree
(EditorsRoute, AppHeader/Footer, LateralityPicker, pdf render files).
TODO gains a dated tour+fixes DONE block.
2026-07-12 16:56:32 +02:00
Bastien Chanot 9d8267ba22 chore: drop dead BoneState values and unreferenced logo PNGs
CLN-6: BoneState 'linked'/'multi' never produced anywhere + their two
CSS rules. CLN-7: 22 of 24 public/assets PNGs unreferenced (favicon is
/favicon.svg; PDF uses the two kept 512px files) — SVG sources and
generate-sizes.sh remain in logos/. Shrinks every build/Docker image.
2026-07-12 16:34:22 +02:00
Bastien Chanot c48406788a fix(pdf): cap inflated attachment size on import
SEC-8 (user-approved change to the protected import path): the flate
fallback materialized the whole decompressed stream unbounded — a
crafted PDF with a deflate bomb could freeze the tab. Stream is now
read chunk-wise and cancelled past 16 MB (valid report JSON is orders
of magnitude smaller); bomb → null → import fails with the generic
error. TDD: real CompressionStream bomb fixture, 180/180 green.
2026-07-12 16:27:40 +02:00
Bastien Chanot 0214ae1537 fix(docker): escape env values in env.js heredoc
SEC-9: a double quote or backslash in APP_* broke the generated JS
(silent config corruption). js_escape() escapes both and collapses
newlines before interpolation. Docker-verified with a hostile
APP_BRAND_NAME: env.js parses, value round-trips exactly.
2026-07-12 16:26:21 +02:00
Bastien Chanot f58a49f7fc feat(store): restore sessionStorage draft on store init
B-3: the osteo:draft mirror was write-only — a page refresh at
/editor bounced to home and lost the session despite the advertised
auto-save. Store now initializes report from readPersistedDraft()
(per-tab sessionStorage: refresh keeps the session, closing the tab
drops it; reset still clears). TDD: 4 new tests incl. refresh
simulation via module re-import — 178/178 green.
2026-07-12 16:25:21 +02:00
Bastien Chanot b047d352c1 feat(species): locale-aware species labels via labelEn
B-6: SpeciesManifest only carried labelFr — EN users saw 'Cheval'.
labelEn required on the manifest, speciesLabel(s, locale) helper in
registry; AnimalForm dropdown + SvgEditor picker localized (locale
passed into initSvgEditor, re-inits on locale change). Scaffolder
template + ADDING-A-SPECIES.md + registry test updated.
2026-07-12 16:23:07 +02:00
Bastien Chanot 74e1623135 fix(i18n): localize SvgEditor input placeholders
B-5: 'head', 'ex: Hanche', 'ex: Hip joint' were hardcoded on an
otherwise localized page. Three new svg_editor.*_placeholder keys,
parity kept; FR output unchanged.
2026-07-12 13:23:56 +02:00
Bastien Chanot 255ab96668 fix(i18n): EN PDF title prefix matches FR document-type semantics
B-4: FR titled exports 'Bilan ostéo — <name>' but EN used the brand
('Faunosteo — '). EN now 'Osteo report — ' — also removes a hardcoded
brand string from the dict (identity rule).
2026-07-12 13:21:45 +02:00
Bastien Chanot 83f02c8fa8 fix(ui): localize Dialog close and LanguageSwitcher group aria-labels
B-1: Dialog close button exposed French 'Fermer' to EN screen-reader
users; B-2: switcher group label was English-only. New dict keys
common.close + lang.group_label in both dicts (parity kept).
2026-07-12 13:21:07 +02:00
Bastien Chanot b7e6371f8a chore(memory): capitalize tour 2026-07-12 — LRN-030/031, EVAL-004, journal 2026-07-12 13:03:24 +02:00
Bastien Chanot 716b1a2be1 docs(tour): report — 2026-07-12 run, converged, 11 commits 2026-07-12 12:50:56 +02:00
Bastien Chanot 1078f74793 docs: sync README, DEPLOY, CHANGELOG with tour fixes (canvg drop, non-root container, base pin) 2026-07-12 11:57:19 +02:00
Bastien Chanot 86ac366136 chore(ui): read Brand logo alt text from config
alt="Faunosteo" hardcoded — identity strings must come from
useConfig() (CLAUDE.md identity rule). Output identical under
default config; custom APP_BRAND_NAME now honored.
2026-07-12 04:48:04 +02:00
Bastien Chanot 4ea8c90c7f chore(i18n): drop dead dict keys, wire LanguageSwitcher through dict
6 keys unused in both dicts removed (common.back, common.none,
editors.title, lateral.bilateral, lateral.unpaired,
pdf.export_date_prefix). LanguageSwitcher hardcoded strings identical
to existing lang.* keys — now reads them via t(); rendered output
unchanged (values identical in both dicts).
2026-07-12 04:48:04 +02:00
Bastien Chanot bbdc0e851a chore: remove dead code and duplicate logic
- drop unused assertNever, canvg dependency (never imported),
  readonly re-export shim in VertebraPicker, stale equine named export
- unexport validateBoneElement (internal only)
- getBoneIdFromEvent now delegates to getAnnotatedElement (dup walk-up)
- rasterizeSvg: drop ignored _scale param (2 call sites + tests)
- extract byte-identical word-wrap into pdf/render/text.ts
- extract mergeBones helper in EditorRoute (block duplicated twice)
- fix stale canvg comment in observationPage
Checks: typecheck, lint, 174/174 tests, build all green
2026-07-12 04:47:54 +02:00
Bastien Chanot c55da07697 fix(docker): pin runner base image to nginx:1.31-alpine
Unpinned nginx:alpine made builds non-reproducible across releases.
Minor-version pin keeps patch updates. Verified: build + HTTP 200.
2026-07-12 03:48:05 +02:00
Bastien Chanot a2bd884bb1 fix(config): add minimum-release-age supply-chain guard
semgrep MEDIUM: pnpm installs now skip package versions published
less than 24h ago (npm supply-chain attack window).
2026-07-12 03:46:59 +02:00
Bastien Chanot d8e478a104 fix(docker): run container fully as non-root nginx user
semgrep HIGH: no USER directive before ENTRYPOINT (container ran as
root). Runtime dirs, conf.d and html dir chowned to nginx so the
entrypoint (env.js write + PORT envsubst) and nginx master both run
as uid 101. Verified: docker build + run, HTTP 200, SPA fallback,
env override OK, ps shows master+workers as nginx.
CONSTRAINT: PORT env var must now be >=1024 (default 8080 unaffected).
2026-07-12 03:46:59 +02:00
Bastien Chanot 187dfb5371 fix(config): move build toolchain to devDependencies
vite, @vitejs/plugin-react-swc, @tailwindcss/vite are build-time only;
they were inflating the production dependency audit surface.
Build + tests verified green after the move.
2026-07-12 03:34:00 +02:00
Bastien Chanot 3f91a45660 fix(editor): sanitize user-imported SVGs before DOM insertion
SvgEditorRoute.loadSVG inserted dropped SVG files with no stripping;
pathology-editor stripped descendants but missed the root element's
on* attributes and javascript: hrefs. Both now remove script/
foreignObject nodes, on* handlers (root included) and javascript:
hrefs before appendChild. Impact bounded (no auth/backend), MEDIUM.
2026-07-12 03:32:50 +02:00
Bastien Chanot 18865def06 fix(config): patch CVE-affected deps (vite, vitest, happy-dom)
- vite 7.3.3 -> 7.3.6 (GHSA-fx2h-pf6j-xcff HIGH, GHSA-v6wh-96g9-6wx3 MED)
- vitest 3.2.4 -> 3.2.7 (GHSA-5xrq-8626-4rwp CRITICAL, dev-only)
- happy-dom 16.8.1 -> 20.10.6 (GHSA-37j7-fg3j-429f CRITICAL, dev-only)
- esbuild -> 0.28.1 within vite range, js-yaml lockfile refresh
pnpm audit: 0 known vulnerabilities; typecheck + 174/174 tests green
2026-07-12 03:25:51 +02:00
554 changed files with 113821 additions and 2549 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
# BUGS-FOUND — behavior-changing findings quarantined by audits
Findings that fixing would change observable behavior — logged here by
audit/cleanup passes, never fixed by them. Route to /bugfix or /feat.
## Tour 2026-07-12 (clean-phase audit) — ALL FIXED 2026-07-12 (user-directed pass, same branch)
| id | file:line | description | severity |
|----|-----------|-------------|----------|
| B-1 (fixed 83f02c8) | src/components/ui/Dialog.tsx:54 | Close button `aria-label="Fermer"` hardcoded French — every dialog exposes a French label to EN-locale screen-reader users. No `common.close` key exists; fix = add key to both dicts + `t()` | low (a11y/i18n) |
| B-2 (fixed 83f02c8) | src/components/brand/LanguageSwitcher.tsx | Group `aria-label="Language"` hardcoded English — FR users get English group label. Fix = new dict key | low (a11y/i18n) |
| B-3 (fixed f58a49f) | src/state/reportStore.ts:145-152 | Draft persistence write-only: every change mirrors report to sessionStorage `osteo:draft`, but no code path restores it — refresh loses session despite the mirror. `readPersistedDraft()` (reportStore.ts:154) exists unused; either implement restore or remove mirror+helper. CLAUDE.md advertises the auto-save | medium (unfinished feature) |
| B-4 (fixed 255ab96) | src/i18n/fr.ts vs en.ts (`pdf.title_prefix`) | PDF title prefix semantics differ per locale: FR 'Bilan ostéo — ' vs EN 'Faunosteo — ' (document type vs brand). Possibly unintended discrepancy in exported PDF metadata | low |
| B-5 (fixed 74e1623) | src/app/routes/SvgEditorRoute.tsx:146,152,154 | Hardcoded placeholders `"head"`, `"ex: Hanche"`, `"ex: Hip joint"` bypass i18n on an otherwise localized page. Possibly intentional examples | low |
| B-6 (fixed b047d35) | src/domain/species/types.ts:19 + AnimalForm.tsx:32 | SpeciesManifest only carries `labelFr` — species dropdown shows "Cheval" to EN users. Fix requires manifest type change (labelEn) | low (i18n gap) |
+43
View File
@@ -0,0 +1,43 @@
# TOUR — grouped multi-axis sweep reports (append-only)
## Tour 2026-07-12 — branch chore/tour-2026-07-12 — 3 iterations — CONVERGED
Axes: security (semgrep floor ×3 + cso posture it1) · clean · reconcile (report-only) · doc.
Iteration 2 clean pass was delta-scoped (3 doc files — only changes since it1's full audit + PASS re-verify).
Iteration 3 ran because it2 surfaced 1 new tuning note; it3 = fresh semgrep on unchanged tree → identical result, 0 new → converged.
| ID | Axis | File | Sev | Finding | Status |
|----|------|------|-----|---------|--------|
| SEC-1 | security | package.json | crit/high | CVE deps: vite (GHSA-fx2h-pf6j-xcff HIGH), vitest (GHSA-5xrq-8626-4rwp CRIT dev), happy-dom (GHSA-37j7-fg3j-429f CRIT dev), esbuild, js-yaml | fixed 18865de — pnpm audit: 0 vulns |
| SEC-2 | security | SvgEditorRoute.tsx:498, pathology-editor.html:1126 | medium | user-dropped SVGs inserted without full sanitization (React editor: none; HTML editor: missed root on* + javascript: hrefs) | fixed 3f91a45 |
| SEC-3 | security | package.json | low | build toolchain (vite + plugins) in prod dependencies — inflated audit surface | fixed 187dfb5 |
| SEC-4 | security | Dockerfile:34 | high | semgrep BLOCK: no USER before ENTRYPOINT — container ran as root | fixed d8e478a — **BREAKING**: PORT env must now be >=1024 (default 8080 unaffected). Docker-verified: build, HTTP 200, SPA fallback, env override, ps = uid 101 |
| SEC-5 | security | .npmrc | medium | no minimum-release-age supply-chain guard | fixed a2bd884 (1440 min) |
| SEC-6 | security | Dockerfile:19 | low | unpinned nginx:alpine base | fixed c55da07 (nginx:1.31-alpine, build-verified) |
| SEC-7 | security | docker/nginx.conf:10,16,21 | medium | add_header inside location blocks — silently drops server-level headers if any are added later | open — defer to /harden (no server-level headers exist yet) |
| SEC-8 | security | src/pdf/attachment.ts:64-72 | low | no decompression-bomb cap on PDF import inflate | open — protected path (CLAUDE.md: ask before changing import) |
| SEC-9 | security | docker/entrypoint.sh:10-17 | low | unescaped env interpolation in env.js heredoc (operator-controlled input; a quote in APP_* breaks the JS) | open |
| SEC-10 | security | .npmrc | low | minimum-release-age=1440 below semgrep-recommended 10080 | open — deliberate 24h dev-velocity trade-off; human call |
| CLN-1 | clean | src (6 sites) | - | dead code: assertNever, canvg dep (never imported), VertebraPicker re-export shim, equine named export, validateBoneElement export, rasterizeSvg _scale param | fixed bbdc0e8 (−93 lines net) |
| CLN-2 | clean | pdf/render, EditorRoute, svgConvention | - | byte-identical word-wrap ×2 → pdf/render/text.ts; mergeBones block ×2 → helper; getBoneIdFromEvent dup walk-up → delegates | fixed bbdc0e8 |
| CLN-3 | clean | i18n/{fr,en}.ts, LanguageSwitcher | - | 6 dead dict keys; switcher hardcoded strings identical to existing lang.* keys | fixed 4ea8c90 (parity 204/204) |
| CLN-4 | clean | Brand.tsx:7 | - | hardcoded alt="Faunosteo" — identity rule violation | fixed 86ac366 (alt via useConfig) |
| CLN-5 | clean | reportStore.ts:154 | - | readPersistedDraft() never called — entangled with bug B-3 (write-only draft mirror); deleting would prejudge the product fix | open — see BUGS-FOUND.md B-3 |
| CLN-6 | clean | anatomy/types.ts:43 + styles/index.css:13 | - | BoneState 'linked'/'multi' never produced + 2 dead CSS rules — possible planned feature | open — human call |
| CLN-7 | clean | public/assets (22 of 24 PNGs) | - | unused logo sizes ship in every build/Docker image | open — confirm no external hotlinks before deleting |
| CLN-8 | clean | labels/canvas/pdf/EditorRoute | - | larger refactors: locale-fallback dedup (6+ sites), PDF constants module, onZoneClick ~60 logic lines, addObservationPage ~200 lines/9 params | open — beyond tour minimal-fix scope, route to /refactor |
| CLN-9 | clean | pdf/attachment.ts:23 | - | attachment description hardcodes brand ('Faunosteo state v2') — PDF format contract | open — confirm before touching (docs/PDF-FORMAT.md) |
| CLN-10 | clean | Dialog/LanguageSwitcher/reportStore/i18n/SvgEditorRoute/species types | - | 6 behavior-changing findings (hardcoded aria labels FR/EN, write-only draft, PDF title prefix asymmetry, i18n placeholders, labelFr-only species) | quarantined → BUGS-FOUND.md B-1..B-6, code untouched |
| REC-1 | reconcile | .claude/tasks/TODO.md:147-149 | - | declared cross-refs "BDR-001..008, LRN-001..010, BLK-001..004" \| real: 22 BDR / 29 LRN / 5 BLK | suggested — update ranges via /reconcile |
| REC-2 | reconcile | TODO.md:126 | - | declared "[ ] env-var brand identity verified" \| real: verified this tour (docker run APP_BRAND_NAME=TourCheck → env.js correct, non-root) | suggested — check box with evidence |
| REC-3 | reconcile | TODO.md:50 | - | declared "[x] sessionStorage draft mirror" \| real: mirror write-only, no restore path (B-3) | suggested — add open item "draft restore or drop mirror" |
| REC-4 | reconcile | CLAUDE.md | - | declared: canvg raster, svgToPngDataUrl(), ReportSchema.version=1, pako, pnpm at ~/.local/share/pnpm/bin \| real: native raster, rasterizeSvg, version 2, DecompressionStream, pnpm at ~/.local/bin | suggested — human-applied CLAUDE.md sync (tour never edits it) |
| DOC-1 | doc | README.md | - | canvg credited for PDF rasterization (feature bullet + stack list) | fixed 1078f74 |
| DOC-2 | doc | DEPLOY.md | - | stale: generic nginx:alpine, root container, no PORT constraint, `origin/master` reference (remote only has main/develop) | fixed 1078f74 |
| DOC-3 | doc | CHANGELOG.md | - | Unreleased section missing tour changes (canvg removal, base pin, security fixes) | fixed 1078f74 |
Checks: typecheck PASS · eslint PASS (0 warnings) · vitest 174/174 PASS · vite build PASS · docker build+run PASS (non-root verified).
Residuals: SEC-7..10, CLN-5..9 (all `open` above) + info: vite chunk >500 kB warning (pre-existing); CI build/push/deploy still unverified (TODO.md:130).
Iteration 2 cso pass skipped by design (iteration-1-only posture audit). semgrep floor ran every iteration (it1 BLOCK(1) → it2 PASS → it3 PASS identical).
Commits: 11 (6 security, 3 clean, 1 doc, 1 report). BREAKING: 1 (SEC-4 — PORT >=1024).
Branch chore/tour-2026-07-12 left UNMERGED — review, then `gitflow finish` on your GO.
+32
View File
@@ -49,3 +49,35 @@ Iterations:
3. `corepack prepare pnpm@10.13.1` → works. Last major before the node:sqlite cache backend; reads lockfile v9 unchanged; already cached on dev host.
Fix: Dockerfile:7 pinned to `pnpm@10.13.1`.
Status: resolved (commit 990c8e7).
---
## BLK-006 | 2026-10-08 | Docker socket permission denied → no local Supabase stack for Claude
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).
Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect).
Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK.
---
## BLK-007 | 2026-10-08 | Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE
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.
Fix: explicit `revoke all on function private.f(args) from public` for every function (new migration 20261008110100 for the Step 3 helpers, inline for Step 4); pgTAP 001 census: anon executes nothing in private/audit, authenticated only the 7 policy predicates.
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
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)
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, `<use>` nesting budget, low-end phone measurement. Plan: docs/development/PDF_IMPORT_HARDENING.md §5. Never close on passing tests alone.
+146
View File
@@ -197,3 +197,149 @@ After 404 fix (moved pathology-editor.html root→public/, LRN-029), considered
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.
---
## BDR-035 | 2026-10-09 | Docker resources prefixed `faunosteo_` (multi-SaaS VPS)
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_<svc>_<project_id>` → 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).
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)
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-<view>.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).
Status: closed; content awaits professional review (REVIEW-REPORT §10, 9 questions).
---
## BDR-037 | 2026-10-10 | Step 4c validated: reference draft, review semantics, migration rule
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
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-<view>.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).
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
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).
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
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.
+87
View File
@@ -28,3 +28,90 @@ Method: user manual export of a v2.0 horse report containing requires_vet_referr
Result: 154/154 tests stayed green; bug shipped to user-facing path. Static signal absent (the ⚠ literal was visible in the source but typecheck/lint don't flag font-encoding issues).
Anomaly: pdf.roundtrip.test.ts exercised export with empty observations + no vet findings. The ⚠ prefix was added in 60e1b04-era (`observationPage.ts:407` ternary) without a regression case covering a flagged leaf.
Action: hotfix swapped ⚠ → `(!) ` (WinAnsi-safe). Added regression `vet-referral marker is encodable by the body font` that calls `widthOfTextAtSize` on a prefixed label — would catch any future non-WinAnsi marker. LRN-021 captured the pdf-lib StandardFonts WinAnsi limitation. Follow-up: switch PDF body to embedded TTF (Inter/Fraunces per CLAUDE.md spec) so the catalog can carry arbitrary glyphs — out of hotfix scope.
## EVAL-004 | 2026-07-12 | Tour sweep converged 3 it. — agent spend-limit deaths resumable
Method: /tour full pipeline on faunosteo — semgrep floor ×3 + cso posture (it1) + full clean audit + fresh independent re-verify + doc-syncer. 13 fixed / 10 open residuals / 6 bugs quarantined; 11 commits on unmerged chore/tour-2026-07-12.
Result: re-verify PASS (0 findings on 20 modified files); checks green throughout (typecheck, lint 0, 174/174, build, docker run non-root). Convergence honest: it2 surfaced 1 new tuning note (min-release-age 1440 < 10080 rec) → triaged open → it3 semgrep identical → converged at 3-iteration bound.
Anomaly: both Phase A agents died mid-run on "monthly spend limit" — SendMessage to same agentId resumed from transcript, zero rework. PostToolUse hook false-positived 3× on 'dangerouslySetInnerHTML' as prose inside audit REPORTS (not code).
Action: none blocking. Consider excluding .claude/audits/*.md from sink-pattern hook scan.
## EVAL-005 | 2026-10-08 | Step 1 characterisation suite (91 cases)
Method: 7 files on real assets (SVG, catalog, fixtures), oracle = audit tables (06 §4, 05 §2.4). Run typecheck/test/lint/build.
Result: 271/271 green, 0 src change. Audit figures all confirmed (26 mappings score 0, 792/612/41, 48 attrs…).
Anomalies: 4 assertions wrong on first run, all test-side (census regex, stale closure, ZONES drawn as bullet rows not ' · ' line, attachment names in object streams). None app-side.
Action: LRN-033. Known quirks pinned as "KNOWN:" tests (orphan findings, no_attachment cause lost, sphenoid id, fuzzy FR pairs).
## EVAL-006 | 2026-10-08 | Step 3 Supabase foundation — PGlite suite
Method: 4 pgTAP files (81 checks: schema/privileges 24, profiles RLS 17, platform roles 28, audit 12) + schema↔types (6) + client (2) on PGlite; root typecheck/lint/build; app suite.
Result: all green first run except plan count (27→28) and pgtap-in-public polluting function census; 278 app + 13 package tests. Zero app behaviour change.
Anomalies: `set_config` rows appear in TAP line capture (noise, filtered by regex). `now()` constant in tx broke naive updated_at>created_at assertion.
Action: LRN-035/036. Not executed: real Supabase image (`supabase test db`), `gen types` diff, seed.sql (needs auth.identities + extensions.crypt), REST manual script. Flagged in report + BLK-006.
## EVAL-007 | 2026-10-08 | Step 3 on the real Supabase stack
Method: `supabase start` (postgres 17.11.0.004), `supabase test db`, `gen types --local` diff, REST curl script (SUPABASE.md §8) with seed users, psql on audit, `db reset`.
Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant.
Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap.
Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved.
## EVAL-008 | 2026-10-08 | Step 4 sheet model — domain tests, pgTAP both engines, fresh verifier + security gates
Method: packages/domain 61 vitest (schema 29 + integrity 32, one per rule code); pgTAP 005 (127 checks) + 001 census on PGlite and real stack (`db reset`, `db test` 210/210, `gen types` diff clean); root check (typecheck, 356 tests, lint 0, build); fresh verifier (contract C1–C13) + security-auditor (semgrep 725 rules 0 findings + checklist).
Result: first gate pass → verifier ECARTS(5), security BLOCK(1): private EXECUTE not revoked (BLK-007), visibility change unaudited, 7 RPCs without non-editor denial test, doc/code mismatches, 75-line SQL function, `any` suppression in a test. All fixed same session: +32 pgTAP checks, hardening migration, visibility RPC, caps, authz-first, SQL check split in 4 functions, `set()/unset()` typed mutations. Second pass: fresh verifier (pending at write time).
Anomalies: 6 test-side fixes on first pgTAP run (RLS hides rows → "no change" asserts; data-modifying CTE; collation of `order by`; trigger name order decides errcode; audit list; pg_temp grants). Executor (opus) deviated usefully: RegionCode pattern separate from StableId.
Action: LRN-038/039/040, BLK-007. Keep the two-gate pass on every migration step.
## EVAL-009 | 2026-10-09 | Step 4b equine import — importer tests, pgTAP both engines, Docker build, gates
Method: packages/anatomy 30 vitest (counts in=out on both sides, special cases, determinism, golden artifacts, guards); pgTAP 001–007 on PGlite and real stack (`db reset`, `db test` 256/256, `gen types` diff clean); root check (61+30+20+278, lint 0, build); `docker build` of the app image; Storage API end-to-end (owner 400 before confirmation → 200 after, alice/anon 400); fresh verifier (C1–C12) + security-auditor (semgrep 130 rules, 0 findings).
Result: first pass verifier ECARTS(4) (self-referential in=out control, undeclared importer-authored labels, docs vs literal sql_paths, silent FR→EN fallback) + security PASS with MEDIUM hash-claim bypass (register_sheet_asset accepts any sha256 → editor reads foreign objects). All fixed: `uploaded_at` + `confirm_sheet_asset_upload` (service role) required by the read predicate, bob-claims-hash pgTAP, authored-label anomalies (27 anomalies now), seeds-listed test, Dockerfile missing workspace manifests (found by building, not by the gates).
Anomalies: real image `storage.protect_delete` aborts direct DELETE tests (LRN-041); pg_temp fixtures need service_role grants; docker build raced the lockfile refresh (rebuild clean).
Action: fresh verifier re-dispatched on the delta; BDR-034, LRN-041.
---
## EVAL-010 | 2026-10-10 | Step 4c equine curation — research agents, changeset, gates
Method: 4 research agents (skull, axial, limbs, osteo/legal), every citation tagged VERIFIED-fetched/snippet/UNVERIFIED; changeset authored in scratch python (44 changes / 679 ops / 48 refs) → pipeline Zod + 20 integrity rules; anatomy 100 vitest (ops, rename propagation, overlay, golden), pgTAP 001–008 on PGlite and real stack (`db reset`, `db test` 267/267, `gen types` diff clean); root check (68+21+100+278, lint 0, build); `docker build`; Storage e2e after upload (owner 200, alice/anon 400); gridded `magick` crops to verify point positions; fresh verifier ×3 + security-auditor ×1.
Result: verifier pass 1 ECARTS(4): B changes left targets `inherited` (CHG-008/032/039 + partials), 3 stale doc numbers, lockfile outside contract scope (orchestrator omission), eslint-disable any in a test → executor: applier rule (B/C ⇒ touched findings/annotations `to_confirm`, `reviewed` refused in B/C), typed test reads, docs. Pass 2 ECARTS(2): JSAVA citation without author (completed from the PDF: Le Roux & Carstens 2018, DOI), DEPLOY.md stale `faunosteo-web`. Pass 3 ECARTS(1): 3 stale doc lines (migration list, "two assets", CLAUDE.md migrations) → fixed by hand, cap of 3 verifier passes reached, not re-verified. Security PASS, LOW: SQL gate did not check reference url scheme → `reference.url.scheme` added (migration still unmerged, pgTAP 008 10 cases); `.env.example` COMPOSE_PROJECT_NAME=osteo-report overrides compose `name:` → file denied to Claude, user action.
Anomalies: ImageMagick MSVG drops `fill="none"` shapes and shapes with `<title>` child (LRN-042); two legacy points (t18-l1, l6-s1) floated above the silhouette, found only by the overlay render, not by the catalog audit; Supabase `db reset` unconfirms the asset row (upload script must re-run: objects kept, row confirmed).
Action: user validation of the draft content (REVIEW-REPORT §10: 11 questions); never publish; Step 5 only after validation.
---
## EVAL-011 | 2026-10-10 | Step 5 app on the canonical sheet — suites on the bundled sheet, archive PDFs, gates
Method: golden v2 PDFs frozen from the old pipeline before any change; suites rewritten on the bundled draft (domain 94, anatomy 107, supabase 21, app 168+: service branches 10/5/12/1, store + v2 draft migration, provider, canvas, pickers, card, route click chain, PDF v3 roundtrip FR/EN + both v2 fixtures + synthetic removed/unknown ids); root check, vite builds none/draft (grep of a draft label in dist = 0/1), docker build, real stack 267/267 + types; legacy-vs-app marker style diff by the verifier (0 differences); fresh verifier ×3 + security-auditor ×1.
Result: verifier pass 1 ECARTS(36) = 4 real (golden test not pinning the new generated files, EditorRoute 398 lines, 5 stale doc lines, one eslint-disable) + my contract omissions (scope files, deleted legacy suites) + floor noise ("species" matched "spec"); pass 2 ECARTS(4) = replacement assertions missing for 4 deleted suites; pass 3 ECARTS(4) = doc counts + 3 more suites' assertions (PDF conclusion/metadata/attachment structure, ObservationCard, persistence). All closed by executors (two) and by hand (docs); cap of 3 passes reached → last lot not re-verified. Security PASS with LOW: prototype-key lookup on untrusted ids (fixed: Object.hasOwn + test), unbounded inflate on the primary attachment path + no file cap (fixed: 16 MiB attachment, 50 MB PDF + test), denylist SVG sanitiser acceptable while assets are repo-built (allowlist before Storage-served assets, Step 13).
Anomalies: executor ran `pnpm format` repo-wide and reverted by hand (watch for `format` in briefs); foreign JSON attachment (no version) surfaced as incompatible_version → fixed to no_attachment (legacy message); verifier floor counts deleted legacy tests as findings until CLARIFICATIONS name them.
Action: user validation of Step 5 (manual FR/EN flow, visual before/after); BDR-038, LRN-043.
## EVAL-012 | 2026-10-10 | Step 5 addendum during user manual validation — per-leaf migration tests, archive check tool, final controls
Method: user asked (while testing) for final controls on last lot + per-leaf test beyond the map + simple v2/v3 PDF comparison method. Built: anatomy test all 612 legacy leaves through `migrateReportV2ToV3` with committed map vs draft document (442 identical / 141 moved = 134 category + 7 leaf renames / 29 removed, snapshots + vet flag verbatim, 26 annotations on right view, v3 re-read stable); app test same leaves via `sheetIndex.nodeAt` + v3 PDF roundtrip; CLI `pnpm report:compare` (pure module + entry, `readAttachedDocument` split out of `extractReportJson`, behaviour unchanged). Contract criteria 16-18 added, gates MET, fresh verifier ×3 + security ×2.
Result: verifier pass 1 ECARTS(2) = floor only (EVAL-011 prose "eslint-disable" false positive → CLARIFICATIONS; 11 dropped `regionFromLabel` assertions → new `legacy.regions.test.ts` on `inferRegionCode`); security PASS + 2 MEDIUM (terminal control chars in untrusted strings; free text printed by default) → executor: `esc()` + `--full` privacy default; pass 2 ECARTS(1) (`--diff` still clear text, JSON.parse message echoed attachment fragment) + security PASS 4 LOW → executor: diff follows `--full`, generic reason, Cc/Cf escaping, regular files only; pass 3 CONFORME. Workspace 94/21/119/181, docker build OK.
Anomalies: verifier stage runs after executor edits only (concurrent reads otherwise); gates.sh needs `EVIDENCE: PENDING` placeholder lines on new criteria. Residuals noted, not fixed: ZodError message echoes closed-vocabulary received values (never names), `compareReport` computes v3 lines twice, template-literal lines >80 chars, locals >5 in two functions.
Action: await user manual validation of Step 5; residuals in TODO follow-up.
---
## EVAL-013 | 2026-10-11 | Step 6 autonomous PDF archives — 5 phases by executors, 3 verifier passes, 4 security audits
Method: analysis (3 analyzers + measurements) challenged by 3 plan-challengers (correctness/robustness/simplicity, 48 findings folded in) → user validation with D7/D8/D13 adjustments → Part II contract (exact types) → one executor per phase (0 freeze goldens, 1 domain, 2 anatomy compose, 3 engine, 4 app) with closed contracts, orchestrator commits → whole-step verifier + security auditor → fix loops.
Result: Phase 0 froze 39 goldens (text/images/links per locale × logo mode, view facts) + 2 route characterisation tests with the OLD code; engine reproduced 36 goldens with 0 mismatch (views: data-* 2→0 and hidden-marker titles declared relaxed). Verifier pass 1 ECARTS(31) = all oracle/scope defects of MY contract (grep on parametrised table, xmldom filter, narrow FILE SCOPE, 3 deleted tests with moved coverage) → contract amended → pass 2 CONFORME 13/13. Security pass 1 BLOCK(1) HIGH real + PoC: archived branding URL written unescaped into `/URI` (PDF object injection via `exportFromEnvelope`), +3 MEDIUM/4 LOW → executor fixed (hex URI, strict URL schema, export re-validation, PNG IHDR budget, CSS-escape rules, NaN guard, file.size) → pass 2 PASS but 2 MEDIUM incl. a regression the fix introduced (UTF-16 BOM URI dead in poppler) + PNG double-IHDR bypass → executor → pass 3 PASS + 1 MEDIUM (UPNG nextZero spin on tEXt) → executor (chunk allowlist + IEND) → pass 4 PASS + 3 MEDIUM (UPNG `inflateRaw` spins on truncated IDAT with allowlisted chunks only; IHDR fields unvalidated; zero dimension) → executor: native bounded `inflateFlate` of the IDAT against the exact raw size, IHDR fields, sides ≥ 1, no interlace, raw ≤ 16 MiB → pass 5 focused. Lesson: a third-party decoder on untrusted bytes needs a native oracle in front, not a chunk allowlist. Final: 656 tests (194/21/130/88/223), typecheck, lint, build, docker ×4 green; goldens byte-identical since 8b86b92.
Anomalies: contract oracles written fast = 2 verifier passes lost (lesson: run every CHECK once before dispatching the verifier); security fix introduced a functional regression invisible to tests because the test reader decoded the BOM (lesson: assert raw bytes, cross-check with a real reader like poppler); executors denied `rm`/`git rm` (orchestrator deletes); one executor used `git stash` despite "no git state" (now forbidden explicitly in briefs); demo envelope with archived branding = 136 KB stored / 306 KB raw (raw > 250 KB, stored < 250 KB: reported, user said data first).
Action: await user manual validation + UX decision on re-export of the kept archive; BLK-009 (pdf-lib ObjStm inflation) before external users; react-router advisories (pre-existing) to bump in a chore.
---
## EVAL-014 | 2026-10-11 | Step 6 closure round — manual-test feedback, BLK-009 scanner, final audits
Method: user manual tests round 1 (logos absent, picker blurry) → reproduction attempts (headless Chromium dev/preview/Docker, Firefox 157 via esbuild harness + raw WebDriver BiDi client, CDP LayerTree, LCD-fringe metric, headed runs on the Wayland session) → fixes by executors → user round 2 confirmed both OK → closure decisions → BLK-009 implemented (byte-scan reader, no object streams) → verifier + 2 security audits + 1 fix loop.
Result: neither visual defect reproduced here (4 environments, 2 engines, 2 PDF renderers); shipped the environment-independent fixes (branding bundled, no fetch; warnings surfaced) and the user confirmed logos + crisp text. Scanner: verifier CONFORME 7/7; audit 1 PASS + 2 MEDIUM (Chromium DecompressionStream read-ahead defeats the cancel: +2.2 GB on a 4 GiB bomb; ×32 candidate CPU) → executor (16 KiB slice feeding, shared 16 MiB budget, monotonic bounded endstream search, `{` pre-check; 133 pdf tests) → audit 2 focused. Workspace 710 tests, build, docker green.
Anomalies: the blur fix of the previous round (will-change) had been marked PARTIALLY MET "desktop by user" — the user's "still blurry" came from that unverified half; this round could not verify real-GPU text rendering either (headless engines render grayscale AA, headed captures failed) → lesson: a screen-rendering defect needs the user's own capture + an A/B recipe early, not days of headless measurement. The Node vitest suite cannot observe browser stream read-ahead: record browser-only bounds as owed manual checks (PDF_IMPORT_HARDENING §5).
Action: BLK-009 stays "mitigated, gate open" (BDR-040); Step 6 finished into develop; release/0.2.0 prepped for the user's go.
+52
View File
@@ -159,3 +159,55 @@ feat(ui+pdf): footer partnership credit "Paws iin Harmony" text -> Paws_in_harmo
fix(editor) 2803cf7 — pathology-editor.html 404 in prod (faunosteo.com/pathology-editor.html). Root cause: file at repo root, Vite bundles only index.html -> never in dist/ -> nginx SPA-fallback -> React "Page introuvable". Worked in `pnpm dev` (serves root files), hid prod gap. Fix: git mv -> public/ (copied verbatim to dist/), href unchanged (public/=web root). Verified via vite preview: /pathology-editor.html=200 text/html. CLAUDE.md + README folder maps synced. LRN-029 captured. Pushed 97f8a92.
- Decided NOT to unify pathology-editor with svg-editor React-route pattern. BDR-022: asymmetry intentional (svg reuses app internals, pathology isolated zero-imports + produces prod JSON -> minimal-change zone). Verified editor fetches same prod assets as app (/species/equine/{pathologies.json,Horse.svg,Horse_head.svg}, all in dist/). No code change.
---
## 2026-07-12
/tour full sweep — branch chore/tour-2026-07-12, 11 commits, UNMERGED (human review pending). Security: CVE deps patched (pnpm audit 0), SVG import sanitized both editors, container non-root (BREAKING: PORT >=1024), nginx:1.31-alpine pin, min-release-age guard. Clean: -93 lines dead code (canvg dep dropped), 3 dedup extracts, i18n dead keys purged. Docs synced (README/DEPLOY/CHANGELOG, incl. stale origin/master). 6 bugs quarantined -> BUGS-FOUND.md (worst: B-3 draft mirror write-only). 4 reconcile suggestions pending /reconcile. Report: .claude/audits/TOUR.md. LRN-030/031, EVAL-004 captured.
---
## 2026-10-08
SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domain map, FE/BE arch, migration, tests, 9 open questions) — user validated + decided: no external users, no v2 compat obligation, equine only, 2 SVG assets kept, import anomalies into draft (no silent fix), self-hosted Supabase on adequate infra, design decisions gated by user (ChatGPT), manual report points confirmed. Step 1: 91 characterisation tests, 2 golden fixtures, CHARACTERIZATION_REPORT.md; 271/271, typecheck/lint/build green; host had no pnpm → corepack (LRN-032). Both committed on feature/step-01-characterisation-tests, validated.
- Step 2 (same day): app → apps/app (git mv, 144 R100), pnpm workspace, Node 24 + pnpm 10.13.1 pins, Dockerfile node:24 filtered build (unverified locally, no daemon), Gitea CI, WORKSPACE.md; 271/271, typecheck, lint, build green from root. Finish purged docs/superpowers (lib BDR-065) → restored under docs/history (BDR-025). Both steps merged into develop (c8d48ab, 4959602). BDR-023/024/025, LRN-034. User confirmed `@faunosteo/app`; working method set: harness owns gitflow/memory/quality, user gives step goals, design changes gated. Next: Step 3 on user goals.
## 2026-10-08 (session 3 — Step 3)
Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof.
- Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish.
- Step 3 validated by user (session 4). chore/supabase-cli-gitignore finished into develop. Step 4 (sheet model) started on feature/step-04-anatomical-sheet-model.
- Step 4 (session 4): spec docs/development/ANATOMICAL_SHEET_MODEL.md; packages/domain (Zod doc strict, 17 integrity rules, 60 tests, opus executor); migration 20261008110000 (species, sheets, immutable versions, assets, 11 RPCs, RLS) + pgTAP 005 (95 checks); types regenerated on real stack (Docker now OK), pgTAP 176/176 real + PGlite; publishSheetVersion gate; docs synced. 5 commits on feature/step-04-anatomical-sheet-model. BDR-030/031/032, LRN-038/039. Verifier + security gates dispatched. Next: user validation, Step 4b importer → equine draft.
- Gates: verifier ECARTS(5) + security BLOCK(1) on first pass (private EXECUTE never revoked = BLK-007, foundation flaw). Fixed: hardening migration 20261008110100, explicit revokes + pgTAP census, set_sheet_visibility RPC, no direct draft DELETE, caps, authz-first, counter, asset copy scoped, SQL check split, url http(s) only. Real stack 210/210, root check green. Fresh verifier re-dispatched on the delta.
## 2026-10-09
Step 4 validated + finished into develop. User decisions on the 7 open points → BDR-033 (follow-gated use, verified publication, no auto-deprecation, platform-owned official, kind rename, server validation, erasure path). Step 4b on feature/step-04b-equine-import: packages/anatomy importer (opus executor, 25 tests) → seed equine v1 as DRAFT (27 ann / 26 linked / 792 nodes / 612 leaves / 41 vet, 0 integrity issues, 18 anomalies reported, ssb-dysfunctions flagged); Storage migration + policy through the sheet, shim storage tables, harness applies seed/**, pgTAP 006/007 (238/238 real stack), assets uploaded + REST/Storage checks (owner 200, alice/anon 400). BDR-034, LRN-041. Gates dispatched; stop for user validation before Step 5.
- Gates 4b: verifier ECARTS(4) + security PASS/MEDIUM → fixed same session (confirm_sheet_asset_upload + uploaded_at in read predicate, 27 anomalies declared, seeds-listed test, Dockerfile manifests for domain/anatomy, docker build green). Real stack 256/256, Storage e2e verified. EVAL-009. Fresh verifier re-run on delta; stop for user validation.
- 2026-10-10 Step 4c on feature/step-04c-equine-curation: Docker `faunosteo_` convention (BDR-035); schema v2 (references, review_status, count_range; migration 20261010100000, pgTAP 008); curation pipeline (executor) + review overlays; 4 research agents (skull, axial, limbs, osteo/legal) → 44 changes / 679 ops / 48 refs authored from scratch python modules; draft 811 nodes, 28 annotations, 0 integrity errors; 9 points moved, carpus added, 9 questions for the osteopath. Root check green, real stack pgTAP + types clean, docker build OK. BDR-036, LRN-042. Gates next; stop for user validation; no publication.
- Gates 4c: verifier ×3 (4→2→1 écarts, last 3 doc lines fixed by hand at cap), executor closed the applier rule + typed tests; security PASS (LOW url scheme → SQL rule `reference.url.scheme`). Real stack 267/267, Storage e2e OK. EVAL-010. Awaiting user validation; `.env.example` COMPOSE_PROJECT_NAME left to the user (file denied).
- Step 4c VALIDATED by user 2026-10-10 → tracking: head view check documented (spec §6), BLK-008 migration limit, BDR-037, DEPLOY.md `.env.example` note. Finished into develop. Next: Step 5 (app on the canonical sheet), design points flagged before any UI work.
- Step 5 preparation (2026-10-10): 4 analyzer agents (core/store, rendering, PDF, tests) + plan/spec reading → docs/development/STEP5_MIGRATION_ANALYSIS.md on chore/step-05-migration-analysis. Key facts: all 27 legacy data-anno-ids differ from canonical ids; 170/612 legacy finding paths moved/removed by curation → generated report-migration-map; markers never drawn by the app (in the SVG); PDF depends on markers only for the highlight; 66 tests import the registry. 8 decisions D1–D8 await the user. No implementation.
- Step 5 implemented (2026-10-10, feature/step-05-app-on-canonical-sheet): domain report v3 + migration (80 tests), pipeline migration map/sheet-ref/app review drawings + layer renderer (110), app rewritten on the sheet (99 tests: service, store, provider, canvas, pickers, PDF v2/v3, route), legacy code removed, docs rewritten (ANNOTATION-RENDERING.md replaces the SVG convention). Root check green, docker build OK, real stack 267/267, default build carries no sheet. BDR-038, LRN-043. Gates next; awaiting user validation.
- Step 5 gates (2026-10-10): verifier 36→4→4 (real gaps closed by 2 executors + doc fixes; cap reached, last test lot unverified by a 4th pass), security PASS (2 LOW fixed: prototype keys, size caps). EVAL-011. Final check green. Awaiting user validation; no publication; default build carries no sheet.
- Step 5 addendum (2026-10-10, user testing manually): per-leaf migration tests (612 leaves, anatomy + app + PDF roundtrip), `pnpm report:compare` archive check tool (privacy default, escaping), stale `scaffold:species` script removed, attachment read/parse split. Gates: verifier 2→1→CONFORME, security PASS ×2 (2 MEDIUM + 4 LOW fixed by executors). EVAL-012, LRN-044. Branch 14 commits ahead, not merged; awaiting user validation; no Step 6.
- Step 5 user validation (2026-10-10): all paths OK. One defect: findings picker text blurry on screen. Root cause (headless Chromium measure): permanent `will-change: transform, opacity` on the picker list + fractional offset inside height-animated card → composited text resampled; PDF unaffected. Hotfix 1f0b710: prop dropped, regression test (app 182). Security PASS, docs NONE. Full check green. User signal → finish Step 5; carpus + moved points noted, 28 annotations NOT a final catalog (enrichment with the osteopath + future editor later). Step 6 to present, not started.
## 2026-10-10 (session — Step 5 closed, Step 6 analysis)
Step 5 validated + closed by user; LRN-045 (permanent will-change blurs text) written on develop. Step 6 analysis on chore/step-06-pdf-archive-analysis: 3 analyzers (PDF pipeline, data model, app/tests) → facts: export reads live SheetIndex (labels, views, asset, all annotations of view), 4 fetched logos + 3 hard-coded URLs, DOM in drawing/highlight/raster, attachment = bare v3 Flate'd by pdf-lib, getAttachments dead on pdf-lib 1.17.1, no report↔sheet check anywhere. Measured: lean snapshot envelope 172 KB raw / 51 KB stored (3 obs), 228 / 54 worst; SVG = 90% of stored. Plan: snapshot = lean AnatomicalSheetDocument + assets inline (reuses index/renderer/integrity rules), packages/pdf engine (xmldom compose promoted from app-review.ts, Rasterizer + Branding inputs, no DOM lib), envelope v1 layered reading (report never lost), rebase on import/restore keeps report.sheet == snapshot.ref, export-side caps. 3 plan-challengers GO WITH FIXES (16+19+13 findings folded in). docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md; TODO 6.0–6.7. Awaiting user decisions D1/D4/D6/D7/D8/D10/D12/D13; no implementation.
## 2026-10-11 (Step 6 implementation)
User validated the Step 6 analysis with D7 (branding archived), D8 (imported snapshot kept, explicit rebase, no new UI without UX gate), D13 (explicit import messages). Analysis chore branch finished; feature/step-06-pdf-archives. Part II contract (exact types) + BDR-039. Phases by executors: 0 freeze (39 goldens, demo fixture, bare v3 PDF, route characterisation), 1 domain (archive/{snapshot,envelope,branding,labels}, sheet-index moved, rebase, bundle asset hashes), 2 anatomy (composeViewSvg + highlightLayer promoted from app-review), 3 engine packages/pdf (xmldom composition, allowlist sanitiser, safeText, Rasterizer, envelope v1, layered reader, resvg test), 4 app (export/import on the engine, archive in session `osteo:archive`, rebase + 4 messages, legacy modules removed). Verifier ECARTS(31, all my contract's oracles/scope) → CONFORME. Security BLOCK(1) HIGH (URI injection via archived branding) → 4 fix loops (hex URI → ASCII hex after poppler regression, URL schema, export re-validation, PNG IHDR budget → chunk allowlist + IEND → native IDAT inflation against exact raw size + IHDR fields, CSS escapes, NaN, file.size) → PASS. Docs: PDF-FORMAT.md real, CLAUDE/README/WORKSPACE/DEPLOY/CHANGELOG. 656 tests, build + docker green. Sizes: demo envelope 55 KB stored no logos / 136 KB with archived branding (306 KB raw). LRN-046, BLK-009, EVAL-013. Awaiting user validation + UX decision for re-export of the kept archive; Step 7 not started.
## 2026-10-11 (Step 6 manual-test feedback)
User: step not merged; findings-picker text still blurry; footer logos absent in their PDFs; decisions: re-export from archive wanted (UX to propose), restore-rebase must be visible, exact labels to validate; BLK-009 analysis. Done on feature/step-06-pdf-archives: logos NOT reproduced (real export in headless Chromium dev/preview/Docker image + Firefox 157 engine harness: 4 logos embedded, 0 warnings, poppler + pdf.js render them) → branding bundled into the app (`src/assets/brand`, `?inline`/`?raw`, no fetch at all) + export returns warnings + `editor.export_warnings` alert (293a6e0); blur NOT reproduced (headless Chromium/Firefox, DPR 1/1.25/2, scrolling 9-leaf list, CDP LayerTree: no composited layer, no lingering animation/will-change; headed runs on the user's Wayland display failed to capture) → analysis + A/B recipe for the user; restore rebase alert `editor.draft_rebased` (e8f1734); docs/development/PDF_IMPORT_HARDENING.md (byte-scan reader + no object streams now; worker/parser later) (5ed4a4b). Root check 660 tests, build, docker green. Awaiting user: browser/zoom for the blur, UX choice for re-export, label validation.
## 2026-10-11 (Step 6 closure)
User round 2: logos OK, picker text crisp, flows OK → STEP 6 VALIDATED. Decisions BDR-040: re-export-archive button refused for good; restore-rebase alert approved; import headlines full/partial (62b8a43). BLK-009: byte-scan attachment reader + export without object streams (60ee712), verifier CONFORME, audit PASS+2 MEDIUM → slice-fed inflater + candidate budget (3a6e926), focused re-audit. EVAL-014. Then: gitflow finish into develop, release/0.2.0 prep (Milestone A) up to the human go; Step 7 not started (UX/design to discuss with ChatGPT first). Step 6 finished into develop (c746952, 139 commits over main); release/0.2.0 prepped (dac75ab) and pushed, awaiting the human go for finish + tag.
+120
View File
@@ -232,3 +232,123 @@ Apply: any feature where "select X in modal → reflect in N places". Find the s
Extra .html at repo root never reaches dist/ — Vite build entry = index.html only. Prod 404: nginx try_files falls through to SPA index.html, React shows "Page introuvable". Fix: put standalone HTML in public/ (copied verbatim to dist/). Links resolve from web root, so href stays /file.html.
**Why:** pathology-editor.html shipped at root (BDR-020 standalone-HTML pattern), worked in `pnpm dev` (Vite serves root files in dev) but 404'd in prod (only public/ + bundled entries land in dist/). Dev-vs-prod gap hid it.
**How to apply:** standalone HTML tool / extra entry → public/, OR add to vite build.rollupOptions.input for hashed-asset processing. Verify via `vite preview` (serves real dist/), not just `pnpm dev`. Ties to [[BDR-020]].
## LRN-030 | 2026-07-12 | Dockerized SPA on port >=1024 — full non-root nginx works
nginx:alpine default = master root, workers nginx. Listen port >=1024 → USER nginx viable: chown /var/cache/nginx + pre-created /var/run/nginx.pid + /etc/nginx/conf.d (entrypoint envsubst rewrite) + html dir (env.js write). Official image log symlinks (/dev/stdout|stderr) work non-root.
**Why:** tour 2026-07-12 semgrep HIGH (no USER before ENTRYPOINT, Dockerfile:34). Fixed d8e478a; verified docker run: HTTP 200, SPA fallback, env override, ps = uid 101 master+workers.
**How to apply:** any nginx-served SPA container: keep listen >=1024, chown the 4 paths above, USER nginx. Contract change: PORT <1024 now fails to bind — flag BREAKING. Alt base: nginxinc/nginx-unprivileged.
## LRN-031 | 2026-07-12 | Build toolchain in dependencies inflates prod CVE audit surface
vite + @vitejs/plugin-react-swc + @tailwindcss/vite sat in dependencies → `pnpm audit --prod` reported their CVEs as prod findings. Build-time-only packages belong in devDependencies; SPA runtime imports none of them.
**Why:** tour 2026-07-12 cso posture audit — all 3 "prod" advisories were build-toolchain. Moved 187dfb5; build+tests green, prod audit clean.
**How to apply:** scaffold check: anything imported only by vite.config / build pipeline → devDependencies. Then `pnpm audit --prod` reflects real runtime surface. Docker multi-stage unaffected (builder installs all).
---
## LRN-032 | 2026-10-08 | pnpm via corepack prepare, not ~/.local/bin
Dev host: no pnpm on PATH, no node_modules, Node 24.21 (CLAUDE.md said Node 20 + `~/.local/bin/pnpm`, both stale). `corepack prepare pnpm@10.13.1 --activate` + `corepack pnpm <cmd>` works, zero global install, same pin as Dockerfile (BLK-005). Suite 271/271 on Node 24.
Apply: never `export PATH=…` in Bash tool (denied); call `corepack pnpm`. Pin `packageManager` in package.json so corepack picks version alone.
---
## LRN-033 | 2026-10-08 | Characterise legacy via DOM + prototype spies, no refactor
Untestable seams (click chain inside route, PDF text) pinned without touching src: render route in MemoryRouter + mock `@/anatomy/svgLoader` to parse real files, dispatch bubbling click on `[data-anno-id]`; `vi.spyOn(PDFPage.prototype,'drawText')` captures every drawn string (pdf-lib has no extractor); attachment dicts via `doc.context.enumerateIndirectObjects()` + `String(obj)` (object streams hide names from raw bytes). Standalone HTML tool: slice functions by text markers, `new Function(src)` → parity test.
Trap: store set outside React then click = stale closure; drive state through UI (collapse card) and `waitFor`.
Apply: any "tests before migration" step on untested legacy code.
---
## LRN-034 | 2026-10-08 | pnpm 10.13 reads onlyBuiltDependencies, not allowBuilds
`allowBuilds` key in pnpm-workspace.yaml = pnpm ≥10.14 syntax; 10.13.1 ignores it silently → "Ignored build scripts: @swc/core, esbuild" on every install. Fix: `onlyBuiltDependencies` list. Warning persists until `pnpm rebuild` (state cached in node_modules/.modules.yaml), then disappears.
Also: root scripts calling `pnpm -r` fail under `corepack pnpm` (shim not on child PATH) → pin pnpm as root devDependency.
Apply: any pnpm 10.x workspace; check `pnpm --version` vs key syntax before trusting a silent config.
---
## LRN-035 | 2026-10-08 | PGlite + pgtap = Dockerless Supabase RLS tests
`@electric-sql/pglite` 0.3 bundles `pgtap`, `pgcrypto`, `uuid_ossp` (`import { pgtap } from '@electric-sql/pglite/pgtap'`). Boot ~1s, `create extension pgtap with schema extensions` + `set search_path to public, extensions` (else pgTAP functions pollute `public` and break "list public functions" checks; filter `pg_depend deptype='e'` too). `db.exec(file)` runs multi-statement begin…rollback; collect string cells → TAP lines; fail on `/^not ok/` or `# Looks like`. After error: `rollback` to clear aborted tx. Impersonate: `set local role authenticated; set_config('request.jwt.claims', '{"sub":…}', true)`. `now()` frozen in tx → test updated_at by overwriting then `is(updated_at, now())`.
Apply: any Supabase project needing SQL tests in CI without Docker.
---
## LRN-036 | 2026-10-08 | Supabase default privileges grant ALL to anon/authenticated on new public tables
Hosted/local Supabase: `alter default privileges … grant all on tables/functions to anon, authenticated, service_role`. New table or RPC = anon can SELECT/EXECUTE until revoked (RLS still filters rows, but RPC runs). Pattern per migration: `revoke all on <table> from public, anon, authenticated;` then exact grants (column-level for partial UPDATE); `revoke all on function … from public, anon`. Also Postgres default EXECUTE to PUBLIC on functions in own schemas → `alter default privileges in schema private revoke execute on functions from public`. Shim replicates defaults so pgTAP `has_table_privilege('anon',…)` catches omissions.
Apply: every migration; pin with pgTAP privilege checks.
---
## LRN-037 | 2026-10-08 | SQL tests seed-agnostic; generated files through a deterministic formatter
Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps.
Apply: any dual-runner test setup (shim vs real); any CI diff on generated code.
---
## LRN-038 | 2026-10-08 | RLS filters, never raises: test "no change", and trigger guards under the owner role
API-role UPDATE/DELETE on a row hidden by policy touches 0 rows silently → `throws_ok` wrong; assert the row unchanged afterwards (`is((select content ...), expected)`). Trigger-level immutability must be proven with `reset role` (table owner bypasses RLS). pgTAP `is()` cannot wrap a data-modifying CTE (`with u as (update …)` must be top level) → plain statement then a read. Triggers fire alphabetically by name: when two BEFORE triggers reject, the first name's errcode surfaces (species check 23514 before guard 42501) → pick test inputs that isolate the guard.
Apply: every RLS + trigger pgTAP file.
---
## LRN-039 | 2026-10-08 | Dual-runner parity: pin collation, grant pg_temp fixtures to API roles
Real Supabase image sorts text with a locale collation (`anatomical_sheet_asset…` before `anatomical_sheet.archived`), PGlite with C → `results_eq` on `order by text` flaps; pin `order by col collate "C"`. pg_temp tables/functions created as postgres are invisible to `set local role authenticated` → `grant all on pg_temp.t to anon, authenticated; grant execute on function pg_temp.f(...)`. jsonb equality check beats `(x->>'k')::int = n` in a CHECK (no cast error on garbage).
Apply: any pgTAP file with fixtures read while impersonating; any ordered results_eq (extends LRN-037).
---
## LRN-040 | 2026-10-08 | Function privileges: revoke per function, pin with a pg_proc census
`alter default privileges in schema X revoke execute on functions from public` does nothing (BLK-007). Pattern: every migration ends with `revoke all on function private.f(args) from public` per function + explicit grants; a pgTAP census (`has_function_privilege('anon'|'authenticated', p.oid, 'execute')` over pg_proc of private/audit, compared to an allowlist via `string_agg(... order by proname::text collate "C")`) fails the next omission. `results_eq` over `name`-typed columns vs text literals raises "could not determine which collation" on PGlite → compare one aggregated string. Trigger functions that call other private functions must be `security definer` once EXECUTE is revoked (the invoking API role no longer holds it).
Apply: every Supabase migration; the census is the backstop.
---
## LRN-041 | 2026-10-09 | Real Supabase image vs PGlite shim: storage triggers, pnpm script cwd
Real `storage.objects` carries `storage.protect_delete` (statement trigger: "Direct deletion from storage tables is not allowed") → a pgTAP that runs DELETE as an API role passes on the shim and aborts the whole file on the real stack; assert write restrictions through a `pg_policies` census instead. Shim stays minimal (buckets/objects columns actually touched). `pnpm --filter pkg script <relative path>` runs inside the package dir → resolve CLI paths from `process.env.INIT_CWD`. Node 24 strip-types cannot follow workspace directory imports (`ERR_UNSUPPORTED_DIR_IMPORT`) → tsx for CLIs that import workspace packages.
Apply: every pgTAP touching storage.*; every workspace CLI.
---
## LRN-042 | 2026-10-10 | Changeset authoring over a baseline: python modules per theme, stylised SVG audited by gridded crops
Authoring 44 changes / 679 ops by hand is error-prone → scratch python modules (one per research theme, shared helpers `set_op/cite_op/add_change`, auto-numbered ids, targets derived from the baseline by walking it) built into changes.json; the pipeline's Zod + integrity rules catch any bad target at once. Order of modules = order of ops: a later module must address ids renamed by an earlier one (consultation-reason category ids). Stylised drawing: render with `magick` + 50-unit grid crops; sample first non-white row per column to prove "point floats above the silhouette" (t18-l1, l6-s1 were 30-70 units above the back). ImageMagick's internal SVG renderer drops shapes with `fill="none"` and shapes containing a `<title>` child → overlay uses fill-opacity and puts `<title>` on the `<g>`. Research agents: one theme each, every citation tagged VERIFIED-fetched/snippet/UNVERIFIED; only fetched or bibliographically confirmed entries enter the registry, unread books say "non consulté" in the citation.
Apply: next species/sheet curation; any overlay/diagnostic SVG rasterised with ImageMagick.
---
## LRN-043 | 2026-10-10 | Migrating an app onto a new data model: freeze goldens first, make ids + maps data, read fresh state in DOM handlers
Freeze golden artifacts with the OLD code before touching it (v2 PDFs via a one-shot vitest, MAKE_GOLDEN=1, deleted after): the new importer is then tested against real archive-like bytes. Generate id/path maps from the pipeline's own records (renames/removals), never hand-written, and commit them as golden-tested data. In React routes, click handlers bound through `useEffect` capture stale closures when two DOM clicks land before a re-render (tests dispatch synchronously): read `store.getState()` inside the handler. A sheet needed to restore a draft but only known from the draft → load the default species' sheet when no report is open. Vitest has its own config: a Vite plugin providing a virtual module must be registered there too. ImageMagick cannot verify marker look with `<title>` children or `fill="none"`: strip titles for the raster only.
Apply: Step 6 (PDF v3 snapshot), Step 13 (Supabase SheetProvider), any future schema bump.
## LRN-044 | 2026-10-10 | CLI over untrusted documents: escape before print, privacy default, generic parse errors
Context: `report:compare` prints content of archive PDFs (attachment JSON). Security audit: raw interpolation lets a crafted attachment carry ESC/CR sequences that erase or forge lines, including a `!! UNRESOLVED` marker in an integrity tool; free text leaks names when stdout lands in CI logs; V8 `JSON.parse` message echoes ~15 chars of the input.
Pattern: one `esc()` helper (`/[\p{Cc}\p{Cf}\u2028\u2029]/gu` → `\uXXXX`) on every interpolated untrusted string incl. file names and error messages; default output = ids + catalog labels + counts + placeholders, `--full` opt-in for names and free text, same rule in every mode (`--diff` too); `SyntaxError` → generic reason; `statSync().isFile()` + size before `readFileSync`; INIT_CWD for paths under pnpm.
Apply: any future CLI/log over report content (Step 6 server import, worker). Test with `\u001b[2K`, `\n`, `\u009b`, `\u202e`, `__proto__` ids.
---
## LRN-045 | 2026-10-10 | Permanent `will-change: transform` blurs text; promote only during the animation
Context: findings picker text blurry on screen, crisp in PDF (Step 5 validation). `motion.ul` kept inline `will-change: transform, opacity` after its 220 ms slide (computed transform `none`); list sat at fractional offset inside height-animated card (left 561.1875 px desktop, top 735.77 px mobile) → element stayed on own compositor layer, text resampled at non-integer position → blur. Fix = drop the prop; motion promotes the element itself while animating (1f0b710).
Pattern: never set permanent `will-change` on text containers; let the animation lib promote for the duration. Diagnose with headless Chromium: computed `willChange`, bounding rect fractional offsets, edge-sharpness ratio before/after (headless has no LCD antialiasing → desktop delta flat, user confirms in real browser). Regression test = rendered element has no inline `will-change`.
Apply: any `motion.*`/CSS transition on lists, cards, modals holding text; design-review audits.
---
## LRN-046 | 2026-10-11 | Refactor a render pipeline behind goldens frozen in two fixture modes; lean-document snapshot beats a new schema
Step 6 moved the PDF pipeline into `packages/pdf` with zero visible change. What made it provable: Phase 0 froze drawn text (page, x, y, size, font), image placements, link annotations and per-view structural facts with the OLD code, in two harness modes (logos absent / present via a fetch stub serving the real public/ bytes) and per locale (footer geometry depends on label width). Golden JSON = oracle; the port had 0 mismatch; the two intentional differences (hidden markers absent, data-* gone) were declared as relaxed fields, never by editing goldens. Snapshot shaped as a valid lean `AnatomicalSheetDocument` reused the index, the renderer and 21 integrity rules (3 challengers killed the dedicated-schema idea). Node-side xmldom composer already existed in curation (`app-review.ts`): promote, don't rewrite. resvg 0.40 panics on gradient fills culled by a cropped root viewBox (head view) → test adapter renders the full box and crops pixels; Chrome is fine. Executors denied `rm`/`git rm`: orchestrator deletes on literal relative paths after checking importers.
Apply: any pipeline extraction (Step 13 Supabase provider, Step 14 worker); any "snapshot" design: reuse the live schema minus content before inventing one.
+81 -5
View File
@@ -38,6 +38,82 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] pathology-editor.html prod 404 fixed — served from public/ so it ships to dist (2803cf7, LRN-029)
- [x] gitflow socle + pre-commit hook adopted (4991c10)
### Tour + fixes 2026-07-12 (branch chore/tour-2026-07-12 — UNMERGED, review pending)
- [x] /tour sweep: CVE deps patched (pnpm audit 0), SVG import sanitized, container non-root (**BREAKING: PORT >=1024**), nginx:1.31-alpine pin, dead code −93 lines (canvg dropped), docs synced. Report: .claude/audits/TOUR.md
- [x] Post-tour fixes: aria-labels i18n (B-1/B-2), EN PDF title prefix (B-4), SvgEditor placeholders (B-5), species labelEn (B-6), draft restore (B-3, TDD), entrypoint escaping (SEC-9), PDF decompression cap (SEC-8, TDD), dead BoneState + 22 unused PNGs (CLN-6/7). 180/180 tests.
---
## SaaS migration (plan: docs/development/IMPLEMENTATION_PLAN.md)
- [x] Step 0 — preparation docs in docs/development/ (2026-10-08, validated)
- [x] Step 1 — characterisation tests: 7 files / 91 cases, 2 golden fixtures, docs/development/CHARACTERIZATION_REPORT.md; 271/271, typecheck, lint, build green (2026-10-08, branch feature/step-01-characterisation-tests, awaiting validation)
- [x] Step 2 — monorepo workspace: apps/app via git mv (144 files), root scripts, Node 24 + pnpm 10.13.1 pins, Dockerfile node:24 + filtered build, CI .gitea/workflows/ci.yml, WORKSPACE.md; 271/271, typecheck, lint, build green from root (2026-10-08, branch feature/step-02-monorepo-workspace, uncommitted, awaiting validation)
- [x] Step 3 — Supabase foundation (2026-10-08, feature/step-03-supabase-foundation merged into develop 7ea0b1f, USER VALIDATED 2026-10-08; real stack verified: start/reset, pgTAP 81/81, gen types diff, REST script — BLK-006 resolved)
- [x] 3.0 context: plan Step 3, BACKEND_ARCHITECTURE §2-§9, business §4.1/§17/§29; Docker socket denied to user → PGlite harness as executable proof, pgTAP kept for `supabase test db`
- [x] 3.1 supabase/config.toml (CLI pinned as root devDependency) + `supabase/seed.sql` (local users only)
- [x] 3.2 migration 0001 foundation: schemas private/audit, set_updated_at, audit.audit_logs append-only, private.log_event
- [x] 3.3 migration 0002 profiles: table, auth.users trigger, protected columns trigger, RLS own row (+ staff read), grants
- [x] 3.4 migration 0003 platform roles: enum platform_role (owner/admin/moderator/support), profile_roles, private.is_platform_* helpers, grant/revoke RPC with audit, RLS
- [x] 3.5 pgTAP tests supabase/tests/*.sql (schema, profiles RLS allow+deny, roles allow+deny, audit append-only)
- [x] 3.6 packages/supabase: PGlite harness (auth shim + migrations) + vitest RLS suite (allow+deny), database.types.ts (generator format) + schema↔types consistency test, browser client factory
- [x] 3.7 app integration: env.ts supabaseUrl/anonKey, lib/supabase.ts lazy client (null when unconfigured), entrypoint.sh + .env.example + compose; no UI change; tests
- [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r
- [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer
- [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006
- [x] Step 4 — canonical anatomical sheet model (2026-10-08, feature/step-04-anatomical-sheet-model merged into develop, USER VALIDATED 2026-10-09; 7 business decisions → BDR-033, spec §5). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md
- [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written
- [x] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability
- [x] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS
- [x] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish
- [x] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test
- [x] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG
- [x] 4.6 verify: pnpm check green (61+17+278), db:reset + db:test 210/210 real stack, types in sync; verifier ECARTS(5) + security BLOCK(1) → all fixed (BLK-007 hardening migration, visibility RPC, +32 pgTAP, doc sync); BDR-030..032, LRN-038..040, EVAL-008
- [ ] Step 4b — equine import (2026-10-09, branch feature/step-04b-equine-import): legacy SVGs + catalog → official equine sheet as DRAFT, import report for business review, no publication
- [x] 4b.0 kind rename observation→consultation_reason (BDR-033 #5); decisions in spec §5 + memory
- [x] 4b.1 packages/anatomy: legacy importer (SVG walker via @xmldom/xmldom, catalog mapper, deterministic ids, legacy-id-map, import report with anomalies incl. ssb-dysfunctions), CLI `pnpm import:equine` writing supabase/seed/anatomical-sheets/equine/v1/{document.json,legacy-id-map.json,IMPORT-REPORT.md,assets/,equine_v1.sql}; tests: counts preserved (27 ann / 26 mapped / 792 nodes / 612 leaves / 41 vet), determinism, Zod + 0 integrity errors, golden artifacts
- [x] 4b.2 migration 20261009100000 sheet asset storage: bucket anatomical-sheet-assets (private), object read policy through the sheet (published refs or editor), no API writes; shim storage tables; pgTAP
- [x] 4b.3 seed: equine_v1.sql idempotent (platform-owned official sheet, private, draft v1, 2 asset rows, fixed ids) in config sql_paths + PGlite harness applies supabase/seed/**; pgTAP 006: draft present, not publishable by non-admin, sheet_document_issues empty, assets match; upload script for the SVG bytes (service key from env, user/operator runs)
- [x] 4b.4 real stack: db reset + db test + types check + assets upload + REST read check; docs (SUPABASE.md, ANATOMICAL_SHEET_MODEL.md §6 import, CLAUDE.md, plan note, CHANGELOG)
- [x] 4b.5 verify: pnpm check green (61+30+20+278), real stack 256/256, types in sync, docker build OK, Storage API 400→200 after confirmation (alice/anon 400); verifier ECARTS(4) + security MEDIUM (hash claim) → fixed (uploaded_at + confirm RPC, authored labels, seeds-listed test, Dockerfile manifests); EVAL-009
- [x] Step 4b VALIDATED by user 2026-10-09 → finished into develop. Draft stays private, never auto-published.
- [x] Step 4c VALIDATED by user 2026-10-10 → finished into develop; draft stays private, never auto-published — equine sheet audit, correction, enrichment (2026-10-09, branch feature/step-04c-equine-curation). User brief: research-backed audit of SVG annotations + findings catalog, corrections by confidence level (A demonstrated / B supported, flagged / C uncertain, question for the osteopath), traceable changeset (id, before, after, nature, rationale, references, level, needs confirmation), reproducible baseline of the 4b import, no publication, no design redesign (propose first).
- [x] 4c.0 Docker naming convention `faunosteo_` (compose container/project names; Supabase CLI names fixed `supabase_<svc>_<project_id>` → documented limit). Docs + memory (BDR).
- [x] 4c.1 domain schema v2: document `references` registry + node `reference_ids`, `review_status` on nodes and annotations, `count_range` on vertebral regions; rules `finding.reference.missing`, `region.count_range.invalid`; tests; migration extending the schema CHECK + SQL issues; types regen; pgTAP.
- [x] 4c.2 packages/anatomy curation layer: changeset schema (Zod, JSON data), applier (set / rename / add / remove / move / cite / annotation ops), before-values captured by the applier, CHANGELOG + REVIEW-REPORT generators, diff v1 → draft; seed dir restructure: `legacy-import/` (baseline, generated) + `draft/` (curated working revision, seeded); cleaned SVG asset (legacy markers stripped), head view = view_box crop of the single asset.
- [x] 4c.3 research (parallel agents, WebSearch): axial skeleton + vertebral variation; skull/sutures/SBS/TMJ/hyoid; appendicular nomenclature NAV/Barone; osteopathic terminology + French legal scope + vet red flags; catalog analyzer pass. Output: findings with verifiable references, classified A/B/C.
- [x] 4c.4 content changes: sphenoid zone restructured (SSB tree duplicated under sphenoid), terminology (lésion → dysfonction, NAV names, FR grammar), 62 EN descriptions + EN disclaimer, vet flags audit, references registry + citations, additions (carpus…), SVG point moves (B, before/after renders), Cd range 15–21.
- [x] 4c.5 reports: REVIEW-REPORT.md for the osteopath (10 sections, questions ranked), CHANGELOG table, before/after review SVGs (draft/review/, PNG renders by operator), quantitative before/after.
- [ ] 4c follow-up (open, not blocking Step 5): 11 questions for the osteopath (draft/REVIEW-REPORT.md §10) → next changeset; legal scope text to re-read on consolidated Légifrance articles before publication; BLK-008 data migration v1→v2 before real data; user action `.env.example` COMPOSE_PROJECT_NAME=faunosteo (DEPLOY.md)
- [x] 4c.6 verify (root check 68+21+100+278, PGlite + real stack 267/267, types, docker build, Storage e2e; verifier ×3 → fixes, security PASS; EVAL-010): pnpm check, PGlite + real stack pgTAP, types, docker build, golden tests; gates verifier + security; docs (spec §6/§7, SUPABASE.md, CLAUDE.md, plan Step 4c, CHANGELOG); memory (BDR/LRN/EVAL/journal). Stop for user validation.
- [x] Step 5 — application on the canonical sheet (analysis validated 2026-10-10; implemented on feature/step-05-app-on-canonical-sheet; USER VALIDATED 2026-10-10, all paths OK; finished into develop 2026-10-10; D5 orphan findings documented as UX follow-up)
- [x] 5.0 freeze: golden v2 PDFs + expected v3 docs; CHARACTERIZATION_REPORT refreshed
- [x] 5.1 pipeline: report-migration-map.json (annotations, views, findingPaths 442/136/≤34), app-main.svg + app-head.svg review renders, category colours changeset (D1)
- [x] 5.2 packages/domain: Report v3 (annotationId+viewId, free region codes, severity codes D8, sheet ref, unresolved findings, localAnnotations []), migrateReportV2ToV3, tests on fixtures + 612 leaves
- [x] 5.3 app foundation: bundledSheetProvider (Vite alias @sheets), sheetIndex, sanitiser, renderAnnotationLayer (legacy look), AnatomyCanvas/DetailModal on views (head = crop)
- [x] 5.4 zoneInteraction service + reducers, store split + sessionStoragePersistence (v2 migration on load), pickers/cards on sheetIndex (D6 ranges, D7 title), EditorRoute < 300 lines
- [x] 5.5 PDF shim + attachment v3 + v2 import (gate D3)
- [x] 5.6 delete legacy (registry, species/*, zoneMatch, spineZones, svgConvention, D4 tools), SVG convention doc replaced, CLAUDE.md map, CHANGELOG, plan note, memory
- [x] 5.7 visual before/after (cmp renders), root check + docker + real stack green; verifier ×3 (gaps closed), security PASS (LOW fixed); EVAL-011. Manual FR/EN flow = user validation
- [x] 5.8 per-leaf migration (user ask 2026-10-10, during manual validation): every legacy leaf (612 = 442 identical, 141 moved, 29 removed) as a v2 finding → migrated → resolved to a draft leaf (anatomy, map file) and through sheetIndex.nodeAt + PDF roundtrip (app); the 27 legacy annotations as zones on their views
- [x] 5.9 archive check tool `pnpm report:compare <pdf|dir>...`: v2 attachment vs migrated v3 side by side, unresolved flagged (removed vs unknown), `--full` opt-in for names/free text, control chars escaped, --diff of two PDFs, --summary; attachment.ts split read/parse (additive, D3); docs PDF-FORMAT/CLAUDE/README
- [x] 5.10 final controls on the last lot: stale root script scaffold:species removed; verifier ×3 (2→1→CONFORME) + security ×2 PASS on criteria 16-18; EVAL-012
- [x] 5.11 user validation defect: findings picker text blurry on screen → permanent `will-change` on the list dropped (hotfix 1f0b710, regression test); PDF never affected
- [ ] 5.12 follow-up (not Step 5): equine sheet anatomical enrichment with the osteopath + future sheet editor (Step 17); the 28 draft annotations (carpus added, points moved) are NOT a final catalog
- [ ] Step 6 — autonomous PDF archives (analysis validated by user 2026-10-11 with D7 branding archived, D8 snapshot kept + explicit rebase, D13 messages → Part II contract + BDR-039; implementation on feature/step-06-pdf-archives, one executor per phase)
- [x] 6.0 analysis: 3 analyzers (pipeline, model, app/tests) + size measurements (envelope 172 KB raw / 51 KB stored for 3 obs, 228 / 54 worst case) + 3 plan-challengers → plan rewritten
- [x] 6.1 Phase 0 freeze (8b86b92: 39 goldens, demo fixture, bare v3 PDF, T12/T13; 206 app tests) with current code: demo report fixture, migrated-v2-with-unresolved builder, G3 bare v3 PDF, G1 text goldens (logos absent + present), G2 structural facts/placements/links, T12 HomeRoute + T13 EditorRoute characterisation
- [x] 6.2 Phase 1 domain (cdc0943: 154 domain tests, snapshot 171 KB raw on the fixture): sheet-index moved, archive/snapshot (buildSheetSnapshot, assertSnapshot, caps), archive/envelope (schema v1, layered readArchiveDocument, SnapshotRejection), report/rebase (rebaseReportOnSheet), bundle carries asset sha + status/name, tests
- [x] 6.3 Phase 2 anatomy (6940926: composeViewSvg + highlightLayer, 130 anatomy tests): render/compose.ts promoted from curation/app-review.ts, highlight on the layer tree, review drawing golden unchanged
- [x] 6.4 Phase 3 packages/pdf (c179560: 53 engine tests, 36 goldens exact, resvg raster, demo envelope 55 KB / 136 KB stored): scaffold (no DOM lib, restricted globals, vitest node, Dockerfile, CI, README), svg/sanitize allowlist + horse.svg zero-removal, render moved, Branding/Rasterizer/exportedAt/safeText/dict, exportReportArchive (T3 both logo modes), readReportArchive (filename-first, layered, attachment_stripped; T4-T6, T8), T1/T7/T9/T10 resvg/T11, xmldom bundle size ≤ 50 KB gz
- [x] 6.5 Phase 4 app (9bd5173: 222 app tests, archive kept in session, rebase + alerts, legacy PDF modules removed, xmldom ≈ 31 KB gz in the main chunk): browserRasterizer, branding.ts, export/import on the engine, rebase on import + draft restore, 2 new messages, old render/attachment/highlight code + pdf.* keys removed, report:compare on engine API, T2/T14/T15, suite migrated 1:1
- [x] 6.6 Phase 5 docs + gates (docs synced; verifier ECARTS(31 oracle/scope) → CONFORME 13/13; security BLOCK(1) → 4 fix loops → PASS; 656 tests, build, docker ×4 green)
- [x] 6.8 user manual tests round 1 (2026-10-11): logos and picker text confirmed OK by the user after branding bundled (293a6e0) and the investigation; restore-rebase alert (e8f1734); STEP 6 VALIDATED BY USER 2026-10-11
- [x] 6.9 closure decisions (BDR-040): re-export-archive button REFUSED for good; import headlines full/partial (62b8a43); BLK-009 byte-scan reader + no object streams (60ee712), fresh security audit + verifier; gate before external users kept in PDF_IMPORT_HARDENING.md §5
- [x] 6.10 finished into develop (c746952); release/0.2.0 prepped (dac75ab: version.txt, package versions, CHANGELOG) and pushed — AWAITING the user's "go" to finish into main + tag v0.2.0 (release-candidate STEP 4-6); Step 7 NOT started (UX/design discussion with ChatGPT first)
- [ ] 6.7 follow-ups recorded for Step 13: catalog asset cap aligned with the archive cap (2 MiB), allowlist sanitiser at upload, app canvas sanitiser (EVAL-011)
- [ ] 5 follow-up: allowlist SVG sanitiser before Storage-served assets (Step 13); orphan findings UX (D5) at the report UX step; report:compare residuals (ZodError reason genericised, v3 lines computed once, long template lines); 16 MiB attachment cap without direct test
---
## Phase A — DONE (kept for reference)
@@ -47,7 +123,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] Anatomy: parseSvgBones, loadSvg, svgToPng raster
- [x] Zustand store: full action set (initReport, hydrateReport, observation CRUD,
conclusion/recommendations/nextAppointment setters, identity setters)
- [x] sessionStorage draft mirror + localStorage practitioner cache
- [x] sessionStorage draft mirror + localStorage practitioner cache (restore path was missing until f58a49f 2026-07-12 — refresh now keeps the session)
- [x] UI primitives: Button, Card, Dialog, Input, Label, Select, Textarea, Badge, Chip
- [x] Canvas: AnatomyCanvas (data-state highlighting, async-mount safe), DetailModal
- [x] Observation chain: ObservationList, ObservationCard, PathologyPicker (flat — REMOVED, replaced by FindingsTreePicker B2),
@@ -123,7 +199,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] PDF QA manual pass: full flow → export → re-import roundtrip
- Fonts embed, JSON attached, multi-SVG grid OK, locale FR + EN exports
- [x] Docker build + compose up smoke test (VPS cold build validated — BLK-005, 990c8e7; local smoke not separately logged)
- [ ] env-var brand identity verified
- [x] env-var brand identity verified (tour 2026-07-12: docker run APP_BRAND_NAME=TourCheck → env.js correct, non-root; hostile-quotes case covered by 0214ae1)
- [x] README finalize (install, dev, Docker, env vars, locale, MIT)
- [x] CHANGELOG 0.1.0 entry
- [x] docs/PATHOLOGIES-FORMAT.md — schema doc + authoring guide (initial shipped 70f21cc 2026-05-20; refreshed for v2.0 boolean-only contract 2026-05-21 — scope section, 5 taxonomy patterns, structural rules, breaking-change notice, horse stats, changelog v1.0→v2.0)
@@ -144,9 +220,9 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
## Memory cross-refs
- BDR-001..BDR-008 — decisions registry
- LRN-001..LRN-010 — learnings registry
- BLK-001..BLK-004 — blockers (all resolved)
- BDR-001..BDR-022 — decisions registry
- LRN-001..LRN-031 — learnings registry
- BLK-001..BLK-005 — blockers (all resolved)
Apply when implementing B-phase:
- LRN-004 (data-anno-special opaque to parser) — zone IDs in JSON must match SVG `data-anno-id`
@@ -0,0 +1,27 @@
# CONTRACT — findings-picker-blur
- date: 2026-10-10 | flow: hotfix | branch: feature/step-05-app-on-canonical-sheet
- status: active
## REQUEST (verbatim — IMMUTABLE)
Un seul défaut visuel constaté : le texte des constats apparaît flou dans le sélecteur de constats. En revanche, il est net dans le PDF. Merci d'analyser la cause réelle (rendu CSS, transformations, mise à l'échelle, opacité, police, etc.) et de corriger ce problème sans modifier inutilement le design ou les interactions. Vérifie le résultat à l'écran, notamment sur desktop et mobile, et conserve les tests de non-régression.
## CLARIFICATIONS
none — request complete. Root cause located in the main loop (headless Chromium, Playwright): the `motion.ul` of `FindingsTreePicker` keeps a permanent inline `will-change: transform, opacity` after its 220 ms slide ends (computed transform `none`); the list sits at a fractional offset inside the height-animated card (left 561.1875 px desktop, top 735.765625 px mobile), so the composited text is resampled and blurs. The PDF never goes through that layer.
## ACCEPTANCE CRITERIA
1. The findings list carries no inline `will-change` (motion promotes the element itself during the slide).
CHECK: grep -n "willChange" apps/app/src/components/observation/FindingsTreePicker.tsx; echo "rc=$?"
EXPECT: rc=1
EVIDENCE: 2026-10-10 grep → no match, rc=1. MET.
2. A regression test asserts the rendered findings list has no inline will-change; every existing test kept.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/components.FindingsTreePicker.test.tsx 2>&1 | tail -3
EXPECT: Tests .* passed
EVIDENCE: 2026-10-10 appended to the existing picker test file (path corrected here, [gated 2026-10-10] main loop) → Test Files 1 passed, Tests 6 passed. App suite 182 passed (executor smoke). MET.
3. Symptom gone on screen (desktop 1280×1, mobile 390×2): computed `willChange` of the list is `auto` and the edge-sharpness ratio rises versus the before capture (main loop measures with the Playwright script, no executor action).
EVIDENCE: 2026-10-10 headless Chromium 1243: willChange "transform, opacity" → "auto" on both profiles. Sharpness ratio mobile 0.640 → 0.774 (visibly crisper), desktop 0.594 → 0.583 (flat: headless renders text without LCD antialiasing, so the desktop difference is not observable there; the compositing mechanism is removed, the user confirms in a real browser). PARTIALLY MET (mechanism + mobile proven; desktop by user).
4. build/tests green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`.
EVIDENCE: typecheck + lint pass, app 182 tests pass (executor smoke); full workspace rerun before gitflow finish.
## FILE SCOPE
apps/app/src/components/observation/FindingsTreePicker.tsx (delete the `style={{ willChange: 'transform, opacity' }}` prop on `motion.ul`)
apps/app/tests/unit/FindingsTreePicker.test.tsx (new or existing picker test file: one regression test)
@@ -0,0 +1,23 @@
# CONTRACT — step-06 bounded attachment extraction (BLK-009, options A + B)
- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives
- status: active
- spec: docs/development/PDF_IMPORT_HARDENING.md §2-§4
## REQUEST (IMMUTABLE)
Remove pdf-lib's parser from the import path: locate the Faunosteo attachment by scanning the PDF bytes, inflate it with the capped native inflater, never call `PDFDocument.load` on untrusted input in the browser. Export without object streams so the Filespec name and the Info keywords stay visible to the scanner. Existing archives (with object streams) must still import. Tests include an object-stream bomb that the new reader never inflates.
## ACCEPTANCE CRITERIA
1. `packages/pdf/src/attachment/scan.ts`: `findEmbeddedFiles(bytes: Uint8Array): EmbeddedFileCandidate[]` walks the bytes (bounded by `MAX_PDF_BYTES`) for stream dictionaries containing `/Type /EmbeddedFile` (also `/Type/EmbeddedFile` without space), reads a direct `/Length N` when present else locates `endstream`, handles `stream\r\n` and `stream\n`, records `{ offset, length, filter: 'FlateDecode' | null, name: string | null }` where `name` comes from a visible `/Filespec` dict whose `/EF << /F n 0 R >>` points at that stream's object number (object header `n 0 obj` before the dict), when visible; candidates ordered: named `osteo-report*` first, then file order. `readAttachmentBytes(bytes): Promise<Uint8Array>`: for each candidate, raw bytes (or `inflateFlate` under `MAX_ATTACHMENT_BYTES` when Flate) → first whose decoded text parses as JSON with a numeric `envelopeVersion` or `version` wins; none → `no_attachment`, or `attachment_stripped` when the bytes carry the keyword stamp (`/Keywords` followed by a literal `(…)` or hex `<…>` string decoding to a text containing `faunosteo-archive`).
CHECK: cd packages/pdf && corepack pnpm vitest run tests/scan.test.ts 2>&1 | grep -E "Tests " | tail -1
EXPECT: Tests .* passed
2. `readReportArchive(bytes, map)` uses the scanner only: `%PDF-` header check + size cap → `invalid_pdf`; no `PDFDocument.load` anywhere under `packages/pdf/src/read.ts` or `src/attachment/`; `readAttachedDocument` becomes `readAttachedDocument(bytes: Uint8Array): Promise<unknown>` (bytes, not a PDFDocument) and the compare CLI (`apps/app/scripts/compare-reports.ts`) uses it without loading the PDF.
CHECK: grep -rn "PDFDocument.load\|PDFDocument\.load" packages/pdf/src apps/app/scripts | wc -l
EXPECT: 0
3. Export: `pdfDoc.save({ useObjectStreams: false })`; a test asserts the saved bytes contain the literal `/Type /Filespec` with `(osteo-report.json)` (or its hex) in clear and no `/Type /ObjStm`; every golden suite stays green (goldens record text/images/links only).
4. Compatibility tests (`tests/scan.test.ts` + existing `read.test.ts`): the frozen fixtures `apps/app/tests/fixtures/report-v2.full.pdf`, `report-v2.minimal.pdf`, `report-v3.bare.pdf` (all written WITH object streams) import with the same outcomes as before; a fresh envelope PDF imports; a PDF with two embedded files (a decoy `EmbeddedFile` first, then the Faunosteo one) picks the Faunosteo one; a PDF whose `/Length` is an indirect reference (craft by hand) is read through the `endstream` fallback; `\r\n` after `stream`; a foreign PDF → `no_attachment`; a stamped PDF without attachment → `attachment_stripped` (write it with `useObjectStreams: false` so the stamp is visible; also document that older stamped files with object streams fall back to `no_attachment`).
5. Bomb test: a PDF containing an object stream (`/Type /ObjStm /Filter /FlateDecode`) whose data is a deflate bomb (≥ 64 MiB of zeros compressed to a few hundred KB, built in the test with node:zlib) plus a valid Faunosteo attachment: `readReportArchive` returns the report in under 2 s and the process RSS does not grow by more than 64 MiB (measure `process.memoryUsage().rss` before/after); the same bytes also carry an attachment-sized bomb variant: an `EmbeddedFile` stream inflating past 16 MiB → `no_attachment` (inflate cancelled), never a hang.
6. Docs: `docs/PDF-FORMAT.md` "Reading an archive" step 2 (byte scan, no object-graph parse, object streams never inflated) and "Known limits" (pdf-lib removed from the import path; remaining: CLI on the same scanner, pdf-lib kept for generation, prerequisites unchanged for external users); `docs/development/PDF_IMPORT_HARDENING.md` §4 marked done with the commit, §5 unchanged.
7. Green from the root: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`; `git diff --quiet 8b86b92 HEAD -- apps/app/tests/fixtures/goldens`.
## FILE SCOPE
packages/pdf/src/{attachment/scan.ts (new), attachment/read.ts, attachment/inflate.ts, read.ts, export.ts, index.ts, errors.ts}, packages/pdf/tests/** , apps/app/scripts/compare-reports.ts, apps/app/scripts/compare/report.ts, apps/app/tests/unit/scripts.compare.test.ts, apps/app/tests/unit/pdf.import.test.ts (if it loads a PDFDocument), docs/PDF-FORMAT.md, docs/development/PDF_IMPORT_HARDENING.md. Nothing else.
@@ -0,0 +1,27 @@
# CONTRACT — step-06 phase 0 freeze
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: active
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II (§17 goldens, §13 types for naming only)
## REQUEST (IMMUTABLE)
Freeze the current PDF pipeline behaviour before any refactor: new fixtures, goldens generated once with the current code, characterisation tests of the two routes. Production code under apps/app/src is NOT modified in this phase.
## ACCEPTANCE CRITERIA
1. Fixture `apps/app/tests/fixtures/report-v3.demo.json`: valid Report v3 on the bundled draft (ids taken from draft/document.json), 6 observations covering: main view zones, head view zone, a spine zone with vertebrae, a bilateral zone with left and right sides, a vet-referral leaf (`requiresVetReferral: true`), a leaf whose label holds an en dash (U+2013), free-text findings, severities, comment, conclusion, recommendations, nextAppointment; `sheet` = the draft ref.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/pdf.goldens.test.ts 2>&1 | tail -3
EXPECT: Tests .* passed
2. Goldens under `apps/app/tests/fixtures/goldens/step6/` exactly as spec §17 (text/images/links per report × locale × logo mode, views per report), generated by `MAKE_GOLDEN=1 corepack pnpm vitest run tests/unit/pdf.goldens.test.ts`, then asserted by the same file without the flag. Reports: v2full, demo, v2unresolved. Logo modes: nologos, logos.
CHECK: ls apps/app/tests/fixtures/goldens/step6 | wc -l
EXPECT: >= 20
3. Fixture `apps/app/tests/fixtures/report-v3.bare.pdf`: the demo report exported by the current code (rasteriser stubbed 1×1, no logos), produced by the same MAKE_GOLDEN run; `tests/fixtures/README.md` documents the new files and the rule "never regenerate without a user decision".
CHECK: test -s apps/app/tests/fixtures/report-v3.bare.pdf && echo ok
EXPECT: ok
4. Characterisation tests `tests/unit/routes.HomeRoute.import.test.tsx` and `tests/unit/routes.EditorRoute.export.test.tsx` as spec §17 (import mocked at module level; alert text with count; the three current error kinds + generic; navigation to /editor; export call shape; download name; failure alert).
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/routes.HomeRoute.import.test.tsx tests/unit/routes.EditorRoute.export.test.tsx 2>&1 | tail -3
EXPECT: Tests .* passed
5. Whole app suite, typecheck and lint green; no file under apps/app/src changed.
CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run 2>&1 | tail -4; git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l
EXPECT: Tests .* passed ; 0
## FILE SCOPE
apps/app/tests/** only (new test files, fixtures, goldens, helpers, README). No change under apps/app/src, packages/**, docs/**.
@@ -0,0 +1,26 @@
# CONTRACT — step-06 phase 1 domain
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: active
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (types), §14 "Read" steps 1-3 and "Bundle", §15 caps table (snapshot + branding rows), §2.2 (lean document content)
## REQUEST (IMMUTABLE)
Give the domain package the archive contracts (sheet snapshot, envelope v1, branding, labels), the layered reader, the report rebase, and move the sheet index into the domain; make the bundle carry the asset hashes. Pure TypeScript + Zod, no DOM, no pdf-lib. The app keeps compiling and its suite stays green through re-export shims; no app behaviour changes in this phase.
## ACCEPTANCE CRITERIA
1. `packages/domain/src/anatomical-sheet/sheet-index.ts` holds `buildSheetIndex`, `pickLabel`, `isObservable`, `SheetIndex`, `ObservableAnnotation`, `SheetIndexSource = { ref: { documentSha256: string }; document: AnatomicalSheetDocument; assets: Readonly<Record<string, string>> }` (generic so `SheetIndex['sheet']` keeps the caller's type: `buildSheetIndex<S extends SheetIndexSource>(sheet: S): SheetIndex<S>`); `pickLabel(text, locale: 'fr' | 'en')`. `apps/app/src/services/sheetIndex.ts` becomes a re-export of it (no other app file edited for this move).
CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm vitest run tests/unit/sheets.provider.test.ts 2>&1 | tail -2
EXPECT: passed
2. `packages/domain/src/archive/` with `snapshot.ts` (`SheetSnapshotRef`, `SheetSnapshotAsset`, `SheetSnapshot`, `SheetSnapshotSchema`, `SnapshotSource`, `buildSheetSnapshot`, `assertSnapshot`, `SnapshotError`, `SnapshotRejection`, `snapshotIndexSource(snapshot): SheetIndexSource`), `branding.ts` (`ImageAsset`, `Credit`, `Branding`, `BrandingSchema`), `labels.ts` (`PDF_LABEL_KEYS`, `PdfLabels`, `PdfLabelSet`, `PdfLabelSetSchema`), `envelope.ts` (`ENVELOPE_FORMAT`, `ENVELOPE_VERSION`, `ReportArchiveEnvelope`, `ReportArchiveEnvelopeSchema`, `ArchiveOrigin`, `ArchiveReadOutcome`, `readArchiveDocument`), `index.ts`; exported as `@faunosteo/domain/archive` (package.json exports) and from the root index. Types and behaviour exactly as spec §13/§14; `SnapshotSource = { status; ref: SheetRef; speciesId; schemaVersion; document; assets; assetHashes? }` so that `LoadedSheet` satisfies it; snapshot `ref` = `{ ...sheet.ref, schemaVersion, speciesId }`.
CHECK: cd packages/domain && corepack pnpm vitest run tests/archive.snapshot.test.ts tests/archive.envelope.test.ts tests/archive.branding-labels.test.ts 2>&1 | tail -3
EXPECT: Tests .* passed
3. `buildSheetSnapshot(sheet, report)` is pure and deterministic: document = all views, annotations, categories, vertebral_config, name/description/scope_disclaimer/attribution/species_id/schema_version kept; `references: []`; every finding zone kept as `{ id, name, categories }` where categories are pruned to the paths referenced by the report's findings (resolved or `unresolved`): category `{ id, kind, name, description: {}, reference_ids: [], review_status, children }`, node `{ id, name, description: {}, requires_vet_referral, reference_ids: [], review_status, children }`; zones not referenced have `categories: []`; assets = every asset reachable from a view (own `svg_asset_id` or parent chain), `sha256` from `assetHashes` or null. On the draft with the fixture report `apps/app/tests/fixtures/report-v2.full.json` migrated: the document passes `AnatomicalSheetDocumentSchema` and `validateSheetDocument` returns no `error` issue; pretty JSON of the snapshot (with the SVG) is under 250,000 bytes (print the number in the test output).
4. `assertSnapshot` order: iterative depth pre-check of `finding_zones[].categories[].children` (> 8 → `caps`) → `SheetSnapshotSchema.parse` (strict wrapper; failure → `schema`) → counters (views ≤ 64, annotations ≤ 1024, nodes ≤ 8192, any LocalizedText value > 512 chars, assets ≤ 4 / ≤ 2 MiB each / ≤ 6 MiB total → `caps`) → `validateSheetDocument` has an `error` → `integrity` → a view that reaches no asset present in `assets` → `integrity`. Tests cover each reason and the happy path.
5. `readArchiveDocument(data, map)` implements spec §14 "Read" steps 1-3 exactly, with these cases tested: bare v3 → `origin 'bare_v3'`, `archive null`, counts 0; bare v2 (fixture) → `'v2'`, `migrated true`, counts from the migration; envelope v1 valid → `'envelope_v1'`, `archive` = validated envelope, `migrated false`; envelope with `envelopeVersion: 2` and report v3 → report returned, `snapshotRejected 'unsupported_envelope'`; envelope v1 with report `version: 4` → throws `UnsupportedReportVersionError` with foundVersion 4; envelope v1 with unknown extra metadata key → accepted; envelope v1 with broken branding → `'schema'`; snapshot over caps → `'caps'`; snapshot ref sheetId/documentSha256 ≠ report.sheet → `'sheet_mismatch'`; `__proto__` keys harmless; non-object → throws.
6. `packages/domain/src/report/rebase.ts`: `rebaseReportOnSheet(report, index, archived)` as spec §13; tests: same sha → untouched, `rebased false`; different sha → unknown annotation → `unresolved: true` + labels from the archived snapshot's annotation name (both locales) when the zone had none; unknown viewId → unresolved; finding with no node → unresolved; already-unresolved items stay; resolved items untouched; `report.sheet` replaced by `index.sheet.ref`; output passes `ReportSchema`.
7. Bundle: `apps/app/vite/sheet-bundle.ts` payload gains `assetHashes` (from `assets.json` `sha256` by `svg_asset_id`); `apps/app/src/sheets/provider.ts` `BundledSheetData`/`LoadedSheet` gain `assetHashes: Readonly<Record<string, string>>` and `schemaVersion: number` (from `ref.schema_version`); `parseBundledSheet` fills them; `tests/unit/sheets.provider.test.ts` asserts the hash of the horse asset equals the manifest value.
8. Green everywhere: `corepack pnpm -r typecheck && corepack pnpm -r lint && corepack pnpm -r test:run` from the repo root (domain, anatomy, supabase, app). The Phase 0 golden tests and route characterisation tests under apps/app/tests must pass unchanged.
CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm typecheck 2>&1 | tail -2 && corepack pnpm test:run 2>&1 | grep -E "Tests|Test Files" | tail -8
EXPECT: all passed
## FILE SCOPE
packages/domain/** (src/anatomical-sheet/sheet-index.ts new, src/archive/* new, src/report/rebase.ts new, index files, package.json exports, tests/archive.*.test.ts, tests/report.rebase.test.ts, tests/sheet-index.test.ts), apps/app/src/services/sheetIndex.ts (re-export only), apps/app/vite/sheet-bundle.ts, apps/app/src/sheets/provider.ts, apps/app/src/sheets/virtual-sheet.d.ts if needed, apps/app/tests/unit/sheets.provider.test.ts. Nothing under apps/app/src/pdf, packages/anatomy, packages/pdf.
@@ -0,0 +1,25 @@
# CONTRACT — step-06 phase 2 compose
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: active
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "composeViewSvg", §13 (Rasterizer not in scope here)
## REQUEST (IMMUTABLE)
Promote the Node-side view composer of the curation pipeline (`packages/anatomy/src/curation/app-review.ts`) into the shared renderer as `composeViewSvg`, with an optional highlight applied on the LayerElement tree before it becomes DOM, so the PDF engine (Phase 3) can compose a highlighted view without a browser and without querySelector. The review drawings stay byte-identical.
## ACCEPTANCE CRITERIA
1. `packages/anatomy/src/render/compose.ts` exports `composeViewSvg(input: { root: Element; document: AnatomicalSheetDocumentInput; viewId: string; highlight?: { annotationIds: ReadonlySet<string>; halo: boolean } }): Element` and `HALO_FILTER_ID = 'osteo-halo'`; it uses only DOM Level 2 APIs on `root` and `root.ownerDocument` (no xmldom import, no querySelector, no `el.remove()`); exported from `packages/anatomy/src/render/index.ts`.
CHECK: grep -n "querySelector\|\.remove()\|xmldom" packages/anatomy/src/render/compose.ts; echo "rc=$?"
EXPECT: rc=1
2. Without `highlight`, output = today's `renderAppReviewDrawing` output: `curation/app-review.ts` becomes a thin caller (parse with xmldom, call `composeViewSvg`, serialise) and the committed review drawings do not drift.
CHECK: cd packages/anatomy && corepack pnpm test:run 2>&1 | tail -3
EXPECT: Tests .* passed (including the existing golden-artifacts test)
3. With `highlight`: only layer elements whose annotation id is in `annotationIds` remain; each gets `fill="#b85a3f"`, `fill-opacity="0.85"` and, when `halo`, `filter="url(#osteo-halo)"`; no `data-*` attribute is emitted on any layer element; `<title>` children are kept; when `halo`, a `<defs>` (created as FIRST child when the asset has none) holds the `osteo-halo` filter exactly as `apps/app/src/pdf/render/observationPage.ts:157-197` (x/y "-100%", width/height "300%", filterUnits userSpaceOnUse, feGaussianBlur stdDeviation 18 result haloWide, feGaussianBlur stdDeviation 8 result haloTight, both in=SourceGraphic, feMerge of haloWide×3, haloTight×2, SourceGraphic); the layer `<g>` is appended last; `viewBox` set from `viewBoxOf(view)` when present; `width`/`height` removed from the root.
CHECK: cd packages/anatomy && corepack pnpm vitest run tests/render.compose.test.ts 2>&1 | tail -3
EXPECT: Tests .* passed
4. Tests (xmldom, draft document + draft horse.svg): main view with two selected annotations (one point → both hitbox and twin highlighted, one spine zone), head view (no halo), nothing selected (layer empty), unknown view throws, idempotent halo (no duplicate filter when called on a root that already has one), highlight keeps `<title>`, zero `data-` attributes in the serialised output, review-mode output byte-identical to the previous `renderAppReviewDrawing` for both views.
5. `pnpm typecheck && pnpm lint && pnpm test:run` green in packages/anatomy; no other package changed.
CHECK: git -C /home/bchanot/Documents/faunosteo status --short | grep -v "^?? packages/anatomy\|^ M packages/anatomy" | grep -v ".claude/" | wc -l
EXPECT: 0
## FILE SCOPE
packages/anatomy/src/render/compose.ts (new), packages/anatomy/src/render/index.ts, packages/anatomy/src/curation/app-review.ts, packages/anatomy/tests/render.compose.test.ts (new). Nothing else.
@@ -0,0 +1,29 @@
# CONTRACT — step-06 phase 3 engine
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: active (phases 1 and 2 landed)
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §13 (packages/pdf block), §14 (Export, Label policy, View SVG, Read), §15 (caps, sanitiser, text), §17 (goldens the engine must reproduce), §3.3
## REQUEST (IMMUTABLE)
Create `packages/pdf` (`@faunosteo/pdf`): the browser-free PDF engine that exports a report archive from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, exportedAt) and reads an archive back (layered reading). Render code moves from `apps/app/src/pdf` with its behaviour frozen by the Phase 0 goldens. The app is NOT wired in this phase (Phase 4); `apps/app/src` is not modified.
## ACCEPTANCE CRITERIA
1. Package scaffold: `packages/pdf/{package.json,tsconfig.json,vitest.config.ts,eslint.config.js,src/,tests/}` following packages/domain conventions; dependencies `pdf-lib ^1.17.1`, `@pdf-lib/standard-fonts ^1.0.0` (for `Encodings.WinAnsi`), `@faunosteo/domain workspace:*`, `@faunosteo/anatomy workspace:*`, `@xmldom/xmldom ^0.9.8`; devDependencies as domain plus `@resvg/resvg-js` (latest 2.x) and `@pdf-lib/upng ^1.0.1` (PNG decode in tests); tsconfig `lib: ["ES2022"]`, `types: ["node","vitest/globals"]`; eslint on `src/**`: `no-restricted-globals` for fetch, window, document, Image, DOMParser, XMLSerializer, navigator, Buffer, process, require and `no-restricted-imports` for patterns `@/*`, `react*`, `node:*`; vitest `environment: 'node'`. Dockerfile copies `packages/pdf/package.json`; `packages/README.md` row updated.
CHECK: cd packages/pdf && corepack pnpm typecheck && corepack pnpm lint && echo ok
EXPECT: ok
2. Public API of `packages/pdf/src/index.ts` exactly spec §13: `exportReportArchive`, `exportFromEnvelope`, `readReportArchive`, `readAttachedDocument`, `ArchiveReadError` (kinds invalid_pdf | no_attachment | attachment_stripped | incompatible_version), `ArchiveExportError` (kinds snapshot_invalid | snapshot_too_large | sheet_mismatch | too_many_pages), `Rasterizer`, `ExportInput`, `ExportResult`, `ExportWarning`, `PdfLocale`, `defaultPdfLabels`, `PDF_KEYWORD`, `MAX_PDF_BYTES`, `MAX_ATTACHMENT_BYTES`, plus `composeHighlightedViewSvg(sheet: SheetSnapshot, viewId, observation): string` for tests and the app.
3. Export behaviour = spec §14 "Export" steps 1-10 and "Label policy"; branding images: `kind 'png'` → base64 decoded with `atob` → `embedPng`; `kind 'svg'` → sanitised + rasterised at width 1200 (height from its viewBox, same clamp) → `embedPng`; each slot fails alone (`logo_failed` warning); view raster failure → page without image + `view_raster_failed`; parallel rasterisation, sequential embedding in view order; `exportedAt` drives every date; `setKeywords([PDF_KEYWORD])`; envelope attached pretty-printed as `osteo-report.json`, description `Faunosteo report archive v1`.
4. Goldens (T3): `tests/goldens.test.ts` reproduces every Phase 0 golden under `apps/app/tests/fixtures/goldens/step6/` for the three reports (v2full migrated through the draft map, demo, v2unresolved rebuilt with the same recipe as Phase 0 — reuse the recipe by reading `apps/app/tests/helpers/legacyLeaves.ts` logic, copy what you need into `tests/helpers/`), two locales, two logo modes: text entries (page, text, x, y, size, font) identical; images identical; links identical (Phase 0 recorded images and links PER LOCALE: `images.<report>.<locale>.<logos>.json`, `links.<report>.<locale>.<logos>.json`, because the footer centres the powered-by block on the label width); views facts identical except `titles` and `dataAttributes` (hidden markers are absent in the engine and the layer `<g>` loses its `data-layer`/`data-view-id`: assert `titles` ≥ highlighted count and `dataAttributes === 0` instead of the golden's 2). Logo modes: `nologos` = Branding with every logo null and credits with fallback texts, fake rasterizer returning the 1×1 PNG; `logos` = Branding built from the real `apps/app/public` files (PNG base64, Paws SVG), fake rasterizer returning the 2×1 PNG for views AND for the partner SVG (same constants and the same single stub as Phase 0, see `apps/app/tests/helpers/goldens.ts`). Compose through `composeViewSvg` from `@faunosteo/anatomy/render` (generic `root: ComposeElement`, xmldom `Element` satisfies it) with `highlight: { annotationIds, halo: view.kind === 'main' }`. Any mismatch is a visible change: do not "fix" the golden; report it.
CHECK: cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -3
EXPECT: Tests .* passed
5. T1 no-sheet re-export (`tests/reexport.test.ts`): export demo from a snapshot built with `buildSheetSnapshot` on the draft loaded from `supabase/seed/anatomical-sheets/equine/draft/` → `readReportArchive` → `exportFromEnvelope` → identical text/images/views facts; envelope deep-equal minus `exportedAt`; the test file imports nothing that knows the draft after the first export (the second export receives only the envelope).
6. Read (`tests/read.test.ts`, T4 T5 T6): roundtrip envelope → `readReportArchive` → `archive` deep-equals the exported envelope, `origin 'envelope_v1'`; `apps/app/tests/fixtures/report-v2.full.pdf` and `report-v2.minimal.pdf` → `'v2'`, migrated, then re-export → import again equals; the 612-leaf v2 report (recipe from legacyLeaves) → 29 unresolved findings kept through export/import; `report-v3.bare.pdf` → `'bare_v3'`, `archive null`; envelope v2 wrapper → report kept + `snapshotRejected 'unsupported_envelope'`; envelope v1 with report v4 → `incompatible_version` foundVersion 4; bare `version: 7` → 7; a PDF with `Keywords` containing `faunosteo-archive` and no attachment → `attachment_stripped`; a foreign PDF → `no_attachment`; the Filespec named `osteo-report.json` is chosen over an earlier unrelated `EmbeddedFile` in a crafted PDF; > 50 MiB → `invalid_pdf`.
7. Security (`tests/security.test.ts`, T8): 5 assets, a 3 MiB asset, depth 9, 1,025 annotations, a view chain cycle, a dangling `svg_asset_id`, `sheet_mismatch` → report imported and `snapshotRejected` with the right reason; hostile SVG assets (`<script>`, `onload`, `javascript:` href, external `<image>`, `<!ENTITY>`, `<style>` with `url(http…)`, 257 `<use>`, root `viewBox="0 0 1 100000"`) → removed / refused / clamped as spec §15, the export still succeeds for the removable ones with the hostile parts gone, and `assertSnapshot` refuses the oversized ones at export with a typed error and no file; `__proto__` ids harmless; 24 MB inflate bomb → null (move the existing test); `horse.svg` and `Paws_in_harmony.svg` sanitise with `removed: []` and a serialisation byte-identical to the parsed input.
8. Text (`tests/text.test.ts`, T9): `safeText` keeps en dash, em dash, accented letters, `•`, `·`; replaces `⚠`, `→`, an emoji by `?`; strips `\t`, U+2028, ESC; `wrapLines` and every drawText go through it (a report with `⚠` in a comment exports without throwing); `formatDate` returns a non-ISO input unchanged.
9. Raster (`tests/raster.test.ts`, T10, resvg): a real `Rasterizer` built on `@resvg/resvg-js` (`fitTo width`) renders the demo report's main and head highlighted views: PNG width = 1200, height = requested ±1, pixels within ±24 of `#b85a3f` present, non-white ratio in [0.01, 0.9]; a rasterizer that throws yields a PDF whose page has no image and one `view_raster_failed` warning.
10. Size (T7): demo envelope attachment stored bytes (the EmbeddedFile stream `contents.length` found through `enumerateIndirectObjects`) < 250,000; the test prints stored and raw sizes for `nologos` and `logos` brandings.
11. Everything green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` in packages/pdf, and `corepack pnpm -r typecheck` at the root; `apps/app/src` untouched.
CHECK: git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l
EXPECT: 0
## FILE SCOPE
packages/pdf/** (new), Dockerfile (one COPY line), packages/README.md (one row), pnpm-lock.yaml (install). Nothing under apps/app/src, packages/domain, packages/anatomy.
@@ -0,0 +1,24 @@
# CONTRACT — step-06 phase 4 app
- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives
- status: draft (dispatched after phase 3 lands)
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II §14 "App session", "Branding in the app", §16 messages, §17 (T12/T13 kept green), Part I §7 T2/T14/T15
## REQUEST (IMMUTABLE)
Wire the application onto `@faunosteo/pdf`: export through the engine with a snapshot, branding and the browser rasterizer; import through the engine with layered reading, kept archive and explicit rebase; new import messages; old PDF code removed; `report:compare` on the engine read API. No visual change to pages or app layout; alerts follow the existing `window.alert` pattern.
## ACCEPTANCE CRITERIA
1. `apps/app/src/pdf/` contains only: `export.ts` (`exportReportToPdf(report, index, { locale }): Promise<Uint8Array>` kept as the route-facing signature, implemented as `exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), branding: await loadBranding(), labels: defaultPdfLabels, locale, rasterizer: browserRasterizer, exportedAt: new Date() })`, warnings → `console.warn`), `import.ts` (`importReportFromPdf(bytes, map)` returning the engine's `ArchiveReadOutcome`; `ImportError` kinds `invalid_pdf | incompatible_version | no_attachment | attachment_stripped` mapped 1:1 from `ArchiveReadError`), `browserRasterizer.ts` (today's `svgToPng.ts` adapted to `(svg, { widthPx, heightPx }) => Promise<Uint8Array>`: the engine computes the size, the adapter sets width/height on the root and draws), `branding.ts` (`loadBranding(): Promise<Branding>` per spec §14). `render/`, `attachment.ts`, `fonts.ts`, `src/anatomy/drawing.ts`'s highlight code are deleted; `drawing.ts` keeps `buildViewSvg`/`parseDrawing`/`sanitizeSvg` for the canvas (unchanged behaviour).
CHECK: ls apps/app/src/pdf
EXPECT: branding.ts browserRasterizer.ts export.ts import.ts
2. Store/persistence per spec §14 "App session": `archive: ReportArchiveEnvelope | null` in `ReportStore`, `hydrateImport({ report, archive })`, `initReport`/`reset`/`hydrateReport` clear it, `osteo:archive` key written only on those actions, `restoreDraft(index)` rebases a stale draft and restores the archive; `ArchivePersistence` beside `ReportPersistence`; tests in `state.reportStore.test.ts` extended (archive kept across a draft restore, cleared on new report, not rewritten on edits: spy on setItem).
3. `HomeRoute`: `importReportFromPdf` → `rebaseReportOnSheet(outcome.report, sheet.index, outcome.archive?.sheetSnapshot ?? null)` → `hydrateImport` → one alert composed per spec §16 (lines: migrated / archive_ok / snapshot_rejected with reason label / rebased with count) → `/editor`; error mapping adds `attachment_stripped`. `EditorRoute` export path unchanged for the user (download name, failure alert). The Phase 0 characterisation tests `routes.HomeRoute.import.test.tsx` and `routes.EditorRoute.export.test.tsx` stay green with at most these edits: the mocked outcome objects gain `origin`/`archive` fields, and the export call-shape assertion stays `(report, index, { locale })`.
4. i18n: keys of spec §16 added to fr.ts and en.ts with the given wording; `pdf.*` keys removed from both app dicts (the engine owns them; `severity.*`, `lateral.*`, `footer.*` stay, the UI uses them); `i18n.keys.test.ts` parity green.
5. `scripts/compare-reports.ts` + `scripts/compare/report.ts`: read through `readAttachedDocument` from `@faunosteo/pdf` and `readArchiveDocument` from `@faunosteo/domain/archive`; an envelope prints one extra header line `archive v1 (snapshot kept | snapshot rejected: <reason>)` under the same escaping rules; `scripts.compare.test.ts` green.
6. New tests: `pdf.export.app.test.ts` (T2: export the demo fixture through `exportReportToPdf` with the real bundled sheet, then mutate a cloned LoadedSheet's labels and one geometry, re-export the ENVELOPE through `exportFromEnvelope` and assert the engine output facts equal the first export, not the mutated sheet; T13 call shape covered by Phase 0), `pdf.goldens.test.ts` adapted so the app export path reproduces the Phase 0 goldens through the engine (same spies; the `rasterizeSvg` mock becomes a mock of `@/pdf/browserRasterizer`), `routes.HomeRoute.archive.test.tsx` (T15: envelope import with same sha → archive kept in store, archive_ok alert; envelope whose sha differs → rebased alert with count, unresolved flags, labels filled, `report.sheet` updated; snapshot rejected outcome → snapshot_rejected alert with the reason label; `attachment_stripped` → its error message), `migration.leaves.test.ts` kept green (612 leaves through the new path).
7. Bundle cost: `SHEET_BUNDLE=draft corepack pnpm build` in apps/app succeeds; report the gzip size of the main JS chunk before (from `git stash`-free method: build develop in a worktree is NOT allowed; instead read the size printed by vite for the chunk containing xmldom and report the total gz of dist/assets/*.js) and the size of the xmldom portion if vite's output isolates it; ceiling 50 KB gz for xmldom's share, else report.
8. Green: from the repo root `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build`; `grep -rn "fetch(" apps/app/src/pdf` shows only `branding.ts`.
CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm test:run 2>&1 | grep -E "Test Files|Tests " | tail -8
EXPECT: all passed
## FILE SCOPE
apps/app/src/pdf/**, apps/app/src/anatomy/drawing.ts (removal of highlight-only code if any), apps/app/src/app/routes/{HomeRoute,EditorRoute,NewReportRoute}.tsx (minimal), apps/app/src/state/{reportStore,persistence}.ts, apps/app/src/i18n/{fr,en}.ts, apps/app/scripts/**, apps/app/package.json (dependency `@faunosteo/pdf: workspace:*`, drop `pdf-lib` only if no app code imports it anymore), apps/app/tests/** (adaptations named above; goldens JSON files never edited), CLAUDE.md folder map lines for apps/app/src/pdf (keep docs minimal; Phase 5 owns the docs). Nothing under packages/**.
@@ -0,0 +1,17 @@
# CONTRACT — step-06 security fix 2 (after re-audit PASS with 2 MEDIUM)
- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives
- status: active
## REQUEST (IMMUTABLE)
Close the two MEDIUM findings of the second audit without changing any page output: (1) the `/URI` written as `PDFHexString.fromText` is UTF-16BE with a BOM, so poppler-based viewers read a dead link (`þÿ…`); write the URL's ASCII bytes as a hex string instead, keeping the injection protection; (2) the PNG budget reads only the first IHDR while UPNG honours the last one: walk the chunk list, require exactly one IHDR (length 13) as the first chunk, refuse any later IHDR and the APNG chunks `acTL`, `fcTL`, `fdAT`.
## ACCEPTANCE CRITERIA
1. `packages/pdf/src/render/linkAnnotation.ts` writes `URI: PDFHexString.of(<hex of the ASCII bytes>)`; a test asserts the saved bytes contain the hex form of `https://faunosteo.com` (uppercase or lowercase hex, no `FEFF`), that a reload through pdf-lib decodes `/URI` to the URL, and that the injection payload (cast past the schema) still yields no `/JavaScript`, `/Next` or `/JS` in the bytes. A character above 0x7e in the URL throws (the schema already refuses it) — test.
CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts tests/goldens.test.ts 2>&1 | grep -E "Tests " | tail -1
EXPECT: Tests .* passed
2. `packages/pdf/src/branding.ts` `pngHeaderIssue` walks chunks (length, type, data, CRC) until `IEND` or the end of the buffer: first chunk must be `IHDR` with length 13; any further `IHDR`, or `acTL`/`fcTL`/`fdAT`, or a chunk length that overruns the buffer → issue; the existing side/pixel caps stay. Tests: doubled IHDR (1×1 then 10000×10000) refused, APNG with `acTL` refused, truncated chunk length refused, the four real `public/` logos and the two fixture PNGs accepted; the export-level test asserts a doubled-IHDR header logo gives exactly `[{ kind: 'logo_failed', slot: 'headerLogo' }]` and `embedPng` never receives it.
3. `docs/PDF-FORMAT.md`: the PNG sentence says the chunk list is walked and a second IHDR or APNG chunk is refused (replace any "never decoded" wording); "Known limits" names the browser rasterizer (`apps/app/src/pdf/browserRasterizer.ts`) as the production path whose `<use>` expansion limits are not measured.
4. Green from the root: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run`; `git diff --quiet 8b86b92 HEAD -- apps/app/tests/fixtures/goldens` (goldens untouched); link goldens still pass in both packages (the readers decode hex strings).
## FILE SCOPE
packages/pdf/src/render/linkAnnotation.ts, packages/pdf/src/branding.ts, packages/pdf/tests/security.test.ts (and tests/helpers if a reader needs the ASCII-hex form), docs/PDF-FORMAT.md. Nothing else.
@@ -0,0 +1,23 @@
# CONTRACT — step-06 security fix (after SECURITY BLOCK(1) + MEDIUM/LOW findings)
- date: 2026-10-11 | flow: ship-feature (executor, security loop) | branch: feature/step-06-pdf-archives
- status: verified (CONFORME on substance after oracle fix; security re-audit pending)
## REQUEST (IMMUTABLE)
Close the HIGH finding (PDF object injection through an archived branding URL) at the sink and at the schema, and the cheap MEDIUM/LOW findings listed below. No behaviour change for valid inputs: the Step 6 goldens must stay green. Findings deferred with a documented limit: pdf-lib uncapped object-stream inflation (pre-existing, needs a Worker or a pre-scan that would refuse our own PDFs), `<use>` nesting expansion (resvg already refuses), Report v3 collection caps on read.
## ACCEPTANCE CRITERIA
1. HIGH sink: `packages/pdf/src/render/linkAnnotation.ts` writes the URI as `PDFHexString.fromText(url)` (or escapes `\`, `(`, `)` and refuses control characters) so no URL can close the string literal; a test exports a PDF whose branding URL is `https://a.example/) /Next << /S /JavaScript /JS (app.alert\(1\)) >> /Z (` through `exportFromEnvelope` AFTER bypassing the schema with a cast, reloads the bytes with pdf-lib and asserts no `/JavaScript` action exists and the link's `/URI` decodes to the full original string (or the export is refused by criterion 3, in which case the test asserts the typed refusal and a second test proves the sink escaping on a URL with `)` that the schema accepts, if any).
CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts 2>&1 | grep -E "Tests " | tail -1
EXPECT: Tests .* passed
EVIDENCE: 2026-10-11 verifier pass 1 ECARTS(1) = this oracle (`tail -2` kept only the Duration line), behaviour MET (33/33, sink + schema + refusal tests read). Oracle corrected by the orchestrator; literal run → `Tests 33 passed (33)`. MET.
2. Schema: `HttpUrlSchema` in `packages/domain/src/archive/branding.ts` accepts only `^https?://[^\s()\\<>"'\x00-\x1f\x7f]+$` (ASCII, no parentheses, backslash, quotes, angle brackets, whitespace, control characters) and ≤ 2048 chars; the current real URLs (`https://faunosteo.com`, `https://zenquality.fr`, `https://www.instagram.com/paws.iin.harmony`) pass; domain tests cover accept/reject.
3. Export re-validates its inputs: `exportReportArchive` runs `BrandingSchema.parse(input.branding)` and `PdfLabelSetSchema.parse(input.labels)` first; a failure → `ArchiveExportError('branding_invalid')` (new kind, documented) before any page is drawn; test.
4. PNG budget: `packages/pdf/src/branding.ts` reads the PNG IHDR (signature + width/height at bytes 16-23) before `embedPng`; refuse when width × height > 16,777,216 (4096²) or either side > 8192, or when the signature is wrong → that slot fails alone with a `logo_failed` warning; test with a crafted IHDR.
5. Sanitiser hardening in `packages/pdf/src/svg/sanitize.ts`: any attribute value containing a backslash `\` is removed; in `style` attributes and in every presentation attribute, any `(` not part of `url(#` is refused (attribute removed); `image-set(`, `expression(`, `@import`, `javascript:`, `behavior:` refused as today. `horse.svg` and `Paws_in_harmony.svg` still sanitise with `removed: []` (existing test stays green); new tests for `u\72l(`, `image-set(`, `fill="u\72l(http://evil/x)"`.
6. NaN guard: `packages/pdf/src/svg/view.ts` raster size uses `Number.isFinite` on the view box numbers; a non-finite or ≤ 0 box falls back to the 0.6 ratio; test with `viewBox="0 0 1e999 1e999"` → a valid size, no NaN.
7. `apps/app/src/app/routes/HomeRoute.tsx` checks `file.size > MAX_PDF_BYTES` before `arrayBuffer()` and maps it to the `invalid_pdf` message; route test updated (`routes.HomeRoute.import.test.tsx` gains one case, others unchanged).
8. `docs/PDF-FORMAT.md` "Limits" gains: the URL rule, the PNG budget, and a "Known limits" paragraph: pdf-lib inflates PDF object streams without a cap when loading (a crafted PDF of a few hundred KB can expand to hundreds of MB in the tab; mitigation planned: parse in a Worker or locate the attachment without a full load), `<use>` expansion bounded by the rasterizer, Report collections not capped on read (export refuses above 500 observations).
9. Green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` from the root; goldens untouched (`git diff --stat 8b86b92 HEAD -- apps/app/tests/fixtures/goldens` empty).
## FILE SCOPE
packages/pdf/src/{render/linkAnnotation.ts,export.ts,errors.ts,branding.ts,svg/sanitize.ts,svg/view.ts,index.ts}, packages/pdf/tests/**, packages/domain/src/archive/branding.ts, packages/domain/tests/archive.branding-labels.test.ts, apps/app/src/app/routes/HomeRoute.tsx, apps/app/tests/unit/routes.HomeRoute.import.test.tsx, docs/PDF-FORMAT.md. Nothing else.
@@ -0,0 +1,51 @@
# CONTRACT — step-06 autonomous PDF archives (whole step, for the fresh verifier)
- date: 2026-10-11 | flow: ship-feature | branch: feature/step-06-pdf-archives
- status: active
- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md (Part II binding), docs/PDF-FORMAT.md; phase contracts 2026-10-11-step-06-phase-{0,1,2,3,4}-*.md
## REQUEST (verbatim user requirements, 2026-10-11 — IMMUTABLE)
Un PDF Faunosteo doit rester lisible, interprétable et réexportable dans le futur, même si : la fiche anatomique originale a disparu ; le catalogue de constats a changé ; les identifiants ou les traductions ont évolué ; le logo Faunosteo a changé ; les ressources du site ne sont plus disponibles ; le bilan contient des éléments hérités ou non résolus. L'export ne doit nécessiter aucun chargement réseau. Preuve automatisée des scénarios : (1) exporter un bilan v3, supprimer l'accès à sa fiche actuelle, puis l'importer et le réexporter depuis son instantané ; (2) modifier le catalogue anatomique courant sans affecter l'interprétation des anciennes archives ; (3) modifier le branding courant sans altérer les ressources historiques d'une archive réexportée ; (4) importer un PDF v2, migrer son bilan et conserver ses éventuels éléments non résolus ; (5) comparer le contenu et le rendu des PDF FR/EN aux références enregistrées avant la refactorisation ; (6) rejeter proprement les instantanés dangereux, invalides ou excessivement volumineux, sans perdre les données récupérables du bilan ; (7) vérifier qu'aucun chargement réseau n'est nécessaire à la génération ; (8) tester la rasterisation réelle des SVG. Aucun changement graphique des pages. Instantané importé conservé en session, rebase explicite sur copie de travail. Messages FR/EN explicites, jamais une importation dégradée présentée comme parfaite.
## ACCEPTANCE CRITERIA
1. Scenario 1 (no-sheet re-export) is a test in packages/pdf that re-exports from the envelope alone and compares text/images/views facts.
CHECK: grep -ln "exportFromEnvelope" packages/pdf/tests/*.test.ts | wc -l; cd packages/pdf && corepack pnpm vitest run tests/reexport.test.ts 2>&1 | tail -2
EXPECT: >= 1 ; passed
2. Scenario 2 (catalog changed) is a test in apps/app that mutates the loaded sheet (labels + geometry) and proves the envelope re-export ignores it.
CHECK: grep -n "mutat\|renamed\|changed sheet\|exportFromEnvelope" apps/app/tests/unit/pdf.export.app.test.ts | head -3; cd apps/app && corepack pnpm vitest run tests/unit/pdf.export.app.test.ts 2>&1 | tail -2
EXPECT: matches ; passed
3. Scenario 3 (branding changed) — the envelope carries `branding` and `labels`, and `exportFromEnvelope` uses them, not the caller's current branding: a test exports with branding A, re-exports the envelope while branding B is the app's current one, and the images/links/text of the re-export equal the first export.
CHECK: grep -rn "branding" packages/pdf/tests/reexport.test.ts apps/app/tests/unit/pdf.export.app.test.ts | grep -i "differ\|current\|B\b\|other" | head -3
EXPECT: at least one assertion that the re-export does not use the current branding (if absent → ECART)
4. Scenario 4 (v2 import with unresolved items kept): v2 fixtures and the 612-leaf report import, unresolved items survive export → import.
CHECK: cd packages/pdf && corepack pnpm vitest run tests/read.test.ts 2>&1 | tail -2; cd ../../apps/app && corepack pnpm vitest run tests/unit/migration.leaves.test.ts 2>&1 | tail -2
EXPECT: passed ; passed
5. Scenario 5 (goldens): the 39 Phase 0 goldens are unchanged in git since commit 8b86b92 and reproduced by the engine (packages/pdf/tests/goldens.test.ts) and by the app path (apps/app/tests/unit/pdf.goldens.test.ts).
CHECK: git diff --stat 8b86b92 HEAD -- apps/app/tests/fixtures/goldens | tail -1; cd packages/pdf && corepack pnpm vitest run tests/goldens.test.ts 2>&1 | tail -2; cd ../../apps/app && corepack pnpm vitest run tests/unit/pdf.goldens.test.ts 2>&1 | tail -2
EXPECT: empty diff ; passed ; passed
6. Scenario 6 (hostile/oversized snapshots rejected, report kept): security tests cover caps, cycles, dangling asset, sheet_mismatch, hostile SVG, entity, use bomb, viewBox bomb, inflate bomb, __proto__; every rejection keeps `report`.
CHECK: cd packages/pdf && corepack pnpm vitest run tests/security.test.ts 2>&1 | grep -E "Tests|✓|passed" | tail -3; grep -cE "^\s*\[?'(five assets|3 MiB|depth 9|1,?025|cycle|dangling|sheet_mismatch)|reason: '" packages/pdf/tests/security.test.ts
EXPECT: 20 passed ; the rejection table lists the 7 cases (count ≥ 7 rows carrying a `reason:`), each asserted to keep `outcome.report` (one shared assertion over the parametrised table is accepted)
7. Scenario 7 (no network): packages/pdf has no `fetch`/DOM usage (lint rule + grep) and its suite runs in vitest `node` environment; the only `fetch(` under apps/app/src/pdf is in branding.ts.
CHECK: grep -rnE "\bfetch\(|\bwindow\.|globalThis\.document|\bnew Image\(|navigator\." packages/pdf/src | wc -l; grep -rln "from '@xmldom/xmldom'" packages/pdf/src | wc -l; grep -rnE "DOMParser|XMLSerializer" packages/pdf/src -l | xargs grep -L "@xmldom/xmldom" | wc -l; grep -rln "fetch(" apps/app/src/pdf; grep -n "environment" packages/pdf/vitest.config.ts; grep -c "no-restricted-globals" packages/pdf/eslint.config.js
EXPECT: 0 ; >= 1 ; 0 (every file using DOMParser/XMLSerializer imports them from xmldom) ; apps/app/src/pdf/branding.ts only ; node ; >= 1
8. Scenario 8 (real raster): resvg-based test renders main and head views with dimension and highlight-colour assertions.
CHECK: cd packages/pdf && corepack pnpm vitest run tests/raster.test.ts 2>&1 | tail -2
EXPECT: passed
9. Pages unchanged: no edit to render constants/layout beyond the move (compare `packages/pdf/src/render/*.ts` against `git show 8b86b92:apps/app/src/pdf/render/*.ts` — differences limited to imports, labels source, SheetIndex source, rasterizer call, safeText); goldens green (criterion 5).
10. Session: store holds `archive`, persisted under `osteo:archive` only on hydrateImport/hydrateReport/initReport/reset; `rebaseReportOnSheet` runs on import and draft restore; tests exist.
CHECK: grep -n "osteo:archive\|hydrateImport\|rebaseReportOnSheet" apps/app/src/state/*.ts apps/app/src/app/routes/HomeRoute.tsx apps/app/src/app/routes/EditorRoute.tsx | wc -l
EXPECT: >= 5
11. Messages: fr.ts and en.ts carry `home.import.archive_ok`, `home.import.snapshot_rejected`, five `home.import.snapshot_reason.*`, `home.import.rebased`, `home.import.error_attachment_stripped`; HomeRoute composes them; i18n parity test green; `pdf.*` keys gone from the app dicts.
CHECK: grep -c "home.import.snapshot_reason\." apps/app/src/i18n/fr.ts apps/app/src/i18n/en.ts; grep -c "'pdf\." apps/app/src/i18n/fr.ts
EXPECT: 5 5 ; 0
12. Whole workspace green and buildable: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build` from the root; `docker build -t faunosteo-step6 .` succeeds.
EVIDENCE: 2026-10-11 orchestrator: root typecheck/lint/test:run (154+21+130+53+222 = 580 tests) and build rc 0 at 9bd5173; `docker build -t faunosteo-step6 .` exit 0 (log in the session scratchpad, image tagged). MET.
13. Docs: docs/PDF-FORMAT.md describes envelope v1, snapshot content, layered reading, rebase, caps, sizes; CLAUDE.md folder map lists packages/pdf and the new apps/app/src/pdf files; CHANGELOG has the Step 6 entry; DEPLOY.md has the rollback note.
CHECK: grep -c "envelopeVersion\|snapshotRejected\|rebase" docs/PDF-FORMAT.md; grep -n "packages/pdf" CLAUDE.md | head -2
EXPECT: >= 3 ; present
## CLARIFICATIONS
- 2026-10-11 (orchestrator, after verifier pass 1 ECARTS(31): oracle defects + scope): CHECKs of criteria 6 and 7 rewritten above (the behaviour was met, the oracles counted the wrong thing). FILE SCOPE widened below to the structurally necessary files. Deleted tests authorised: `apps/app/tests/unit/pdf.attachment.test.ts` → replaced by `packages/pdf/tests/read.test.ts` (roundtrip, no_attachment, oversized) and `apps/app/tests/unit/pdf.import.test.ts`; `pdf.attachment.inflate.test.ts` → `packages/pdf/tests/security.test.ts` (inflate bomb); `pdf.svgToPng.test.ts` → `apps/app/tests/unit/pdf.browserRasterizer.test.ts`. The spec (Part II §18, Phase 4 contract criterion 1) planned the removal of the legacy modules with their tests.
## FILE SCOPE
packages/pdf/**, packages/domain/** (src/archive, src/report/rebase.ts, src/anatomical-sheet/sheet-index.ts, barrels, package.json, tests), packages/anatomy/src/render/{compose,index}.ts, packages/anatomy/src/curation/app-review.ts, packages/anatomy/tests/render.compose.test.ts, apps/app/package.json, apps/app/src/services/sheetIndex.ts, .claude/** (memory, TODO, contracts), apps/app/src/pdf/**, apps/app/src/state/**, apps/app/src/app/routes/{HomeRoute,EditorRoute}.tsx, apps/app/src/i18n/{fr,en}.ts, apps/app/src/sheets/provider.ts, apps/app/vite/sheet-bundle.ts, apps/app/scripts/**, apps/app/tests/**, docs/**, CLAUDE.md, README.md, CHANGELOG.md, DEPLOY.md, Dockerfile, packages/README.md, pnpm-lock.yaml.
+2 -2
View File
@@ -19,8 +19,8 @@ coverage/
*.tsbuildinfo
# Binary & media assets — reference by path only when needed
public/species/**/*.svg
src/assets/**
**/public/species/**/*.svg
**/src/assets/**
*.png
*.jpg
*.jpeg
+7
View File
@@ -1,13 +1,20 @@
node_modules/
**/node_modules/
dist/
**/dist/
.git/
.env
.env.*
!.env.example
coverage/
**/coverage/
.vite/
**/.vite/
*.log
.DS_Store
Thumbs.db
graphify-out/
.claude/
.gitea/
docs/
logos/
+6
View File
@@ -8,5 +8,11 @@ APP_BRAND_NAME=Osteo Report
APP_FOOTER_NAME=Osteo Report
APP_TAGLINE=Bilans d'ostéopathie animalière
# Supabase connection exposed to the browser (public values, RLS protects data).
# Empty = app runs without backend. Local stack: `pnpm db:start` prints both.
# NEVER put the service_role key here or in any browser-facing variable.
APP_SUPABASE_URL=
APP_SUPABASE_ANON_KEY=
# Docker Compose project namespace
COMPOSE_PROJECT_NAME=osteo-report
+52
View File
@@ -0,0 +1,52 @@
# Gitea Actions (same syntax as GitHub Actions). Runs on the self-hosted forge
# runner; no external provider. The check job covers the SQL layer through the
# PGlite harness (no Docker); the supabase job replays it on the real stack.
name: ci
on:
push:
branches: [main, develop]
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- name: Activate pnpm (version from package.json "packageManager")
run: corepack enable && corepack prepare --activate
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm test:run
- run: pnpm lint
- run: pnpm build
docker:
runs-on: ubuntu-latest
needs: check
steps:
- uses: actions/checkout@v4
- name: Docker image builds (runner needs a Docker daemon)
run: docker build -t faunosteo:ci .
supabase:
runs-on: ubuntu-latest
needs: check
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- run: corepack enable && corepack prepare --activate
- run: pnpm install --frozen-lockfile
- name: Start the local stack (runner needs a Docker daemon); applies migrations + seed
run: pnpm supabase start
- name: pgTAP on the real PostgreSQL image
run: pnpm db:test
- name: Generated types match the schema
run: pnpm db:types:check
- if: always()
run: pnpm supabase stop --no-backup
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# gitflow post-commit — generated by gitflow_init. Do not hand-edit.
hook=post-commit
# Pushes every commit as it lands (BDR-095): a remote only backs up what it
# holds. Never fails the commit: no origin / offline / refused → warning only.
# Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests).
[ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0
# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed:
# an unparseable value or a config read failure also means "no push", named.
# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4.
v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$?
case "$rc:$v" in
0:true|1:*) ;;
0:false) exit 0 ;;
*) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;;
esac
git remote get-url origin >/dev/null 2>&1 || exit 0
br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track
if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi
if $t git push -q -u --follow-tags origin "$br" >/dev/null 2>&1; then exit 0; fi
echo "gitflow $hook: push of '$br' FAILED — this commit exists only on this disk." >&2
echo " Push by hand: git push -u origin $br (rejected as non-fast-forward? never force-push; ask first)" >&2
exit 0
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# gitflow post-merge — generated by gitflow_init. Do not hand-edit.
hook=post-merge
# Pushes every commit as it lands (BDR-095): a remote only backs up what it
# holds. Never fails the commit: no origin / offline / refused → warning only.
# Opt out for one command with GITFLOW_NO_PUSH=1 (throwaway repos, tests).
[ "${GITFLOW_NO_PUSH:-0}" = 1 ] && exit 0
# Manual-push mode (human-set): git config gitflow.autopush false. Fail closed:
# an unparseable value or a config read failure also means "no push", named.
# Mirrors gitflow_push_mode (lib/gitflow.sh); arms pinned by T18b/T18h/T18q2/T18q4.
v=$(git config --bool gitflow.autopush 2>/dev/null); rc=$?
case "$rc:$v" in
0:true|1:*) ;;
0:false) exit 0 ;;
*) echo "gitflow $hook: gitflow.autopush unreadable (git rc $rc) — NOT pushed, treated as manual push mode; fix the value by hand" >&2; exit 0 ;;
esac
git remote get-url origin >/dev/null 2>&1 || exit 0
br=$(git symbolic-ref --short -q HEAD 2>/dev/null) || exit 0 # detached HEAD — nothing to track
if command -v timeout >/dev/null 2>&1; then t="timeout ${GITFLOW_PUSH_TIMEOUT:-30}"; else t=""; fi
if $t git push -q -u --follow-tags origin "$br" >/dev/null 2>&1; then exit 0; fi
echo "gitflow $hook: push of '$br' FAILED — this commit exists only on this disk." >&2
echo " Push by hand: git push -u origin $br (rejected as non-fast-forward? never force-push; ask first)" >&2
exit 0
+26 -3
View File
@@ -7,17 +7,40 @@ br=$(git symbolic-ref --short -q HEAD 2>/dev/null)
git rev-parse --verify -q HEAD >/dev/null 2>&1 || exit 0 # root commit — allow
[ -f "$gd/MERGE_HEAD" ] && exit 0 # merge in progress — allow
# Secret backstop (job7) — any branch, not just protected ones. Non-blocking
# if gitleaks isn't installed; auto-discovers ./.gitleaks.toml (repo root).
# gitleaks >= 8.19 scans the index with `git --staged`; older builds (Ubuntu's
# 8.16 package) only know `protect --staged`, and `git` exits 1 there as an
# unknown command — which would block every commit. Probe the subcommand first.
if command -v gitleaks >/dev/null 2>&1; then
gl_sub=git
gitleaks git --help >/dev/null 2>&1 || gl_sub=protect
if ! gitleaks "$gl_sub" --staged --no-banner >/dev/null 2>&1; then
echo "gitflow pre-commit: BLOCKED — gitleaks found a secret in staged changes." >&2
echo " Details: gitleaks $gl_sub --staged --no-banner" >&2
echo " Genuine false-positive? add an allowlist rule to .gitleaks.toml — never bypass with --no-verify." >&2
exit 1
fi
else
echo "gitflow pre-commit: gitleaks not installed — secret scan skipped (https://github.com/gitleaks/gitleaks)." >&2
fi
# Per-repo opt-out of the branch model (a clone of a foreign project):
# git config gitflow.protect false
[ "$(git config --bool --default true gitflow.protect)" = false ] && exit 0
case "$br" in
main|develop) ;; # protected — keep checking
*) exit 0 ;; # working branch — allow
esac
# whitelist: all-staged-under-.claude/ (memory/doc/deploy helpers) — allow
if [ -z "$(git diff --cached --name-only | grep -v '^\.claude/' | head -1)" ]; then
# whitelist: all-staged-under-.claude/ (memory/doc/deploy helpers) or
# .githooks/ (the hooks themselves, refreshed by the lib) — allow
if [ -z "$(git diff --cached --name-only | grep -vE '^\.(claude|githooks)/' | head -1)" ]; then
exit 0
fi
echo "gitflow pre-commit: BLOCKED — direct commit on '$br'." >&2
echo " Branch from the right base (feature/bugfix->develop, hotfix->main), or merge." >&2
echo " (.claude/** memory commits are exempt; --no-verify bypasses locally.)" >&2
echo " (.claude/** and .githooks/** commits are exempt; foreign clone? git config gitflow.protect false)" >&2
exit 1
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# gitflow reference-transaction — generated by gitflow_init. Do not hand-edit.
# Refuses deleting (or renaming) main / develop, whatever the
# command. Mirrors gitflow_protected_base (lib/gitflow.sh).
[ "$1" = prepared ] || exit 0
while read -r _old new ref; do
case "$ref" in refs/heads/main|refs/heads/develop) ;; *) continue ;; esac
case "$new" in *[!0]*) continue ;; esac # new value not all-zeros → an update, not a deletion
# Per-repo opt-out (a foreign clone): git config gitflow.protect false
[ "$(git config --bool --default true gitflow.protect)" = false ] && exit 0
echo "gitflow reference-transaction: BLOCKED — deleting '$ref', a protected base." >&2
echo " main and develop are never deleted or renamed. A merged working branch: gitflow.sh delete <branch>" >&2
exit 1
done
exit 0
+4
View File
@@ -55,3 +55,7 @@ graphify-out/
.claude/gstack/
.claude/deploy/PENDING.json
.claude/deploy/NEXT.sh
# Supabase CLI local state (written by supabase start / db reset)
supabase/.branches/
supabase/.temp/
+1
View File
@@ -0,0 +1 @@
24
+4
View File
@@ -1,2 +1,6 @@
shamefully-hoist=false
strict-peer-dependencies=false
# Supply-chain guard: only install package versions published >= 24h ago
minimum-release-age=1440
# Refuse to install on a Node/pnpm outside package.json "engines" (explicit environment)
engine-strict=true
+1 -1
View File
@@ -1 +1 @@
20
24
+34
View File
@@ -6,6 +6,29 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [0.2.0] — 2026-10-11
### Added (SaaS migration, plan Steps 3–6)
- **Autonomous PDF archives (Step 6)** — new `@faunosteo/pdf` engine (`packages/pdf`): the PDF is rendered from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, export date), with no network and no browser DOM; the attachment becomes a **report archive envelope v1** (`osteo-report.json`) carrying the Report v3, a lean but valid snapshot of the anatomical sheet (views, annotations, geometry, colours, relations, the finding paths used with their ancestor labels, the SVG drawing), the branding used at export and the FR/EN label dictionary, so an old bilan is reproduced identically after any catalog, wording or logo change. Layered reading keeps the report even when the wrapper or the snapshot is refused (closed reasons), v2 and bare v3 PDFs still import, a PDF whose attachment was stripped is recognised. Imported archives are kept in the session; a bilan reopened on a different sheet is rebased on a working copy with unresolved items flagged and their labels kept, and the import message says so. SVG assets go through an allowlist sanitiser with size and complexity caps checked at import and at export; a WinAnsi guard keeps any text from crashing the export. Pages unchanged (frozen by 39 goldens). `docs/PDF-FORMAT.md` written for real.
- **Bounded attachment import and bundled branding (Step 6 closure)** — the PDF attachment is extracted by a bounded byte scan (no pdf-lib parse on import, 16 KiB inflate slices, shared 16 MiB candidate budget, JSON depth pre-check, export without object streams); the logos and identity used at export are bundled with the app.
- **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change.
- **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`.
- **Application on the canonical sheet (Step 5)** — the editor renders the bundled reference sheet (curated equine draft, `SHEET_BUNDLE=draft`; a default build carries no sheet): markers drawn from the document with the legacy look (`@faunosteo/anatomy/render`), head view as a crop of the same drawing, zone interaction service, pickers on the sheet's regions (usual count, extension to the documented range) and finding zones. Report document **v3** (`packages/domain/report`): zones by annotation and view ids, findings by zone and path, severity codes, exact sheet reference; v2 PDFs and drafts migrate through the generated `report-migration-map.json`, unresolved items kept with their labels. Removed: species registry, label matchers, SVG convention parser, `/editors`, `/svg-editor`, `pathology-editor.html`, `scaffold:species`; the legacy sources now live under `supabase/seed/anatomical-sheets/equine/legacy-sources/`. Archive check tool `pnpm report:compare` (attachment vs its v3 reading, unresolved items flagged); the 612 legacy catalog leaves are tested through the migration in both packages.
- **Equine sheet curation (Step 4c)** — document schema v2 (references registry, `review_status` on findings and annotations, configurable vertebral `count_range`; migration `20261010100000`, pgTAP 008); `@faunosteo/anatomy` curation pipeline: authored changeset (`curation/changes.json`, levels A/B/C, before/after records) applied to the legacy baseline → working draft with `CHANGELOG.md`, `REVIEW-REPORT.md` (10 sections for the osteopath) and before/after review drawings; one cleaned SVG asset, head view as a crop. Content: research-backed audit of the horse sheet (44 changes, 48 verifiable references): sphenoid zone restructured, NAV terminology, FR/EN translations, vertebral ranges, ten SVG points relocated, carpus zone added, veterinary red flags, legal disclaimer anchored on R. 243-6 / R. 243-8, osteopathic-model status on unvalidated concepts, 11 questions for the professional. Still a private DRAFT, not published. Docker resources prefixed `faunosteo_` (Compose project and container).
- **Equine import (Step 4b)** — `@faunosteo/anatomy` deterministic importer: `Horse.svg` + `Horse_head.svg` + `pathologies.json` → canonical document, legacy id map, French import report, idempotent seed creating the official sheet `faunosteo-cheval` as a private DRAFT (never published by code). Storage bucket `anatomical-sheet-assets` (content-addressed SVGs, read through the sheet, operator upload script).
### Changed (SaaS migration, plan Step 2)
- **pnpm workspace** — the application moved to `apps/app` (`@faunosteo/app`) with `git mv`; root commands (`pnpm typecheck|test:run|lint|build|dev`) delegate to the packages. `packages/` reserved, empty. CI workflow added (`.gitea/workflows/ci.yml`).
- **Node 24 LTS / pnpm 10.13.1** — declared in `.nvmrc`, `.node-version`, `engines`, `packageManager`; `engine-strict` on; Dockerfile builds on `node:24-alpine` and copies `apps/app/dist`.
### Added (SaaS migration, plan Steps 0–1)
- **Implementation plan** — `docs/development/` (27-step plan, migration map, domain map, architecture, strategies, open questions).
- **Characterisation suite** — 91 tests on the real SVGs, catalog and PDF pipeline; two golden Report v2 fixtures (`CHARACTERIZATION_REPORT.md`).
### Added
- **Laterality & bilaterality** — `LateralSideSchema` (left/right) + `Bone.lateral`, `data-anno-lateral` parsed from the SVG; `LateralityPicker` modal in the zone-click flow, side shown in zone badges and PDF labels; bilateral zones get a separate findings picker per side.
@@ -21,10 +44,21 @@ Versions follow [Semantic Versioning](https://semver.org/).
- **Responsive mobile** — full phone/tablet adaptation across all components.
- **Project renamed** Zoosteo → Faunosteo across the whole codebase.
### Removed
- **`canvg` dependency** — PDF SVG rasterization now uses the browser's native `Image`/`canvas` pipeline (`src/pdf/render/svgToPng.ts`) instead of the `canvg` library.
### Fixed
- **`pathology-editor.html` 404 in production** — it lived at the repo root, Vite never bundled it into `dist/`; moved to `public/` so it ships (LRN-029).
- **Docker species caching** — `Cache-Control: no-cache` header added for `/species/` assets so an updated catalog is served fresh.
- **nginx runner base image** pinned to `nginx:1.31-alpine` (was the floating `nginx:alpine` tag).
### Security
- **Docker container runs fully as non-root** (`USER nginx`) — `PORT` must now be `>=1024` (default `8080` unaffected).
- **Supply-chain guard** — `.npmrc` gained `minimum-release-age=1440`, blocking install of package versions published less than 24h ago.
- **User-imported SVGs sanitized** — the SVG editor and the standalone pathology editor now strip `<script>`/`<foreignObject>` nodes, `on*` event-handler attributes, and `javascript:` hrefs before inserting an imported SVG into the DOM.
---
+211 -98
View File
@@ -11,7 +11,18 @@ Single-praticien French web app for veterinary osteopathy bilans on animal anato
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.
Static SPA, no backend, no auth. Deployed via Docker + nginx on Scaleway VPS.
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`,
tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved the
application onto that model: the editor renders the bundled reference sheet (the
curated equine DRAFT, `SHEET_BUNDLE=draft`), writes Report v3 and imports v2 PDFs
through a generated migration map. Step 6 made the PDF an autonomous archive: the
`packages/pdf` engine renders from explicit inputs (report, sheet snapshot, branding,
labels, rasterizer) with no network and no DOM, and the attachment is an envelope v1
carrying the report, a lean sheet snapshot, the branding and the labels used, so an old
bilan is reproduced identically after any catalog, wording or logo change
(`docs/PDF-FORMAT.md`). The Supabase client is still unused by the UI.
MVP species: equine only. Open-source MIT.
---
@@ -20,8 +31,8 @@ MVP species: equine only. Open-source MIT.
| Concern | Choice | Version |
|---|---|---|
| Runtime | Node.js | 20 |
| Package manager | pnpm | >=9 (11.x on host) |
| 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 |
@@ -29,15 +40,23 @@ MVP species: equine only. Open-source MIT.
| State | Zustand | 5 |
| Validation | Zod | 3 |
| PDF | pdf-lib | 1.17 |
| SVG raster | canvg | 4 |
| 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
@@ -62,6 +81,19 @@ 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
# Reference sheet in the app: the dev server bundles the curated draft; a build does not
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
pnpm preview:draft # same, then serves it
pnpm import:equine # regenerate legacy-import/ and draft/ (document, migration map, review drawings)
pnpm report:compare <pdf|dir>... # archive check: attachment vs its v3 reading, unresolved items flagged (docs/PDF-FORMAT.md)
```
## Docker commands
@@ -70,6 +102,9 @@ pnpm format
# Build image
docker build -t faunosteo .
# Build an image that embeds the reference DRAFT sheet (preview only, never the default)
docker build --build-arg SHEET_BUNDLE=draft -t faunosteo .
# Run with compose (reads .env for APP_* vars)
docker compose up --build
@@ -77,8 +112,14 @@ docker compose up --build
docker compose down
```
Note: pnpm binary at `~/.local/share/pnpm/bin/pnpm` on dev host (corepack broken).
Add it to PATH: `export PATH="$HOME/.local/share/pnpm/bin:$PATH"`.
Naming convention: every Docker resource Faunosteo owns is prefixed `faunosteo_`
when the name is configurable (container `faunosteo_app`, Compose project
`faunosteo`); the Supabase CLI imposes `supabase_<service>_faunosteo`, documented
as a limit in DEPLOY.md "Docker resource naming". Never rename a resource that
holds data without keeping its volume.
Note: no global pnpm needed. `corepack enable` once (reads `packageManager`),
or call `corepack pnpm <cmd>`. Root scripts resolve `node_modules/.bin/pnpm`.
---
@@ -89,8 +130,12 @@ pnpm test:run # vitest run — all tests, single pass, CI-safe
pnpm test # vitest watch — dev loop
```
Test files live in `tests/unit/*.test.ts` and `tests/unit/*.test.tsx`.
Setup: `tests/setup.ts` imports @testing-library/jest-dom.
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. The 612 legacy catalog leaves run through the v2 → v3 migration
in both `packages/anatomy` (against the draft document) and the app (sheet index + PDF roundtrip). Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Suites run on the bundled reference sheet (`tests/helpers/sheet.ts`); frozen v2 fixtures under `tests/fixtures/`.
SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts`
on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack.
---
@@ -106,55 +151,46 @@ pnpm format # Prettier write
## Folder structure
```
osteo/
├─ public/
│ ├─ species/equine/{Horse,Horse_head}.svg ← real anatomy SVGs
│ └─ pathology-editor.html ← standalone JSON editor (served as static file)
faunosteo/
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset)
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
├─ src/
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,SvgEditor,NotFound}Route.tsx
│ │ ├─ routes/{Home,NewReport,Editor,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}
│ ├─ sheets/{provider,useSheet}.ts ← SheetProvider interface, bundled implementation, per-species hook
│ ├─ services/
│ │ ├─ sheetIndex.ts ← read-only lookups over the loaded sheet (ids, never labels)
│ │ └─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae)
│ ├─ 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
│ │ ├─ reportStore.ts ← Zustand store (Report v3) + persistence.ts (sessionStorage adapter, v2 draft migration)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/
│ │ ├─ types.ts ← Bone, BoneCategory, BoneState
│ │ ├─ svgConvention.ts ← parseSvgBones()
│ │ ├─ svgLoader.ts ← loadSvg(), svgToPngDataUrl()
│ │ └─ labels.ts ← boneLabel(bone, locale, fallback)
│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,LanguageSwitcher}.tsx
│ ├─ pdf/
│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts
│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng}.ts
│ ├─ lib/{dates,id,assert,zoneMatch,spineZones}.ts
│ ├─ styles/{index,tokens,svg-editor}.css ← Tailwind v4 CSS-first + SVG editor styles
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
│ └─ main.tsx
├─ tests/
│ ├─ setup.ts
@@ -163,23 +199,41 @@ osteo/
│ ├─ 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
│ ├─ ANNOTATION-RENDERING.md ← annotation layer contract (attributes, styles, colours)
│ ├─ PDF-FORMAT.md
│ ├─ superpowers/specs/
│ │ ├─ 2026-05-18-osteo-report-mvp-design.md
│ │ ├─ 2026-05-20-b3-i18n-fr-en-design.md
│ │ └─ 2026-05-22-pathology-editor-design.md
│ └─ superpowers/plans/
│ ├─ 2026-05-18-osteo-report-mvp.md
│ └─ 2026-05-20-b3-i18n-fr-en.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): anatomical-sheet (document, integrity rules, sheet-index), report (v3, v2 migration, rebase), archive (sheet snapshot, envelope v1, branding, labels, layered reader)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, pure annotation-layer renderer + view composer (`./render`)
├─ packages/pdf/ ← @faunosteo/pdf: browser-free PDF engine — src/{export,read,text,branding}.ts, attachment/, svg/{parse,sanitize,view}.ts, render/, i18n/; tests reproduce the Step 6 goldens
│ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts
│ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft
│ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts
├─ packages/supabase/ ← @faunosteo/supabase
│ ├─ src/{index,client,database.types,anatomical-sheets}.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, storage, sheet_document_schema_v2
│ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
│ │ ├─ curation/{changes,references}.json ← AUTHORED changeset + references registry (never generated)
│ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, sheet-ref, report-migration-map, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
├─ .claude/{tasks/TODO.md,memory/,audits/}
├─ Dockerfile, docker-compose.yml
├─ .env.example, .editorconfig, .nvmrc, .prettierrc.json
├─ eslint.config.js, index.html
├─ package.json, tsconfig*.json
├─ vite.config.ts, vitest.config.ts
├─ CLAUDE.md, README.md, LICENSE
├─ 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
```
---
@@ -192,33 +246,48 @@ User interaction
→ 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
Sheet loading
→ useSheet(speciesId) → SheetProvider (bundled: virtual:faunosteo-sheet, SHEET_BUNDLE=draft)
→ Zod-validated document + assets + migration map → buildSheetIndex()
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
SVG interaction
→ AnatomyCanvas builds the view: sanitised asset + renderAnnotationLayer() (markers from the document)
→ delegated click on [data-anno-id] → decideZoneClick() (services/zoneInteraction, pure)
→ open_view → DetailModal (same drawing, view_box crop, or the view's own asset)
→ open_vertebra_picker / open_laterality_picker → pickers → reducers (ensureZone, addSides, syncVertebrae)
→ toggle / remove_both_sides → updateObservation() in store
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportReportToPdf(report, index, { locale })
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
→ { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF import
→ importReportFromPdf(bytes)
→ extractReportJson → Zod validate
→ hydrateReport() → navigate /editor
→ importReportFromPdf(bytes, migrationMap) → readReportArchive (engine)
→ byte scan for the EmbeddedFile stream (no pdf-lib parse on untrusted bytes, BLK-009): named osteo-report* first,
capped native inflation → layered reading: report (v3 as is, v2 migrated, else incompatible_version),
envelope metadata tolerant, snapshot/branding/labels strict → archive kept or snapshotRejected (closed reason)
→ rebaseReportOnSheet(report, index, archivedSnapshot) when the loaded sheet differs (unresolved flags, labels kept)
→ hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → 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`
```
---
@@ -236,42 +305,80 @@ Runtime config
- 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`
- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
- PDF static labels (section headings, metadata) live in the engine (`packages/pdf/src/i18n`, `defaultPdfLabels`, 25 keys) and are archived in the envelope; the app dicts hold no `pdf.*` key
### Identity strings
- NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE
- Always read from ConfigProvider via useConfig()
- src/config/env.ts is the only place with defaults
### 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
### Annotation rendering
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws
the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there
- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
and annotations); no graphic redesign without prior validation
### Schemas
- domain/schema/*.ts are the data contracts — never change without bumping version
- `packages/domain/src/report/*.ts` are the report data contracts (v3 current, v2 input only); never change
without bumping the version on a breaking change (additive optional fields keep it)
- All user-provided data goes through Zod parse before hitting the store
- ReportSchema.version = 1 for MVP; future breaking changes → version 2
- Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
`mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
(`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
v1 and unknown versions are refused with a typed error
### Stores
- No direct store mutation outside Zustand actions
- No business logic in components — delegate to store actions
- sessionStorage key: osteo:draft (auto-saved on every observation change)
- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits)
- 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
- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report
- The engine (`packages/pdf`) has no DOM lib, no fetch, no Node-only global (lint-enforced); rasterisation is an injected adapter; every SVG it receives is sanitised by allowlist with caps
- Page layout is frozen by the Step 6 goldens: any visible change needs a user decision and a golden regeneration
- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
### 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
### Anatomical sheet content
- The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content
change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section)
- The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically
validated and a production build carries no sheet unless that flag is set on purpose
### Database (Supabase)
- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
statuses (practitioner/student/professor come from verification, cabinet roles from
organization_members). Never add a professional status to `platform_role`.
- Every `public` table: RLS enabled, `revoke all` from API roles then exact grants,
separate policies per command, no `using (true)` for anon/authenticated (test-enforced).
- Writes that change privileges or sensitive state go through a security-definer RPC
that checks `auth.uid()` and calls `private.log_event()`. Never a direct table policy.
- Helpers in `private` are `security definer`, `set search_path = ''`, EXECUTE revoked
from public and granted only to the roles that evaluate them.
- A migration is never edited once applied. Each migration ships its pgTAP file with
allowed AND denied cases, and a regenerated `database.types.ts`.
- The browser holds the anon key only. The `service_role` key value never appears in env.js, .env.example or code;
operator scripts under `packages/*/scripts/` read it from the environment and are never bundled.
- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
### Anatomical sheet model (packages/domain + migration 20261008110000)
- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs.
- Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the
explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime.
- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then
`publish_sheet_version`. Integrity rule codes are shared by `validateSheetDocument` (TS) and
`private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table.
- Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`.
- Official equine sheet = generated seed `draft/` (`pnpm import:equine`, never edit `legacy-import/` or `draft/` by hand;
the golden test fails on drift). Every content change goes through `curation/changes.json` (traced in CHANGELOG.md).
It is a DRAFT until a platform admin publishes it after business review of `REVIEW-REPORT.md`.
- Sheet SVG bytes live in Storage bucket `anatomical-sheet-assets` as `<sha256>.svg`; uploads are an operator task
(`pnpm assets:upload <seed dir>` with the service key in env), never from the browser.
### Component stubs
- Scaffold stubs render <div>ComponentName placeholder</div>
@@ -283,7 +390,8 @@ Runtime config
- **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 backend, no API routes. Section N/A.
- **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.
---
@@ -302,13 +410,15 @@ Runtime config
| zustand 5 | Lightweight global state |
| zod 3 | Schema validation + type inference |
| pdf-lib 1.17 | Pure-JS PDF generation + native attachments |
| canvg 4 | SVG → Canvas rasterization for PDF |
| 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 |
---
@@ -316,18 +426,21 @@ Runtime config
## 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 pako decompression.
- pnpm binary: `~/.local/share/pnpm/bin/pnpm` on dev host. Add to PATH in shell profile.
- Domain schema changes (`packages/domain/src/report/*.ts`) require updating all callers + bumping version if breaking.
- Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first.
- Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the
importer's input (the user's historical files).
- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet` — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Import never parses untrusted PDF object graphs: the attachment is located by byte scan and inflated under the 16 MiB cap (BLK-009). Opening the import to external users is gated by `docs/development/PDF_IMPORT_HARDENING.md` §5 (BDR-040).
- After PDF roundtrip tests fail: check attachment bytes, then the layered reader (report first, envelope metadata, snapshot/branding/labels), then DecompressionStream inflation. Goldens under `apps/app/tests/fixtures/goldens/step6` are never regenerated without a user decision.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- 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`.
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`
+65 -9
View File
@@ -1,11 +1,13 @@
# Deploy
Single nginx:alpine container behind a host reverse proxy that terminates
TLS. The container serves a static SPA bundle from `/usr/share/nginx/html`
TLS. The container serves a static SPA bundle (built from `apps/app`, Node 24,
pnpm 10.13.1) from `/usr/share/nginx/html`
and a runtime-injected `env.js`; there is no backend, no database, no
persistent server-side state. Praticien data lives in the browser
(`sessionStorage` / `localStorage`) and in the exported PDFs themselves
(JSON attached natively to each PDF).
(JSON attached natively to each PDF). The container runs entirely as a
non-root `nginx` user — no process is root after the image is built.
---
@@ -13,12 +15,56 @@ persistent server-side state. Praticien data lives in the browser
| Service | Image source | Port (container) | Port (host) | Role |
| ------- | ----------------------------------------- | ---------------- | --------------- | ----------------------------------------------------------------------------------- |
| `app` | local build (multi-stage `Dockerfile`) | `${PORT:-8080}` | `${PORT:-8080}` | Serves the SPA (`dist/`) + runtime `env.js`. nginx:alpine inside, SPA fallback to `index.html`. |
| `app` | local build (multi-stage `Dockerfile`) | `${PORT:-8080}` | `${PORT:-8080}` | Serves the SPA (`dist/`) + runtime `env.js`. `nginx:1.31-alpine` inside, runs as non-root `nginx` user, SPA fallback to `index.html`. |
The host should publish only ports `22`, `80`, `443` to the internet. The
container port (`8080` by default) should stay loopback-only — the host
reverse proxy reads from it on `127.0.0.1:8080`.
### Reference sheet in the image (SHEET_BUNDLE)
The application needs an anatomical sheet to work. Until sheets are served by
Supabase (plan Step 13) the only source is the sheet bundled at build time:
| Build | Sheet in the bundle |
|---|---|
| `docker build .` / `pnpm build` (default, CI) | none: the app shows "no anatomical sheet" and refuses to create or import a report |
| `docker build --build-arg SHEET_BUNDLE=draft .` / `pnpm build:preview` | the curated equine DRAFT, medically unvalidated |
Bundling the draft is a deliberate preview decision, never the default: the
draft content is readable by anyone who can load the application (BDR-037).
### Docker resource naming
Expected change in `.env.example` (file not editable by the assistant):
replace `COMPOSE_PROJECT_NAME=osteo-report` with `COMPOSE_PROJECT_NAME=faunosteo`
or drop the line. The variable overrides `name: faunosteo` in
`docker-compose.yml`, so an `.env` copied from the example would still create
`osteo-report_*` resources. No secret is involved.
Several SaaS may share one VPS, so every Docker resource Faunosteo owns
carries the `faunosteo_` prefix whenever its name is configurable:
containers, Compose project (hence networks and named volumes), images and
future services (`faunosteo_app`, `faunosteo_worker`, `faunosteo_supabase_db`…).
| Resource | Name | Set by |
| ------------------------------ | ------------------------------------- | ---------------------------------------- |
| SPA container | `faunosteo_app` | `container_name` in `docker-compose.yml` |
| Compose project, network | `faunosteo`, `faunosteo_default` | top-level `name:` in `docker-compose.yml` |
| Local Supabase stack (CLI) | `supabase_<service>_faunosteo` | `project_id` in `supabase/config.toml` |
Known limit: the Supabase CLI hard-codes `supabase_<service>_<project_id>`
for its containers, volumes and network (`supabase_network_faunosteo`); the
project id is a suffix, not a prefix. The name stays unique per SaaS, so no
workaround is applied. A self-hosted production Supabase (docs/development/
SUPABASE.md §10) is a Compose project we write ourselves and must follow the
prefix (`faunosteo_supabase_db`, `faunosteo_supabase_auth`, …).
Renaming a container never touches data: the SPA container holds no volume.
When a future service gains a named volume, keep the volume name across a
rename (`external: true` or an explicit `name:`) instead of recreating it.
---
## Required environment
@@ -34,9 +80,13 @@ each one explicitly.
| `APP_BRAND_NAME` | yes | `Faunosteo` | Header brand block, PDF header. Praticien-visible identity. |
| `APP_FOOTER_NAME` | yes | `Faunosteo` | Footer copyright line. |
| `APP_TAGLINE` | yes | `Outils pour ostéopathes animaliers` | Hero tagline on Home. |
| `PORT` | no | `8080` | Container listen port. Override to relocate the loopback bind. |
| `APP_SUPABASE_URL` | no | empty | Supabase project URL exposed to the browser. Empty = app runs without backend (current mode). |
| `APP_SUPABASE_ANON_KEY` | no | empty | Supabase anon (publishable) key. Public by design, data stays behind RLS. Never the service_role key. |
| `PORT` | no | `8080` | Container listen port. Must be `>=1024` — the container runs as a non-root `nginx` user and cannot bind privileged ports. |
No secrets are required — there is no API, no DB, no provider credential.
No secrets are required in this file: the anon key is public by design and
the service_role key never leaves the Supabase host (see
`docs/development/SUPABASE.md`).
The `.env` file is not sensitive but should still be `chmod 600` to keep
local identity overrides private.
@@ -162,8 +212,8 @@ curl -sI http://127.0.0.1:8080/ | head -1 # expect 200 OK
curl -s http://127.0.0.1:8080/env.js # expect window.__APP_CONFIG__ = {...};
```
If the build OOMs on a 1 GB VPS, build locally and rsync the resulting
`dist/` over, then bind-mount it into a plain `nginx:alpine` until you
If the build OOMs on a 1 GB VPS, build locally (`pnpm build`) and rsync the
resulting `apps/app/dist/` over, then bind-mount it into a plain `nginx:alpine` until you
upsize.
---
@@ -176,7 +226,7 @@ VPS is the path:
```bash
cd ~/faunosteo
git fetch origin
git reset --hard origin/master # default branch is "master" on this remote
git reset --hard origin/main # default branch is "main" on this remote
docker compose up --build -d
docker image prune -f # reclaim old build layers
```
@@ -192,6 +242,12 @@ For zero-downtime updates, `docker compose up --build -d` rebuilds the
image then recreates the container; the container restart is sub-second
because nginx:alpine boots instantly. There is no warmup phase.
Rollback note (PDF archives, Step 6): PDFs exported by a Step 6 build carry
a report archive envelope. A build older than Step 6 reads such a PDF as "no
attachment"; a Step 6 build reads every older PDF (bare v2 and v3). Roll back
only with that limit in mind and tell the practitioners which build produced
their files.
---
## Data persistence
@@ -615,7 +671,7 @@ from `/var/lib/docker/containers/<id>/*.log` anyway, lower the cap in
(`/etc/docker/daemon.json`). Host nginx logs in `/var/log/nginx/`;
rotate via logrotate (default Ubuntu config). Certbot logs in
`/var/log/letsencrypt/`.
- **Manual log prune**: `docker compose logs --no-color > /tmp/x; truncate -s 0 $(docker inspect --format='{{.LogPath}}' faunosteo-web)`.
- **Manual log prune**: `docker compose logs --no-color > /tmp/x; truncate -s 0 $(docker inspect --format='{{.LogPath}}' faunosteo_app)`.
- **Key rotation**: `.env` carries no secret material, but if
`APP_BRAND_NAME` etc. need to change, edit `.env` + `docker compose up
-d` (no rebuild — `entrypoint.sh` reads env on container start).
+29 -11
View File
@@ -1,34 +1,52 @@
# ---- stage 1: builder -----------------------------------------------
FROM node:20-alpine AS builder
# Node 24 LTS (Node 20 reached end-of-life on 2026-04-30). pnpm pinned to the
# same version as package.json "packageManager"; pnpm 11 needs Node >= 22.13
# and rewrites the lockfile, so the 10.x line stays pinned on purpose.
FROM node:24-alpine AS builder
WORKDIR /app
# Install pnpm via corepack
RUN corepack enable && corepack prepare pnpm@10.13.1 --activate
# Copy manifests first for layer caching
COPY package.json pnpm-lock.yaml* ./
# Workspace manifests first for layer caching (install depends only on these)
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY apps/app/package.json apps/app/
COPY packages/domain/package.json packages/domain/
COPY packages/anatomy/package.json packages/anatomy/
COPY packages/pdf/package.json packages/pdf/
COPY packages/supabase/package.json packages/supabase/
RUN pnpm install --frozen-lockfile
# Copy source and build
# Copy source and build the private app only.
# SHEET_BUNDLE=draft embeds the reference equine DRAFT (medically unvalidated)
# into the bundle for a preview deployment; the default image carries no sheet
# (BDR-037, Step 5 D2): `docker build --build-arg SHEET_BUNDLE=draft .`
ARG SHEET_BUNDLE=none
ENV SHEET_BUNDLE=$SHEET_BUNDLE
COPY . .
RUN pnpm build
RUN pnpm --filter @faunosteo/app build
# ---- stage 2: runner ------------------------------------------------
FROM nginx:alpine AS runner
FROM nginx:1.31-alpine AS runner
# Copy built static assets
COPY --from=builder /app/dist /usr/share/nginx/html
COPY --from=builder /app/apps/app/dist /usr/share/nginx/html
# Copy custom nginx config and entrypoint
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
# Run fully as non-root (port 8080 is unprivileged). nginx needs to own:
# its runtime dirs, the config it rewrites at startup (PORT envsubst),
# and the html dir (entrypoint writes env.js there).
RUN chmod +x /entrypoint.sh \
&& touch /var/run/nginx.pid \
&& chown -R nginx:nginx /var/cache/nginx /var/run/nginx.pid \
/etc/nginx/conf.d /usr/share/nginx/html
USER nginx
# Drop root: nginx master runs as root for port binding, workers as nginx
# The entrypoint writes env.js before exec-ing nginx
EXPOSE 8080
ENTRYPOINT ["/entrypoint.sh"]
+47 -40
View File
@@ -5,10 +5,11 @@ SVGs — click zones, build observations, export a self-contained PDF with the
full report JSON embedded as a native PDF attachment. Re-importing that PDF
restores the state for a follow-up.
Multi-species by design. MVP data set covers the **horse** (équin). Additional
species — dog, cat, goat, cow, pig, rabbit, donkey, sheep — drop in by adding
their SVG schematic + manifest + pathology file under `src/domain/species/`.
See [`docs/ADDING-A-SPECIES.md`](docs/ADDING-A-SPECIES.md) for the recipe.
Multi-species by design. The MVP ships the **horse** sheet: a canonical anatomical
sheet document (drawing + annotations + findings catalog, `packages/domain`)
generated and curated under `supabase/seed/anatomical-sheets/equine/`. Another
species is another sheet document, no code change.
See `docs/development/ANATOMICAL_SHEET_MODEL.md` §6 for how a sheet is produced.
Open to every praticien who wants to use it. No authentication, no backend,
no central server in v1 — the PDF is the long-term record. Phase 2 will add
@@ -19,36 +20,33 @@ contract.
## Features
- **Anatomy canvas** — inline SVG with clickable zones; hitbox+visible twin pattern; delegated click listener
- **Anatomy canvas** — inline SVG drawing with markers rendered from the sheet document (hitbox + visible twin, delegated click listener)
- **Observation builder** — group zones into clinical observations with severity and free-text notes
- **Hierarchical findings tree** — per-zone picker with breadcrumb drill-down through the expert-authored catalog (26 zones for the horse), vet-referral badges on sensitive leaves, scope-disclaimer modal once per session
- **Vertebra picker** — region tabs (C/T/L/S/Cd) with multi-select chip grid for precise vertebral notation
- **Detail popups** — click a zone (e.g. head) to open a secondary SVG with finer-grained zones
- **PDF export** — A4 portrait with rasterized anatomy SVGs (canvg @ 2×), structured observations, and the full report JSON as a native PDF attachment
- **Detail views** — click the head trigger to open the head view (a crop of the same drawing, or a view's own asset)
- **PDF export** — A4 portrait with rasterized views, structured observations, and the full Report v3 JSON as a native PDF attachment; older v2 PDFs import through a generated migration map
- **PDF re-import** — open a previously exported PDF to restore the session for a follow-up
- **Bilingual UI** — full FR/EN interface with a one-click language switcher; default locale auto-detected from the browser, then persisted
- **Configurable identity** — site name, brand, footer, tagline all come from env vars; nothing hardcoded
- **Practitioner cache** — last-used practitioner block prefilled via localStorage
- **Pathology editor** — standalone `pathology-editor.html` tool (no build step) for visually editing the species findings JSON via SVG zone selection; exports a downloadable JSON file
- **Laterality** — left/right side selection on bilateral zones, reflected in badges and the PDF
- **SVG anatomy editor** — in-app `/svg-editor` tool to annotate anatomy SVGs
- **Welcome screen + editors page** — tabbed entry with a project SVG picker and an `/editors` listing
- **Footer branding** — global footer (copyright, "Powered by ZenQuality", partner logo), on site + PDF
---
## Stack
- Node.js 20
- Node.js 24 LTS + pnpm 10.13 (corepack)
- React 19 + TypeScript 5 (strict)
- Vite 7 + @vitejs/plugin-react-swc
- Tailwind CSS v4 (CSS-first, no postcss config)
- Zustand 5 (state)
- Zod 3 (schema + runtime validation)
- pdf-lib 1.17 (PDF generation + native attachments)
- canvg 4 (SVG → canvas rasterization)
- motion 11 (animations)
- vitest 3 + happy-dom + @testing-library/react
- Supabase (PostgreSQL 17, Auth, RLS) via the pinned CLI; `@supabase/supabase-js` 2; PGlite for Dockerless SQL tests
---
@@ -57,9 +55,8 @@ contract.
Single process, no Docker:
```bash
# Requires pnpm — install if needed:
curl -fsSL https://get.pnpm.io/install.sh | sh
source ~/.bashrc # or restart your shell
# Node 24 (see .nvmrc) + pnpm 10.13.1 via corepack, no global install:
corepack enable
pnpm install
cp .env.example .env # edit APP_* vars if desired
@@ -81,8 +78,9 @@ docker compose up --build
```bash
pnpm typecheck # TypeScript strict, no emit
pnpm lint # ESLint 9 flat config, 0 warnings
pnpm test:run # vitest run (174 tests)
pnpm build # tsc + vite build → dist/
pnpm test:run # vitest run (domain, anatomy, supabase/PGlite, app)
pnpm build # tsc + vite build → apps/app/dist/
pnpm report:compare <pdf|dir>... # archive PDF vs its v3 reading, unresolved items flagged
```
---
@@ -90,7 +88,7 @@ pnpm build # tsc + vite build → dist/
## Build & deploy
```bash
pnpm build # production build → dist/
pnpm build # production build → apps/app/dist/
docker build -t faunosteo . # multi-stage Docker image
docker compose up --build # run with env_file: .env
```
@@ -102,10 +100,13 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
## Documentation
- [CLAUDE.md](CLAUDE.md) — project conventions, stack reference, architecture overview
- [docs/ANATOMY-SVG-CONVENTION.md](docs/ANATOMY-SVG-CONVENTION.md) — SVG data-* contract (source of truth)
- [docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) — guide for adding a second species post-MVP
- [docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md) — findings catalog format + authoring guide
- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract
- [docs/ANNOTATION-RENDERING.md](docs/ANNOTATION-RENDERING.md) — annotation layer contract (markers drawn from the sheet document)
- [docs/development/ANATOMICAL_SHEET_MODEL.md](docs/development/ANATOMICAL_SHEET_MODEL.md) — canonical anatomical sheet document, curation pipeline, report migration map
- [docs/development/STEP5_MIGRATION_ANALYSIS.md](docs/development/STEP5_MIGRATION_ANALYSIS.md) — how the application moved onto the canonical sheet (Report v3)
- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF pages, report archive envelope (snapshot, branding, labels), reading and limits
- [docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md](docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md) — why and how the PDF became an autonomous archive (Step 6)
- [docs/development/PDF_IMPORT_HARDENING.md](docs/development/PDF_IMPORT_HARDENING.md) — PDF import against decompression bombs: what lands now, what is required before external users
- [docs/development/SUPABASE.md](docs/development/SUPABASE.md) — local Supabase stack, migrations, RLS tests, generated types
- [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening)
- [CHANGELOG.md](CHANGELOG.md) — versioned release notes
- [.claude/tasks/TODO.md](.claude/tasks/TODO.md) — implementation roadmap
@@ -115,23 +116,29 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
## Project layout
```
osteo/
├─ public/species/equine/ anatomy SVGs (Horse.svg, Horse_head.svg)
faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
├─ apps/app/ the private application (@faunosteo/app):
├─ vite/sheet-bundle.ts Vite plugin bundling the reference sheet (SHEET_BUNDLE=draft|none)
├─ src/app/ routes + ConfigProvider
├─ src/config/ runtime env config resolution
├─ src/domain/ Zod schemas + species registry + equine data
├─ src/sheets/ SheetProvider (bundled implementation) + useSheet hook
├─ src/services/ sheet index (lookups by id) + zone interaction service (pure)
├─ src/i18n/ translation dicts (fr/en) + useT() hook
├─ src/state/ Zustand store + locale store + localStorage cache
├─ src/anatomy/ SVG parser + loader
├─ src/state/ Zustand store (Report v3) + persistence adapter + locale store
├─ src/anatomy/ drawing: sanitised asset + annotation layer → inline SVG per view
├─ src/components/ UI primitives, canvas, observation, report
├─ src/pdf/ export/import/attachment/fonts + renderers
├─ src/pdf/ app side of the PDF: snapshot + branding + browser rasterizer → @faunosteo/pdf engine
├─ src/lib/ id, dates, assert utilities
├─ src/styles/ Tailwind v4 CSS + design tokens
├─ tests/unit/ vitest tests
├─ tests/unit/ vitest tests on the bundled sheet (+ frozen v2 fixtures)
├─ packages/domain/ @faunosteo/domain: canonical sheet document + report document (v3, v2 migration)
├─ packages/anatomy/ @faunosteo/anatomy: legacy importer, curation pipeline, annotation-layer renderer + view composer
├─ packages/pdf/ @faunosteo/pdf: browser-free PDF engine (explicit inputs, archive envelope v1, layered reader)
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
├─ supabase/ CLI config, SQL migrations, local seed (incl. the equine sheet), pgTAP tests
├─ docker/ entrypoint.sh + nginx.conf
├─ docs/ conventions + species guide + PDF spec
├─ index.html SPA entry point
└─ public/pathology-editor.html standalone pathology JSON editor (served as static file)
├─ docs/ conventions, sheet model, PDF spec, development plan
└─ index.html SPA entry point
```
---
@@ -142,16 +149,16 @@ v0.1.0 MVP — implementation complete.
- `pnpm typecheck` ✅
- `pnpm lint` ✅
- `pnpm test:run` ✅ — 174 tests across 30 files
- `pnpm test:run` ✅ — 367 tests across the workspace (domain, anatomy, supabase, app)
- `pnpm build` ✅
The first species data set ships with the real `Horse.svg` + `Horse_head.svg`
anatomy sources at `public/species/equine/` and a full v2.0 findings catalog
(26 zones, 792 nodes, 612 leaves, 41 vet-referral leaves) authored by the
domain expert. Adding **dog, cat, goat, cow, pig, rabbit, donkey, sheep** is
the same procedure: convention-compliant SVG + manifest + findings JSON. See
[docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) and
[docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md).
The first species ships as the equine anatomical sheet: the historical
`Horse.svg`, `Horse_head.svg` and findings catalog (26 zones, 792 nodes)
imported, then audited and curated (`supabase/seed/anatomical-sheets/equine/`,
45 traced changes, 48 references). The application bundles that curated
draft in development (`SHEET_BUNDLE=draft`); it is not medically validated and
a production build carries no sheet unless asked. Another species is another
sheet document produced the same way.
Manual QA checklist: `.claude/audits/MVP-QA.md` — walk it through `pnpm dev`
before delivery.
File renamed without changes.
View File
File renamed without changes.
+50
View File
@@ -0,0 +1,50 @@
{
"name": "@faunosteo/app",
"version": "0.2.0",
"private": true,
"description": "Faunosteo private application: veterinary osteopathy reports with PDF export/import",
"license": "MIT",
"scripts": {
"dev": "vite",
"build": "tsc -p tsconfig.json --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"report:compare": "tsx scripts/compare-reports.ts"
},
"dependencies": {
"@faunosteo/anatomy": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/pdf": "workspace:*",
"@faunosteo/supabase": "workspace:*",
"motion": "^11.11.17",
"pdf-lib": "^1.17.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.1",
"zod": "^3.24.1",
"zustand": "^5.0.2"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^20.19.41",
"@types/react": "^19.0.1",
"@types/react-dom": "^19.0.1",
"@vitejs/plugin-react-swc": "^3.7.2",
"eslint": "^9.17.0",
"eslint-plugin-react": "^7.37.3",
"eslint-plugin-react-hooks": "^5.1.0",
"globals": "^15.14.0",
"happy-dom": "^20.10.6",
"tsx": "^4.23.15",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vite": "^7.3.6",
"vitest": "^3.2.7"
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+164
View File
@@ -0,0 +1,164 @@
/**
* Archive check: reads the report attached to one or more Faunosteo PDFs and
* prints it next to its v3 reading on the bundled reference sheet.
*
* pnpm report:compare <file.pdf | folder>... [--summary] [--full]
* [--locale fr|en] [--diff a.pdf b.pdf]
*
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
* is checked against the sheet. Items the sheet cannot place are marked
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
* PDFs (an archive and its re-export after import, typically). By default
* only identifiers, catalog labels, counts and placeholders are printed and
* compared (a text shows as `conclusion (present)`); names and free texts,
* printed and compared, need `--full`.
* Untrusted strings are printed with control characters escaped. It writes
* no output file.
*/
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
readArchiveDocument,
UnsupportedReportVersionError,
} from '@faunosteo/domain'
import {
ArchiveReadError,
MAX_PDF_BYTES,
readAttachedDocument,
} from '@faunosteo/pdf'
import { parseBundledSheet } from '../src/sheets/provider'
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
import {
compareReport,
diffLines,
esc,
parseArgs,
renderComparison,
renderSummary,
type CliArgs,
type Comparison,
} from './compare/report'
const SEED_DIR = resolve(
fileURLToPath(import.meta.url),
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
const CWD = process.env.INIT_CWD ?? process.cwd()
function loadSheet(): SheetIndex {
const json = (name: string) =>
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
// The comparison needs the document and the map, not the drawings.
return buildSheetIndex(
parseBundledSheet({
status: 'draft',
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
assets: {},
assetHashes: {},
}),
)
}
/** A folder stands for its PDFs; any other argument stays one entry. */
function expandArg(arg: string): string[] {
const path = resolve(CWD, arg)
try {
if (!statSync(path).isDirectory()) return [path]
} catch {
return [path] // reported as a failed entry by compareFile
}
return readdirSync(path)
.filter((f) => f.toLowerCase().endsWith('.pdf'))
.sort()
.map((f) => join(path, f))
}
async function compareFile(
path: string,
sheet: SheetIndex,
args: CliArgs,
): Promise<Comparison> {
const st = statSync(path)
if (!st.isFile()) throw new Error('not a regular file')
if (st.size > MAX_PDF_BYTES) throw new Error('file too large')
const bytes = new Uint8Array(readFileSync(path))
// Byte-scan reader (BLK-009): the PDF object graph is never parsed here.
const raw = await readAttachedDocument(bytes)
try {
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, args)
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
// The version is a number or null: nothing of the attachment is echoed.
throw new Error(`report version ${err.foundVersion} cannot be read`)
}
throw err
}
}
/** The engine's typed read failures, worded without echoing the file. */
const READ_FAILURES: Record<ArchiveReadError['kind'], string> = {
invalid_pdf: 'not a readable PDF',
no_attachment: 'no Faunosteo attachment found',
attachment_stripped:
'attachment stripped (the PDF is stamped as a Faunosteo archive)',
incompatible_version: 'report version cannot be read',
}
/** A missing or unreadable file is a failed entry, not a crash. */
function failureReason(err: unknown): string {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT') return 'file not found'
if (code === 'EACCES') return 'file not readable'
if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind]
// JSON.parse messages echo a fragment of the attachment.
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
return err instanceof Error ? err.message : String(err)
}
async function main(argv: string[]): Promise<number> {
const args = parseArgs(argv)
const files = args.files.flatMap(expandArg)
if (files.length === 0 || (args.diff && files.length !== 2)) {
console.error(
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]',
)
return 1
}
const sheet = loadSheet()
const results: Comparison[] = []
let failures = 0
for (const file of files) {
const name = esc(basename(file))
try {
const c = await compareFile(file, sheet, args)
results.push(c)
if (!args.diff) {
const lines = args.summary
? [renderSummary(name, c)]
: [...renderComparison(name, c), '']
console.log(lines.join('\n'))
}
} catch (err) {
failures += 1
console.log(`!! ${name}: ${esc(failureReason(err))}`)
}
}
if (args.diff && results.length === 2) {
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
}
return failures ? 2 : 0
}
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(err) => {
console.error(esc(err instanceof Error ? err.message : String(err)))
process.exit(1)
},
)
+385
View File
@@ -0,0 +1,385 @@
import {
ReportV2Schema,
findingPathKey,
type ArchiveReadOutcome,
type Finding,
type FindingV2,
type ObservationZoneV2,
type Report,
type ReportZone,
} from '@faunosteo/domain'
import type { Locale } from '../../src/i18n/types'
import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
/**
* Pure comparison of a report document found in a PDF with its v3 reading:
* a v2 archive is shown legacy id → canonical id line by line, a v3 report
* is checked against the bundled sheet. Every item the sheet cannot place is
* marked `!! UNRESOLVED` with the reason, nothing is summarised away. A Step 6
* envelope adds one header line saying whether its snapshot was kept.
*/
export const UNRESOLVED = '!! UNRESOLVED'
export interface CompareOptions {
locale: Locale
/** Print names and the real free texts (off by default: placeholders). */
full: boolean
}
export interface Comparison {
/** `v2` when the attachment was migrated, `v3` when read as is. */
source: 'v2' | 'v3'
header: string[]
observations: string[][]
footer: string[]
/** Lines in the v3 vocabulary only, for `--diff` between two PDFs. */
normalized: string[]
counts: Counts
}
export interface Counts {
observations: number
zones: number
unresolvedZones: number
findings: number
unresolvedFindings: number
}
/**
* Escapes Unicode control (C0, DEL, C1) and format characters (bidi
* overrides, zero-width) plus the line and paragraph separators as `\uXXXX`
* (newline and carriage return included): a PDF is untrusted, and a raw
* escape sequence printed to a terminal can rewrite the screen or fake a line.
*/
export function esc(text: string): string {
return text.replace(
/[\p{Cc}\p{Cf}\u2028\u2029]/gu,
(c) => `\\u${c.codePointAt(0)!.toString(16).padStart(4, '0')}`,
)
}
const q = (text: string) => `"${esc(text)}"`
function zoneRef(z: { annotationId: string; viewId: string; side?: string }) {
return esc(`${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`)
}
function findingRef(f: { findingZoneId: string; path: readonly string[] }) {
return esc(findingPathKey(f.findingZoneId, f.path))
}
function vertebraeOf(z: { vertebrae?: { region: string; index: number }[] }) {
return z.vertebrae?.length
? ` [${z.vertebrae.map((v) => esc(`${v.region}${v.index}`)).join(', ')}]`
: ''
}
/** Free-text lines: the texts with `full`, else only how many there are. */
function textLines(texts: readonly string[], full: boolean): string[] {
if (texts.length === 0) return []
if (!full) return [`text (${texts.length} entries)`]
return texts.map((t) => `text ${q(t)}`)
}
/** A single free-text field: its content with `full`, else a placeholder. */
function fieldLine(label: string, value: string | undefined, full: boolean) {
if (!value) return []
return [full ? `${label} ${q(value)}` : `${label} (present)`]
}
/** A v3 zone against the sheet: current label, or why it cannot be shown. */
function describeZone(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const ref = `${zoneRef(z)}${vertebraeOf(z)}`
const anno = sheet.annotation(z.annotationId)
if (z.unresolved) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} ${UNRESOLVED} legacy zone kept from the archive`
}
if (!anno || anno.view_id !== z.viewId) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} !! not in the sheet (unflagged)`
}
return `${ref} ${q(pickLabel(sheet.name(anno), locale))}`
}
/** A v3 finding against the sheet: current label, or why it cannot be shown. */
function describeFinding(
f: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const snapshot = q(locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot)
const vet = f.requiresVetReferral ? ' (!)' : ''
const side = f.side ? ` ${esc(f.side)}` : ''
const ref = `${findingRef(f)}${side}${vet}`
if (f.unresolved) {
return `${ref} ${snapshot} ${UNRESOLVED} kept with its snapshot`
}
const node = sheet.nodeAt(f.findingZoneId, f.path)
if (!node) return `${ref} ${snapshot} !! not in the sheet (unflagged)`
if (node.children.length > 0) {
return `${ref} ${snapshot} !! points at a category, not a leaf`
}
return `${ref} ${q(pickLabel(node.name, locale))}`
}
/** Legacy zone → migrated zone. */
function describeZoneMigration(
legacy: ObservationZoneV2,
out: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const side = legacy.side ? ` ${legacy.side}` : ''
const detail = legacy.detailSourceId ? '@' + legacy.detailSourceId : ''
const from = `${esc(legacy.boneId + detail + side)}${vertebraeOf(legacy)}`
if (out.unresolved) {
return `${from} ${UNRESOLVED} unknown legacy id, kept as ${zoneRef(out)}`
}
const anno = sheet.annotation(out.annotationId)
const label = anno ? q(pickLabel(sheet.name(anno), locale)) : '!! missing'
return `${from} ${q(out.labelFrSnapshot ?? '')} → ${zoneRef(out)} ${label}`
}
/** Legacy finding → migrated finding, with the fate the map decided. */
function describeFindingMigration(
legacy: FindingV2,
out: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const map = sheet.sheet.migrationMap.finding_paths
const vet = legacy.requiresVetReferral ? ' (!)' : ''
const legacyKey = findingPathKey(legacy.zoneId, legacy.path)
const key = `${esc(legacyKey)}${vet}`
const snapshot = q(
locale === 'en' ? legacy.labelEnSnapshot : legacy.labelFrSnapshot,
)
if (out.unresolved) {
const why = Object.hasOwn(map, legacyKey)
? 'removed from the sheet, kept with its label'
: 'never in the legacy catalog, kept with its label'
return `${key} ${snapshot} ${UNRESOLVED} ${why}`
}
const node = sheet.nodeAt(out.findingZoneId, out.path)
const label = node ? q(pickLabel(node.name, locale)) : '!! missing'
const target = findingRef(out) === esc(legacyKey) ? 'same' : findingRef(out)
return `${key} ${snapshot} → ${target} ${label}`
}
function observationLines(
obs: Report['observations'][number],
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const lines = [
`[${esc(obs.id)}] severity ${esc(obs.severity ?? 'none')}`,
...obs.zones.map((z) => `zone ${describeZone(z, sheet, opts.locale)}`),
...obs.findings.map(
(f) => `finding ${describeFinding(f, sheet, opts.locale)}`,
),
...textLines(obs.freeTextFindings, opts.full),
...fieldLine('comment ', obs.comment, opts.full),
]
return lines
}
/** The report document inside the attachment: the envelope's, or the bare one. */
function reportDataOf(raw: unknown): unknown {
const isEnvelope =
typeof raw === 'object' &&
raw !== null &&
typeof (raw as { envelopeVersion?: unknown }).envelopeVersion === 'number'
return isEnvelope ? (raw as { report: unknown }).report : raw
}
function migratedObservationLines(
raw: unknown,
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[][] {
const v2 = ReportV2Schema.parse(reportDataOf(raw))
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
? esc(`${legacy.severity} → ${out.severity}`)
: 'none'
const lines = [`[${esc(legacy.id)}] severity ${severity}`]
legacy.zones.forEach((z, j) => {
const line = describeZoneMigration(z, out.zones[j]!, sheet, opts.locale)
lines.push(`zone ${line}`)
})
legacy.findings.forEach((f, j) => {
const line = describeFindingMigration(
f,
out.findings[j]!,
sheet,
opts.locale,
)
lines.push(`finding ${line}`)
})
lines.push(...textLines(legacy.freeTextFindings, opts.full))
lines.push(...fieldLine('comment ', legacy.comment, opts.full))
return lines
})
}
function countsOf(report: Report): Counts {
const zones = report.observations.flatMap((o) => o.zones)
const findings = report.observations.flatMap((o) => o.findings)
return {
observations: report.observations.length,
zones: zones.length,
unresolvedZones: zones.filter((z) => z.unresolved).length,
findings: findings.length,
unresolvedFindings: findings.filter((f) => f.unresolved).length,
}
}
/** The envelope line: present only when the attachment was an archive. */
function archiveLine(outcome: ArchiveReadOutcome): string[] {
if (outcome.archive) return ['archive v1 (snapshot kept)']
if (outcome.snapshotRejected) {
return [`archive v1 (snapshot rejected: ${esc(outcome.snapshotRejected)})`]
}
return []
}
function headerLines(
source: 'v2' | 'v3',
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const { report } = outcome
const ref = sheet.sheet.ref
const sameSheet =
report.sheet.sheetId === ref.sheetId &&
report.sheet.documentSha256 === ref.documentSha256
const sheetLine = sameSheet
? `sheet ${esc(ref.sheetId)} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${esc(report.sheet.sheetId)} !! written on another sheet document (sha ${esc(report.sheet.documentSha256.slice(0, 12))}…)`
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
...archiveLine(outcome),
sheetLine,
`id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
if (opts.full) {
lines.push(
`practitioner ${q(report.practitioner.name)} · animal ${q(report.animal.name)} · owner ${q(report.owner.name)}`,
)
}
return lines
}
function footerLines(report: Report, full: boolean): string[] {
const appointment = report.nextAppointment
return [
...fieldLine('conclusion', report.conclusion, full),
...fieldLine('recommendations', report.recommendations, full),
...(appointment
? [
full
? `next appointment ${esc(JSON.stringify(appointment))}`
: `next appointment (${appointment.kind})`,
]
: []),
]
}
/**
* `raw` is the attachment as found in the PDF (bare report or envelope),
* `outcome` its layered reading (`readArchiveDocument`); `outcome.migrated`
* tells which vocabulary the lines use.
*/
export function compareReport(
raw: unknown,
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): Comparison {
const { report, migrated } = outcome
const source = migrated ? 'v2' : 'v3'
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
)
// Same privacy default as the listing: texts are compared with `--full`.
const normalized = [
...report.observations.flatMap((o) => observationLines(o, sheet, opts)),
...footerLines(report, opts.full),
]
return {
source,
header: headerLines(source, outcome, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
footer: footerLines(report, opts.full),
normalized,
counts: countsOf(report),
}
}
export function renderComparison(name: string, c: Comparison): string[] {
return [
`== ${name}`,
...c.header.map((l) => ` ${l}`),
...c.observations.flatMap((lines) =>
lines.map((l, i) => (i === 0 ? ` ${l}` : ` ${l}`)),
),
...c.footer.map((l) => ` ${l}`),
]
}
export function renderSummary(name: string, c: Comparison): string {
const n = c.counts
return `${name} · ${c.source === 'v2' ? 'v2→v3' : 'v3'} · ${n.observations} obs · zones ${n.zones}/${n.unresolvedZones} unresolved · findings ${n.findings}/${n.unresolvedFindings} unresolved`
}
/** Lines of A absent from B and lines of B absent from A, in order. */
export function diffLines(a: string[], b: string[]): string[] {
const inB = new Set(b)
const inA = new Set(a)
return [
...a.filter((l) => !inB.has(l)).map((l) => `- ${l}`),
...b.filter((l) => !inA.has(l)).map((l) => `+ ${l}`),
]
}
export interface CliArgs extends CompareOptions {
files: string[]
summary: boolean
diff: boolean
}
export function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
files: [],
locale: 'fr',
full: false,
summary: false,
diff: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]!
if (arg === '--full') args.full = true
else if (arg === '--summary') args.summary = true
else if (arg === '--diff') args.diff = true
else if (arg === '--locale') {
const value = argv[++i]
if (value !== 'fr' && value !== 'en') {
throw new Error('--locale takes fr or en')
}
args.locale = value
} else if (arg.startsWith('--'))
throw new Error(`unknown option ${esc(arg)}`)
else args.files.push(arg)
}
return args
}
+97
View File
@@ -0,0 +1,97 @@
import {
createLayerElement,
renderAnnotationLayer,
viewBoxOf,
} from '@faunosteo/anatomy/render'
import type { SheetView } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
/**
* Builds the inline SVG of one view: the sheet's drawing (sanitised asset
* text) framed on the view's box, plus the annotation layer generated from
* the document. The drawing is parsed once per asset and cloned per view.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const FORBIDDEN_TAGS = ['script', 'foreignObject', 'iframe', 'object', 'embed']
export type ViewStates = ReadonlyMap<string, 'current'>
/** Drops scripts, embedded documents, event handlers and script URLs (LRN-025). */
export function sanitizeSvg(root: Element): void {
for (const tag of FORBIDDEN_TAGS) {
for (const el of Array.from(root.getElementsByTagName(tag))) el.remove()
}
for (const el of Array.from(root.querySelectorAll('*'))) {
for (const attr of Array.from(el.attributes)) {
const name = attr.name.toLowerCase()
const value = attr.value.trim().toLowerCase()
if (name.startsWith('on') || value.startsWith('javascript:')) {
el.removeAttribute(attr.name)
}
}
}
}
export function parseDrawing(svgText: string): SVGSVGElement {
const doc = new DOMParser().parseFromString(svgText, 'image/svg+xml')
if (doc.querySelector('parsererror')) throw new Error('invalid SVG asset')
const root = doc.documentElement
if (root.tagName.toLowerCase() !== 'svg')
throw new Error('asset root is not <svg>')
sanitizeSvg(root)
return root as unknown as SVGSVGElement
}
const parsed = new Map<string, SVGSVGElement>()
function drawingOf(index: SheetIndex, assetId: string): SVGSVGElement {
const key = `${index.sheet.ref.documentSha256}:${assetId}`
let root = parsed.get(key)
if (!root) {
const text = index.sheet.assets[assetId]
if (text === undefined) throw new Error(`asset ${assetId} not bundled`)
root = parseDrawing(text)
parsed.set(key, root)
}
return root
}
/** The asset a view draws: its own, else its parent's (a crop). */
export function assetOfView(index: SheetIndex, view: SheetView): string {
if (view.svg_asset_id) return view.svg_asset_id
if (view.kind === 'detail') {
const parent = index.view(view.parent_view_id)
if (parent) return assetOfView(index, parent)
}
throw new Error(`view ${view.id} has no asset`)
}
export function buildViewSvg(
index: SheetIndex,
viewId: string,
states: ViewStates,
): SVGSVGElement {
const view = index.view(viewId)
if (!view) throw new Error(`unknown view ${viewId}`)
const source = drawingOf(index, assetOfView(index, view))
const svg = document.createElementNS(SVG_NS, 'svg')
for (const attr of Array.from(source.attributes)) {
if (attr.name === 'width' || attr.name === 'height') continue
svg.setAttribute(attr.name, attr.value)
}
svg.setAttribute(
'viewBox',
viewBoxOf(view) ?? source.getAttribute('viewBox') ?? '0 0 100 100',
)
for (const child of Array.from(source.childNodes)) {
svg.appendChild(document.importNode(child, true))
}
const layer = renderAnnotationLayer({
document: index.sheet.document,
viewId,
states,
})
svg.appendChild(createLayerElement(document, layer) as unknown as Node)
return svg
}
+2 -7
View File
@@ -1,15 +1,12 @@
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { ConfigProvider } from './providers/ConfigProvider'
import Footer from '@/components/brand/Footer'
import HomeRoute from './routes/HomeRoute'
import NewReportRoute from './routes/NewReportRoute'
import EditorRoute from './routes/EditorRoute'
import SvgEditorRoute from './routes/SvgEditorRoute'
import EditorsRoute from './routes/EditorsRoute'
import NotFoundRoute from './routes/NotFoundRoute'
function AppShell() {
const hideFooter = useLocation().pathname === '/svg-editor'
return (
<div className="flex min-h-screen flex-col">
<main className="flex-1 flex flex-col">
@@ -17,12 +14,10 @@ function AppShell() {
<Route path="/" element={<HomeRoute />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} />
<Route path="/svg-editor" element={<SvgEditorRoute />} />
<Route path="/editors" element={<EditorsRoute />} />
<Route path="*" element={<NotFoundRoute />} />
</Routes>
</main>
{!hideFooter && <Footer />}
<Footer />
</div>
)
}
+316
View File
@@ -0,0 +1,316 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import DetailModal from '@/components/canvas/DetailModal'
import ObservationList from '@/components/observation/ObservationList'
import ObservationPickers from '@/components/observation/ObservationPickers'
import ConclusionPanel from '@/components/report/ConclusionPanel'
import ReportHeader from '@/components/report/ReportHeader'
import EditInfosDialog, {
isIdentityComplete,
type Identity,
} from '@/components/report/EditInfosDialog'
import DisclaimerDialog from '@/components/report/DisclaimerDialog'
import Button from '@/components/ui/Button'
import { useReportStore } from '@/state/reportStore'
import { writeCachedPractitioner } from '@/state/practitionerCache'
import { useLocaleStore } from '@/state/localeStore'
import { useSheet } from '@/sheets/useSheet'
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
toggleZone,
type ZoneRef,
} from '@/services/zoneInteraction'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/domain'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
/** What the PDF lacks, named for the practitioner: logo slots and view ids. */
function missingItemsOf(warnings: readonly ExportWarning[]): string[] {
return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId))
}
/** Zones and findings a draft rebase could not find on the loaded sheet. */
function unresolvedCountOf(outcome: RebaseOutcome): number {
return outcome.unresolvedZones + outcome.unresolvedFindings
}
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
export default function EditorRoute() {
const navigate = useNavigate()
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const store = useReportStore()
const { report, activeObservationIndex: activeIndex } = store
// Without a report yet (draft restore), the default species' sheet carries the migration map.
const sheet = useSheet(report?.animal.speciesId ?? DEFAULT_SPECIES_ID)
const [detailViewId, setDetailViewId] = useState<string | null>(null)
const [vertebraTarget, setVertebraTarget] = useState<number | null>(null)
const [lateralTarget, setLateralTarget] = useState<ZoneRef | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
// One alert per restore, even if the effect runs again before the re-render.
const rebaseAlerted = useRef(false)
useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
}, [])
// No report in memory: restore the per-tab draft once the sheet is known.
// A draft rebased on another sheet is announced with its unresolved count.
useEffect(() => {
if (report) return
if (sheet.status === 'ready') {
const outcome = store.restoreDraft(sheet.index)
if (outcome?.rebased && !rebaseAlerted.current) {
rebaseAlerted.current = true
const count = String(unresolvedCountOf(outcome))
window.alert(t('editor.draft_rebased').replace('{count}', count))
}
}
if (sheet.status !== 'loading' && !useReportStore.getState().report)
navigate('/')
}, [report, sheet, store, navigate, t])
useEffect(() => {
if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined')
return
if (sessionStorage.getItem(DISCLAIMER_FLAG)) return
const text = sheet.index.sheet.document.scope_disclaimer
setDisclaimer(
pickLabel({ fr: text.fr ?? '', en: text.en ?? '' }, locale) || null,
)
}, [sheet, locale])
const activeObs =
activeIndex >= 0 ? report?.observations[activeIndex] : undefined
const states = useMemo<ViewStates>(() => {
const map = new Map<string, 'current'>()
activeObs?.zones.forEach((z) => map.set(z.annotationId, 'current'))
return map
}, [activeObs])
const onZoneClick = useCallback(
(annotationId: string) => {
// Fresh state: two clicks may land before React re-renders the handler.
const { report, activeObservationIndex: activeIndex } =
useReportStore.getState()
if (sheet.status !== 'ready' || !report) return
const activeObs =
activeIndex >= 0 ? report.observations[activeIndex] : undefined
const index = sheet.index
const annotation = index.annotation(annotationId)
const decision = decideZoneClick(annotation, activeObs)
if (!annotation) return
switch (decision.kind) {
case 'ignore':
return
case 'open_view':
return setDetailViewId(decision.viewId)
case 'activate_fallback':
return store.setActiveObservation(report.observations.length - 1)
case 'open_vertebra_picker': {
const { observation, index: zoneIndex } = ensureZone(
activeObs!,
annotation,
)
store.updateObservation(activeIndex, observation)
return setVertebraTarget(zoneIndex)
}
case 'open_laterality_picker':
return setLateralTarget(refOf(annotation))
case 'remove_both_sides':
return store.updateObservation(
activeIndex,
removeAllSides(activeObs!, refOf(annotation)),
)
case 'toggle':
return store.updateObservation(
activeIndex,
toggleZone(activeObs!, annotation),
)
}
},
[sheet, store],
)
function acknowledgeDisclaimer() {
sessionStorage?.setItem(DISCLAIMER_FLAG, '1')
setDisclaimer(null)
}
function saveEditInfos() {
if (!editDraft) return
if (!isIdentityComplete(editDraft)) return
store.setPractitioner(editDraft.practitioner)
store.setAnimal(editDraft.animal)
store.setOwner(editDraft.owner)
writeCachedPractitioner(editDraft.practitioner)
setEditDraft(null)
}
async function onExport(index: SheetIndex) {
if (!report) return
setExporting(true)
try {
const { pdf, warnings } = await exportReportToPdf(report, index, {
locale,
})
const blob = new Blob([pdf as BlobPart], { type: 'application/pdf' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
a.click()
URL.revokeObjectURL(url)
const missing = missingItemsOf(warnings)
if (missing.length) {
window.alert(
t('editor.export_warnings').replace('{items}', missing.join(', ')),
)
}
} catch (err) {
console.error('PDF export failed', err)
window.alert(t('editor.export_failed'))
} finally {
setExporting(false)
}
}
if (!report) return null
if (sheet.status === 'loading') {
return (
<p className="p-6 text-sm text-[var(--color-ink-muted)]">
{t('sheet.loading')}
</p>
)
}
if (sheet.status === 'none') return null
const index = sheet.index
const detailView = detailViewId ? index.view(detailViewId) : undefined
return (
<main className="min-h-screen flex flex-col">
<ReportHeader
report={report}
onEditInfos={() =>
setEditDraft({
practitioner: report.practitioner,
animal: report.animal,
owner: report.owner,
})
}
/>
<div className="flex-1 grid grid-cols-1 lg:grid-cols-[2fr_3fr] gap-4 sm:gap-6 p-4 sm:p-6">
<section className="border border-[var(--color-border)] rounded-2xl bg-[var(--color-surface)] overflow-hidden max-h-[55vh] lg:max-h-none flex flex-col">
<AnatomyCanvas
index={index}
viewId={index.mainView.id}
states={states}
onZoneClick={onZoneClick}
className="flex-1"
/>
<p
className="px-3 py-1.5 text-xs text-[var(--color-ink-muted)] border-t border-[var(--color-border)]"
data-testid="sheet-status"
>
{t(
index.sheet.status === 'draft'
? 'sheet.status.draft'
: 'sheet.status.published',
)}
</p>
</section>
<section className="space-y-4 sm:space-y-6">
<ObservationList
observations={report.observations}
activeIndex={activeIndex}
onToggle={(i) =>
store.setActiveObservation(activeIndex === i ? -1 : i)
}
onAdd={store.addObservation}
onDelete={store.removeObservation}
onMoveUp={store.moveObservationUp}
onMoveDown={store.moveObservationDown}
sheet={index}
onChange={store.updateObservation}
onOpenVertebraPicker={(_i, zoneIndex) =>
setVertebraTarget(zoneIndex)
}
onRemoveZone={(i, zoneIndex) => {
const obs = report.observations[i]
if (obs) store.updateObservation(i, removeZoneAt(obs, zoneIndex))
}}
/>
<ConclusionPanel
conclusion={report.conclusion}
recommendations={report.recommendations}
nextAppointment={report.nextAppointment}
onChangeConclusion={store.setConclusion}
onChangeRecommendations={store.setRecommendations}
onChangeNextAppointment={store.setNextAppointment}
/>
<div className="flex justify-end">
<Button onClick={() => onExport(index)} disabled={exporting}>
{exporting ? t('editor.exporting') : t('editor.export')}
</Button>
</div>
</section>
</div>
{detailView && (
<DetailModal
open
onClose={() => setDetailViewId(null)}
index={index}
viewId={detailView.id}
title={pickLabel(detailView.name, locale)}
states={states}
onZoneClick={onZoneClick}
/>
)}
{editDraft && (
<EditInfosDialog
draft={editDraft}
species={[
{ id: index.sheet.speciesId, name: index.sheet.document.name },
]}
onChange={setEditDraft}
onCancel={() => setEditDraft(null)}
onSave={saveEditInfos}
/>
)}
{disclaimer && (
<DisclaimerDialog
text={disclaimer}
onAcknowledge={acknowledgeDisclaimer}
/>
)}
<ObservationPickers
sheet={index}
activeIndex={activeIndex}
activeObs={activeObs}
vertebraTarget={vertebraTarget}
lateralTarget={lateralTarget}
onCloseVertebra={() => setVertebraTarget(null)}
onCloseLateral={() => setLateralTarget(null)}
/>
</main>
)
}
+206
View File
@@ -0,0 +1,206 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import {
rebaseReportOnSheet,
type ArchiveReadOutcome,
type RebaseOutcome,
} from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/**
* The detail lines of the import alert (STEP6 §16), in a fixed order: a
* lossy v2 migration, the archive kept, the snapshot dropped with its
* reason, the rebase onto the current sheet. Empty when nothing applies.
*/
function importDetailLines(
outcome: ArchiveReadOutcome,
rebase: RebaseOutcome,
t: Translate,
): string[] {
const lines: string[] = []
const lost = outcome.unresolvedFindings + outcome.unresolvedZones
if (outcome.migrated && lost > 0) {
lines.push(t('home.import.migrated').replace('{count}', String(lost)))
}
if (outcome.archive) lines.push(t('home.import.archive_ok'))
if (outcome.snapshotRejected) {
lines.push(
t('home.import.snapshot_rejected').replace(
'{reason}',
t(`home.import.snapshot_reason.${outcome.snapshotRejected}`),
),
)
}
if (rebase.rebased) {
const count = rebase.unresolvedZones + rebase.unresolvedFindings
lines.push(t('home.import.rebased').replace('{count}', String(count)))
}
return lines
}
/**
* Degraded recovery: something the practitioner must check. A rejected
* snapshot, a migration or a rebase that lost items. A rebase that resolved
* everything is a complete restoration on a different sheet.
*/
function isDegradedImport(
outcome: ArchiveReadOutcome,
rebase: RebaseOutcome,
): boolean {
const lost = outcome.unresolvedFindings + outcome.unresolvedZones
const rebaseLost = rebase.unresolvedZones + rebase.unresolvedFindings
return (
outcome.snapshotRejected !== undefined ||
(outcome.migrated && lost > 0) ||
(rebase.rebased && rebaseLost > 0)
)
}
/**
* The one alert shown after a successful import: a headline that says
* whether the restoration is complete or partial, then the detail lines.
* Empty (no alert) when there is nothing to say: a bare v3 on the same sheet.
*/
function importMessages(
outcome: ArchiveReadOutcome,
rebase: RebaseOutcome,
t: Translate,
): string[] {
const details = importDetailLines(outcome, rebase, t)
if (details.length === 0) return []
const headline = isDegradedImport(outcome, rebase)
? t('home.import.degraded')
: t('home.import.complete')
return [headline, ...details]
}
/** The error line under the import button, by ImportError kind. */
function importErrorMessage(err: unknown, t: Translate): string {
if (!(err instanceof ImportError)) return t('home.import.error_generic')
switch (err.kind) {
case 'incompatible_version':
return t('home.import.error_incompatible_version').replace(
'{version}',
String(err.foundVersion ?? '?'),
)
case 'invalid_pdf':
return t('home.import.error_invalid_pdf')
case 'attachment_stripped':
return t('home.import.error_attachment_stripped')
case 'no_attachment':
return t('home.import.error_no_attachment')
}
}
export default function HomeRoute() {
const navigate = useNavigate()
const fileRef = useRef<HTMLInputElement | null>(null)
const hydrateImport = useReportStore((s) => s.hydrateImport)
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const t = useT()
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File, index: SheetIndex) {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
const outcome = await importReportFromPdf(bytes, index.sheet.migrationMap)
const rebase = rebaseReportOnSheet(
outcome.report,
index,
outcome.archive?.sheetSnapshot ?? null,
)
hydrateImport({ report: rebase.report, archive: outcome.archive })
const lines = importMessages(outcome, rebase, t)
if (lines.length > 0) window.alert(lines.join('\n\n'))
navigate('/editor')
}
async function onPickFile(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file || sheet.status !== 'ready') return
setBusy(true)
setError(null)
try {
await importFile(file, sheet.index)
} catch (err) {
setError(importErrorMessage(err, t))
} finally {
setBusy(false)
if (fileRef.current) fileRef.current.value = ''
}
}
const noSheet = sheet.status === 'none'
return (
<main className="flex-1 flex flex-col">
<AppHeader />
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
{noSheet && (
<Card className="p-4 sm:p-6 space-y-2 md:col-span-2">
<h2 className="font-serif text-xl sm:text-2xl">
{t('home.no_sheet.title')}
</h2>
<p className="text-sm text-red-700">
{t('home.no_sheet.description')}
</p>
</Card>
)}
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">
{t('home.new_report.title')}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('home.new_report.description')}
</p>
<Button
onClick={() => navigate('/new')}
size="lg"
disabled={noSheet}
>
{t('home.new_report.cta')}
</Button>
</Card>
<Card className="p-4 sm:p-6 space-y-3 sm:space-y-4">
<h2 className="font-serif text-xl sm:text-2xl">
{t('home.import.title')}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('home.import.description')}
</p>
<input
ref={fileRef}
type="file"
accept="application/pdf,.pdf"
className="hidden"
onChange={onPickFile}
/>
<Button
variant="secondary"
size="lg"
onClick={() => fileRef.current?.click()}
disabled={busy || sheet.status !== 'ready'}
>
{busy ? t('home.import.loading') : t('home.import.cta')}
</Button>
{error && <p className="text-sm text-red-700">{error}</p>}
</Card>
</div>
</section>
</main>
)
}
+119
View File
@@ -0,0 +1,119 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label'
import { todayIso } from '@/lib/dates'
import {
readCachedPractitioner,
writeCachedPractitioner,
} from '@/state/practitionerCache'
import { useReportStore } from '@/state/reportStore'
import { useSheet } from '@/sheets/useSheet'
import { useT } from '@/i18n/useT'
/** The one species this build ships a sheet for. */
export const DEFAULT_SPECIES_ID = 'equine'
export default function NewReportRoute() {
const navigate = useNavigate()
const initReport = useReportStore((s) => s.initReport)
const t = useT()
const sheet = useSheet(DEFAULT_SPECIES_ID)
const [practitioner, setPractitioner] = useState<Practitioner>({ name: '' })
const [animal, setAnimal] = useState<Animal>({
speciesId: DEFAULT_SPECIES_ID,
name: '',
})
const [owner, setOwner] = useState<Owner>({ name: '' })
const [date, setDate] = useState(todayIso())
useEffect(() => {
const cached = readCachedPractitioner()
if (cached) setPractitioner(cached)
}, [])
const canSubmit =
practitioner.name.trim() &&
animal.name.trim() &&
owner.name.trim() &&
sheet.status === 'ready'
function submit() {
if (!canSubmit || sheet.status !== 'ready') return
writeCachedPractitioner(practitioner)
initReport(
{
date,
practitioner,
animal,
owner,
observations: [],
conclusion: '',
recommendations: '',
},
sheet.index.sheet.ref,
)
navigate('/editor')
}
return (
<main className="min-h-screen">
<AppHeader />
<div className="max-w-3xl mx-auto px-4 sm:px-6 py-6 sm:py-8 space-y-6 sm:space-y-8">
<h1 className="font-serif text-2xl sm:text-3xl">
{t('new_report.title')}
</h1>
{sheet.status === 'none' && (
<p className="text-sm text-red-700">
{t('home.no_sheet.description')}
</p>
)}
<div>
<Label htmlFor="date">{t('new_report.date_label')}</Label>
<Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
</div>
<PractitionerForm value={practitioner} onChange={setPractitioner} />
<AnimalForm
animal={animal}
owner={owner}
species={
sheet.status === 'ready'
? [
{
id: sheet.index.sheet.speciesId,
name: sheet.index.sheet.document.name,
},
]
: [
{
id: DEFAULT_SPECIES_ID,
name: { fr: 'Cheval', en: 'Horse' },
},
]
}
onChangeAnimal={setAnimal}
onChangeOwner={setOwner}
/>
<div className="flex gap-3 justify-end">
<Button variant="ghost" onClick={() => navigate('/')}>
{t('common.cancel')}
</Button>
<Button disabled={!canSubmit} onClick={submit}>
{t('new_report.submit')}
</Button>
</div>
</div>
</main>
)
}
@@ -9,8 +9,12 @@ export default function NotFoundRoute() {
<main className="min-h-screen grid place-items-center">
<div className="text-center space-y-4">
<h1 className="font-serif text-4xl">{t('not_found.title')}</h1>
<p className="text-[var(--color-ink-muted)]">{t('not_found.description')}</p>
<Button onClick={() => navigate('/')}>{t('common.back_to_home')}</Button>
<p className="text-[var(--color-ink-muted)]">
{t('not_found.description')}
</p>
<Button onClick={() => navigate('/')}>
{t('common.back_to_home')}
</Button>
</div>
</main>
)
File renamed without changes.
@@ -1,10 +1,13 @@
import { useConfig } from '@/app/providers/ConfigProvider'
const HEIGHT = { sm: 'h-7', md: 'h-9', lg: 'h-11' } as const
export default function Brand({ size = 'md' }: { size?: 'sm' | 'md' | 'lg' }) {
const { brandName } = useConfig()
return (
<img
src="/logo-horizontal.svg"
alt="Faunosteo"
alt={brandName}
className={`${HEIGHT[size]} w-auto`}
/>
)
@@ -1,6 +1,6 @@
import { Link } from 'react-router-dom'
import { useConfig } from '@/app/providers/ConfigProvider'
import { useT } from '@/i18n/useT'
import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url'
export default function Footer() {
const cfg = useConfig()
@@ -9,14 +9,7 @@ export default function Footer() {
return (
<footer className="mt-8 sm:mt-12 border-t border-neutral-200 bg-neutral-50 py-4 sm:py-6 text-center text-xs sm:text-sm text-neutral-600">
<p className="mb-3">
© {year} {cfg.footerName}. {t('footer.all_rights_reserved')}{' '}
<span className="text-neutral-300">·</span>{' '}
<Link
to="/editors"
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors"
>
{t('footer.editors')}
</Link>
© {year} {cfg.footerName}. {t('footer.all_rights_reserved')}
</p>
<div className="flex flex-wrap items-center justify-center gap-2 sm:gap-4">
<span className="flex items-center gap-2">
@@ -45,7 +38,7 @@ export default function Footer() {
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium"
>
<img
src="/Paws_in_harmony.svg"
src={pawsInHarmonyUrl}
alt="Paws in Harmony"
className="h-6 w-auto inline-block align-middle"
/>
@@ -1,18 +1,20 @@
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
import type { Locale } from '@/i18n/types'
const ITEMS: { value: Locale; label: string; ariaLabel: string }[] = [
{ value: 'fr', label: 'FR', ariaLabel: 'Passer en français' },
{ value: 'en', label: 'EN', ariaLabel: 'Switch to English' },
const ITEMS: { value: Locale; labelKey: string; ariaKey: string }[] = [
{ value: 'fr', labelKey: 'lang.fr', ariaKey: 'lang.switch_to_fr' },
{ value: 'en', labelKey: 'lang.en', ariaKey: 'lang.switch_to_en' },
]
export default function LanguageSwitcher() {
const locale = useLocaleStore((s) => s.locale)
const setLocale = useLocaleStore((s) => s.setLocale)
const t = useT()
return (
<div
role="group"
aria-label="Language"
aria-label={t('lang.group_label')}
className="inline-flex rounded-full border border-[var(--color-border)] overflow-hidden text-xs font-medium"
>
{ITEMS.map((item) => {
@@ -21,7 +23,7 @@ export default function LanguageSwitcher() {
<button
key={item.value}
type="button"
aria-label={item.ariaLabel}
aria-label={t(item.ariaKey)}
aria-pressed={active}
onClick={() => setLocale(item.value)}
className={[
@@ -31,7 +33,7 @@ export default function LanguageSwitcher() {
: 'text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)]',
].join(' ')}
>
{item.label}
{t(item.labelKey)}
</button>
)
})}
@@ -0,0 +1,128 @@
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useLocaleStore } from '@/state/localeStore'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
export interface AnatomyCanvasProps {
index: SheetIndex
viewId: string
states: ViewStates
onZoneClick: (annotationId: string, viewId: string) => void
className?: string
}
const ANNOTATED = '[data-anno-id]'
function annotatedTarget(event: Event): Element | null {
const target = event.target
return target instanceof Element ? target.closest(ANNOTATED) : null
}
/**
* One view of the sheet: the drawing plus the annotation layer generated
* from the document, rebuilt when the view changes and restyled in place
* when the selection changes. Clicks are delegated on `data-anno-id`.
*/
export default function AnatomyCanvas({
index,
viewId,
states,
onZoneClick,
className = '',
}: AnatomyCanvasProps) {
const wrapperRef = useRef<HTMLDivElement | null>(null)
const svgRef = useRef<HTMLDivElement | null>(null)
const tooltipRef = useRef<HTMLDivElement | null>(null)
const locale = useLocaleStore((s) => s.locale)
// Latest states for the build effect, which must only re-run on a view change.
const statesRef = useRef(states)
useLayoutEffect(() => {
statesRef.current = states
}, [states])
useEffect(() => {
const host = svgRef.current
if (!host) return
host.replaceChildren(buildViewSvg(index, viewId, statesRef.current))
}, [index, viewId])
useEffect(() => {
const host = svgRef.current
if (!host) return
host.querySelectorAll<Element>(ANNOTATED).forEach((el) => {
const state = states.get(el.getAttribute('data-anno-id') ?? '')
if (state) el.setAttribute('data-state', state)
else el.removeAttribute('data-state')
})
}, [states, index, viewId])
useEffect(() => {
const host = svgRef.current
if (!host) return
const onClick = (e: Event) => {
const id = annotatedTarget(e)?.getAttribute('data-anno-id')
if (id) onZoneClick(id, viewId)
}
host.addEventListener('click', onClick)
return () => host.removeEventListener('click', onClick)
}, [onZoneClick, viewId])
const showTooltip = useCallback(
(el: Element, x: number, y: number) => {
const tip = tooltipRef.current
if (!tip) return
const label = pickLocaleLabel(
el.getAttribute('data-anno-name-fr') ?? '',
el.getAttribute('data-anno-name-en') ?? '',
locale,
)
if (!label) {
tip.style.opacity = '0'
return
}
tip.textContent = label
tip.style.opacity = '1'
tip.style.left = `${x + 12}px`
tip.style.top = `${y - 8}px`
},
[locale],
)
useEffect(() => {
const host = svgRef.current
if (!host) return
const hide = () => {
if (tooltipRef.current) tooltipRef.current.style.opacity = '0'
}
const onMove = (e: MouseEvent) => {
const el = annotatedTarget(e)
const wrapper = wrapperRef.current
if (!el || !wrapper || el.hasAttribute('data-anno-opens-view'))
return hide()
const rect = wrapper.getBoundingClientRect()
showTooltip(el, e.clientX - rect.left, e.clientY - rect.top)
}
host.addEventListener('mousemove', onMove)
host.addEventListener('mouseleave', hide)
return () => {
host.removeEventListener('mousemove', onMove)
host.removeEventListener('mouseleave', hide)
}
}, [showTooltip])
return (
<div
data-testid="anatomy-canvas"
data-view-id={viewId}
ref={wrapperRef}
className={`svg-canvas relative w-full h-full ${className}`}
>
<div
ref={svgRef}
className="w-full h-full [&>svg]:max-w-full [&>svg]:max-h-full [&>svg]:mx-auto"
/>
<div ref={tooltipRef} className="zone-tooltip" style={{ opacity: 0 }} />
</div>
)
}
@@ -0,0 +1,43 @@
import Dialog from '@/components/ui/Dialog'
import AnatomyCanvas from './AnatomyCanvas'
import type { ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
export interface DetailModalProps {
open: boolean
onClose: () => void
index: SheetIndex
viewId: string
title: string
states: ViewStates
onZoneClick: (annotationId: string, viewId: string) => void
}
/** A detail view of the sheet (a crop or its own drawing) in a dialog. */
export default function DetailModal({
open,
onClose,
index,
viewId,
title,
states,
onZoneClick,
}: DetailModalProps) {
const t = useT()
return (
<Dialog open={open} onClose={onClose} title={title} size="xl">
<div className="aspect-[4/3] w-full">
<AnatomyCanvas
index={index}
viewId={viewId}
states={states}
onZoneClick={onZoneClick}
/>
</div>
<p className="mt-4 text-sm text-[var(--color-ink-muted)]">
{t('detail.click_to_add')}
</p>
</Dialog>
)
}
@@ -0,0 +1,286 @@
import { useMemo, useState } from 'react'
import { motion } from 'motion/react'
import type {
Finding,
FindingCategory,
FindingNode,
FindingZone,
LateralSide,
LocalizedOptionalText,
} from '@faunosteo/domain'
import Button from '@/components/ui/Button'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
const levelVariants = {
enter: (dir: 1 | -1) => ({ opacity: 0, x: dir * 32 }),
center: { opacity: 1, x: 0 },
}
type TreeNode = FindingCategory | FindingNode
export interface FindingsTreePickerProps {
zone: FindingZone
side?: LateralSide
selected: Finding[]
onChange: (next: Finding[]) => void
}
function isLeaf(node: TreeNode): boolean {
return node.children.length === 0
}
function samePath(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((seg, i) => seg === b[i])
}
function pathStartsWith(
full: readonly string[],
prefix: readonly string[],
): boolean {
return (
full.length >= prefix.length && prefix.every((seg, i) => full[i] === seg)
)
}
function findNode(
categories: readonly FindingCategory[],
path: readonly string[],
): TreeNode | undefined {
let nodes: readonly TreeNode[] = categories
let node: TreeNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node
}
function descriptionOf(node: TreeNode, locale: Locale): string | undefined {
const text: LocalizedOptionalText | undefined = node.description
if (!text) return undefined
return (
(locale === 'en' ? text.en || text.fr : text.fr || text.en) || undefined
)
}
/**
* Drill-down picker over one finding zone of the sheet. A finding is keyed
* by `(findingZoneId, path, side)`; labels are snapshotted at selection.
*/
export default function FindingsTreePicker({
zone,
side,
selected,
onChange,
}: FindingsTreePickerProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [path, setPath] = useState<string[]>([])
const [direction, setDirection] = useState<1 | -1>(1)
function goInto(nodePath: string[]) {
setDirection(1)
setPath(nodePath)
}
function goBack() {
setDirection(-1)
setPath(path.slice(0, -1))
}
function goToDepth(depth: number) {
setDirection(depth >= path.length ? 1 : -1)
setPath(path.slice(0, depth))
}
const currentNodes = useMemo<readonly TreeNode[]>(() => {
if (path.length === 0) return zone.categories
return findNode(zone.categories, path)?.children ?? []
}, [zone, path])
const focusedNode = useMemo(
() => (path.length === 0 ? undefined : findNode(zone.categories, path)),
[zone, path],
)
const breadcrumb = useMemo<{ label: string; depth: number }[]>(() => {
const crumbs = [{ label: pickLabel(zone.name, locale), depth: 0 }]
let nodes: readonly TreeNode[] = zone.categories
path.forEach((seg, i) => {
const n = nodes.find((x) => x.id === seg)
if (n) {
crumbs.push({ label: pickLabel(n.name, locale), depth: i + 1 })
nodes = n.children
}
})
return crumbs
}, [zone, path, locale])
const matches = (f: Finding) => f.findingZoneId === zone.id && f.side === side
const isLeafSelected = (leafPath: string[]) =>
selected.some((f) => matches(f) && samePath(f.path, leafPath))
const countSelectedUnder = (nodePath: string[]) =>
selected.filter((f) => matches(f) && pathStartsWith(f.path, nodePath))
.length
function toggleLeaf(leafPath: string[], leaf: TreeNode) {
if (isLeafSelected(leafPath)) {
onChange(
selected.filter((f) => !(matches(f) && samePath(f.path, leafPath))),
)
return
}
const next: Finding = {
findingZoneId: zone.id,
path: leafPath,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en,
}
if ('requires_vet_referral' in leaf && leaf.requires_vet_referral)
next.requiresVetReferral = true
if (side) next.side = side
onChange([...selected, next])
}
const focusedDescription = focusedNode && descriptionOf(focusedNode, locale)
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-1 text-xs text-[var(--color-ink-muted)]">
{breadcrumb.map((c, i) => {
const isLast = i === breadcrumb.length - 1
return (
<span key={`${c.label}-${i}`} className="flex items-center gap-1">
<button
type="button"
onClick={() => goToDepth(c.depth)}
disabled={isLast}
className={
isLast
? 'text-[var(--color-ink)] font-medium'
: 'underline text-[var(--color-accent-strong)]'
}
>
{c.label}
</button>
{!isLast && <span aria-hidden="true">›</span>}
</span>
)
})}
</div>
{focusedDescription && (
<p className="text-xs italic text-[var(--color-ink-muted)]">
{focusedDescription}
</p>
)}
{path.length > 0 && (
<Button
size="sm"
variant="ghost"
onClick={goBack}
aria-label={t('findings.back_to_parent')}
>
{t('findings.back')}
</Button>
)}
<motion.ul
key={path.join('/') || '__root__'}
custom={direction}
variants={levelVariants}
initial="enter"
animate="center"
transition={{ duration: 0.22, ease: 'easeOut' }}
className="space-y-1.5 max-h-64 overflow-auto pr-1"
>
{currentNodes.length === 0 ? (
<li className="text-sm text-[var(--color-ink-muted)]">
{t('findings.no_options')}
</li>
) : (
currentNodes.map((node) => {
const nodePath = [...path, node.id]
const nodeLabel = pickLabel(node.name, locale)
const nodeDesc = descriptionOf(node, locale)
if (isLeaf(node)) {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
return (
<li key={node.id}>
<label className="flex items-start gap-2 cursor-pointer">
<input
type="checkbox"
checked={isLeafSelected(nodePath)}
onChange={() => toggleLeaf(nodePath, node)}
className="mt-1 accent-[var(--color-accent)]"
aria-label={nodeLabel}
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]">
{nodeLabel}
</span>
{vet && (
<span
title={t('findings.vet_referral')}
aria-label={t('findings.vet_referral')}
className="text-[var(--color-danger)]"
>
⚠
</span>
)}
</div>
{nodeDesc && (
<div className="text-xs text-[var(--color-ink-muted)]">
{nodeDesc}
</div>
)}
</div>
</label>
</li>
)
}
const selectedCount = countSelectedUnder(nodePath)
const selectedAria = `${selectedCount} ${
selectedCount > 1
? t('findings.selected_plural')
: t('findings.selected_singular')
}`
return (
<li key={node.id}>
<button
type="button"
onClick={() => goInto(nodePath)}
className="flex items-center justify-between w-full text-left text-sm px-2 py-1.5 rounded hover:bg-[var(--color-surface-strong)] text-[var(--color-ink)]"
aria-label={`${t('findings.open')} ${nodeLabel}`}
>
<span className="flex items-center gap-2">
<span>{nodeLabel}</span>
{selectedCount > 0 && (
<span
aria-label={selectedAria}
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
>
{selectedCount}
</span>
)}
</span>
<span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
›
</span>
</button>
</li>
)
})
)}
</motion.ul>
</div>
)
}
@@ -0,0 +1,62 @@
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import type { LateralSide } from '@faunosteo/domain'
import { useT } from '@/i18n/useT'
export interface LateralityPickerProps {
open: boolean
onClose: () => void
onSelect: (sides: LateralSide[]) => void
title: string
existingSides: LateralSide[]
}
export default function LateralityPicker({
open,
onClose,
onSelect,
title,
existingSides,
}: LateralityPickerProps) {
const t = useT()
const hasLeft = existingSides.includes('left')
const hasRight = existingSides.includes('right')
return (
<Dialog open={open} onClose={onClose} title={title} size="sm">
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink-muted)]">
{t('lateral.which_side')}
</p>
<div className="flex gap-3 justify-center">
<Button
variant={hasLeft ? 'ghost' : 'primary'}
disabled={hasLeft}
onClick={() => onSelect(['left'])}
>
{t('lateral.left')}
</Button>
<Button
variant={hasRight ? 'ghost' : 'primary'}
disabled={hasRight}
onClick={() => onSelect(['right'])}
>
{t('lateral.right')}
</Button>
<Button
variant={hasLeft && hasRight ? 'ghost' : 'primary'}
disabled={hasLeft && hasRight}
onClick={() => {
const sides: LateralSide[] = []
if (!hasLeft) sides.push('left')
if (!hasRight) sides.push('right')
onSelect(sides)
}}
>
{t('lateral.both')}
</Button>
</div>
</div>
</Dialog>
)
}
@@ -0,0 +1,471 @@
import { useMemo, useState } from 'react'
import type {
Finding,
FindingZone,
LateralSide,
Observation,
ReportZone,
} from '@faunosteo/domain'
import { AnimatePresence, motion } from 'motion/react'
import Card from '@/components/ui/Card'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import FindingsTreePicker from './FindingsTreePicker'
import FreeTextFindingInput from './FreeTextFindingInput'
import SeveritySelector from './SeveritySelector'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
export interface ObservationCardProps {
observation: Observation
index: number
expanded: boolean
onToggle: () => void
onDelete: () => void
onMoveUp: () => void
onMoveDown: () => void
canMoveUp: boolean
canMoveDown: boolean
// Editor body props (used only when expanded)
sheet: SheetIndex
onChange: (next: Observation) => void
onOpenVertebraPicker: (zoneIndex: number) => void
onRemoveZone: (zoneIndex: number) => void
}
/** Zone label: the sheet's current name, else the snapshot, else the id. */
export function zoneLabel(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function describeZone(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
t: (key: string) => string,
): string {
const label = zoneLabel(z, sheet, locale)
if (z.vertebrae?.length) {
return `${label} (${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')})`
}
if (z.side) {
return `${label} (${t(z.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`
}
return label
}
interface ZoneTree {
zone: FindingZone
side?: LateralSide
}
/** One picker per (finding zone, side) the observation's zones resolve to. */
function zoneTrees(observation: Observation, sheet: SheetIndex): ZoneTree[] {
const seen = new Set<string>()
const out: ZoneTree[] = []
for (const z of observation.zones) {
const annotation = sheet.annotation(z.annotationId)
if (!isObservable(annotation) || !annotation.finding_zone_id) continue
const zone = sheet.findingZone(annotation.finding_zone_id)
if (!zone) continue
const key = z.side ? `${zone.id}:${z.side}` : zone.id
if (seen.has(key)) continue
seen.add(key)
out.push({ zone, side: z.side })
}
return out
}
/** Findings the sheet no longer holds at their path (migrated data, kept verbatim). */
function unresolvedFindings(
observation: Observation,
sheet: SheetIndex,
): Finding[] {
return observation.findings.filter(
(f) => !sheet.nodeAt(f.findingZoneId, f.path),
)
}
export default function ObservationCard({
observation,
index,
expanded,
onToggle,
onDelete,
onMoveUp,
onMoveDown,
canMoveUp,
canMoveDown,
sheet,
onChange,
onOpenVertebraPicker,
onRemoveZone,
}: ObservationCardProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [expandedZoneId, setExpandedZoneId] = useState<string | null>(null)
const zoneCount = observation.zones.length
const findingCount =
observation.findings.length + observation.freeTextFindings.length
const zoneCountLabel = t(
zoneCount > 1
? 'observation.zone_label_plural'
: 'observation.zone_label_singular',
)
const findingCountLabel = t(
findingCount > 1
? 'observation.finding_label_plural'
: 'observation.finding_label_singular',
)
const trees = useMemo(
() => zoneTrees(observation, sheet),
[observation, sheet],
)
const unresolved = useMemo(
() => unresolvedFindings(observation, sheet),
[observation, sheet],
)
function onHeaderKey(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
onToggle()
}
}
const stop = (fn: () => void) => (event: React.MouseEvent) => {
event.stopPropagation()
fn()
}
const removeFinding = (target: Finding) =>
onChange({
...observation,
findings: observation.findings.filter((f) => f !== target),
})
return (
<Card
className={[
'transition',
expanded
? 'ring-2 ring-[var(--color-accent)]'
: 'hover:bg-[var(--color-surface-strong)]',
].join(' ')}
>
<div
role="button"
tabIndex={0}
aria-expanded={expanded}
aria-label={`${expanded ? t('observation.collapse_aria') : t('observation.expand_aria')} ${index + 1}`}
onClick={onToggle}
onKeyDown={onHeaderKey}
className="flex items-start justify-between gap-3 p-4 cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40 rounded-2xl"
>
<div className="flex-1 min-h-[60px] text-left">
<div className="flex items-center gap-2 mb-2">
<Badge tone="neutral">
{t('observation.badge_n')}
{index + 1}
</Badge>
{observation.severity && (
<Badge
tone={
observation.severity === 'severe'
? 'danger'
: observation.severity === 'moderate'
? 'warn'
: 'neutral'
}
>
{t(`severity.${observation.severity}`)}
</Badge>
)}
</div>
<div className="text-sm text-[var(--color-ink-muted)]">
{zoneCount} {zoneCountLabel} · {findingCount} {findingCountLabel}
</div>
{!expanded && observation.comment && (
<p className="mt-2 text-sm line-clamp-2 text-[var(--color-ink)]">
{observation.comment}
</p>
)}
</div>
<div
className="flex items-start gap-1"
onClick={(event) => event.stopPropagation()}
>
<Button
size="sm"
variant="ghost"
disabled={!canMoveUp}
onClick={stop(onMoveUp)}
aria-label={t('common.move_up')}
>
↑
</Button>
<Button
size="sm"
variant="ghost"
disabled={!canMoveDown}
onClick={stop(onMoveDown)}
aria-label={t('common.move_down')}
>
↓
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onDelete)}
aria-label={t('common.delete')}
>
🗑
</Button>
<Button
size="sm"
variant="ghost"
onClick={stop(onToggle)}
aria-label={expanded ? t('common.collapse') : t('common.expand')}
>
{expanded ? '▲' : '▼'}
</Button>
</div>
</div>
<AnimatePresence initial={false}>
{expanded && (
<motion.div
key="body"
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-4 pb-4 pt-2 border-t border-[var(--color-border)] space-y-6">
<section>
<Label>{t('observation.zones_label')}</Label>
{observation.zones.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('observation.zones_empty')}
</p>
) : (
<ul className="flex flex-wrap gap-2">
{observation.zones.map((z, i) => (
<li
key={`${z.annotationId}-${z.viewId}-${z.side ?? ''}-${i}`}
>
<Badge tone="accent" className="gap-2">
{describeZone(z, sheet, locale, t)}
{z.unresolved &&
!sheet.annotation(z.annotationId) && (
<span
className="text-xs italic"
title={t('observation.zone_unresolved')}
>
{t('observation.unresolved_short')}
</span>
)}
{sheet.isSpine(z.annotationId) && (
<button
type="button"
onClick={() => onOpenVertebraPicker(i)}
className="underline text-xs text-[var(--color-accent-strong)]"
title={t('observation.vertebrae_button_title')}
>
{t('observation.vertebrae_button')}
</button>
)}
<button
type="button"
aria-label={`${t('observation.remove_zone')} ${zoneLabel(z, sheet, locale)}`}
onClick={() => onRemoveZone(i)}
className="ml-1 text-[var(--color-accent-strong)]"
>
✕
</button>
</Badge>
</li>
))}
</ul>
)}
</section>
<section>
<Label>{t('observation.findings_catalog_label')}</Label>
{trees.length === 0 ? (
<p className="text-sm text-[var(--color-ink-muted)]">
{observation.zones.length === 0
? t('observation.findings_pick_zone_first')
: t('observation.findings_no_catalog')}
</p>
) : (
<ul className="space-y-2">
{trees.map(({ zone, side }) => {
const pickerKey = side ? `${zone.id}:${side}` : zone.id
const open = expandedZoneId === pickerKey
const selectedCount = observation.findings.filter(
(f) => f.findingZoneId === zone.id && f.side === side,
).length
const selectedAria = `${selectedCount} ${selectedCount > 1 ? t('findings.selected_plural') : t('findings.selected_singular')}`
return (
<li
key={pickerKey}
className={[
'rounded-xl border bg-[var(--color-surface)] transition',
open
? 'border-[var(--color-accent)] ring-1 ring-[var(--color-accent)]'
: 'border-[var(--color-border)]',
].join(' ')}
>
<button
type="button"
onClick={() =>
setExpandedZoneId(open ? null : pickerKey)
}
aria-expanded={open}
aria-controls={`findings-zone-${pickerKey}`}
className="w-full flex items-center justify-between gap-2 px-3 py-2 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/40"
>
<span className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--color-ink)]">
{pickLabel(zone.name, locale)}
{side &&
` (${t(side === 'left' ? 'lateral.left' : 'lateral.right')})`}
</span>
{selectedCount > 0 && (
<span
aria-label={selectedAria}
className="inline-flex items-center justify-center min-w-[20px] h-[20px] px-1.5 rounded-full text-[11px] font-semibold bg-[var(--color-accent)] text-white"
>
{selectedCount}
</span>
)}
</span>
<span
aria-hidden="true"
className="text-[var(--color-ink-muted)]"
>
{open ? '▲' : '▼'}
</span>
</button>
<AnimatePresence initial={false}>
{open && (
<motion.div
key="picker-body"
id={`findings-zone-${pickerKey}`}
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.18, ease: 'easeOut' }}
className="overflow-hidden"
>
<div className="px-3 pb-3 pt-1 border-t border-[var(--color-border)]">
<FindingsTreePicker
zone={zone}
side={side}
selected={observation.findings}
onChange={(next) =>
onChange({
...observation,
findings: next,
})
}
/>
</div>
</motion.div>
)}
</AnimatePresence>
</li>
)
})}
</ul>
)}
</section>
{unresolved.length > 0 && (
<section>
<Label>{t('observation.findings_unresolved_label')}</Label>
<p className="text-xs text-[var(--color-ink-muted)] mb-2">
{t('observation.findings_unresolved_help')}
</p>
<ul className="space-y-1">
{unresolved.map((f, i) => (
<li
key={`${f.findingZoneId}-${f.path.join('/')}-${f.side ?? ''}-${i}`}
className="flex items-center gap-2 text-sm"
>
<span className="text-[var(--color-ink)]">
{f.requiresVetReferral ? '⚠ ' : ''}
{locale === 'en'
? f.labelEnSnapshot
: f.labelFrSnapshot}
{f.side &&
` (${t(f.side === 'left' ? 'lateral.left_short' : 'lateral.right_short')})`}
</span>
<button
type="button"
aria-label={`${t('common.delete')} ${locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot}`}
onClick={() => removeFinding(f)}
className="text-[var(--color-accent-strong)]"
>
✕
</button>
</li>
))}
</ul>
</section>
)}
<section>
<Label>{t('observation.findings_free_label')}</Label>
<FreeTextFindingInput
items={observation.freeTextFindings}
onChange={(items) =>
onChange({ ...observation, freeTextFindings: items })
}
/>
</section>
<section>
<Label>{t('observation.severity_label')}</Label>
<SeveritySelector
value={observation.severity}
onChange={(s) => onChange({ ...observation, severity: s })}
/>
</section>
<section>
<Label htmlFor={`obs-comment-${observation.id}`}>
{t('observation.comment_label')}
</Label>
<Textarea
id={`obs-comment-${observation.id}`}
value={observation.comment}
onChange={(e) =>
onChange({ ...observation, comment: e.target.value })
}
placeholder={t('observation.comment_placeholder')}
/>
</section>
</div>
</motion.div>
)}
</AnimatePresence>
</Card>
)
}
@@ -1,8 +1,7 @@
import type { Observation } from '@/domain/schema/observation'
import type { SpeciesFindings } from '@/domain/schema/findings'
import type { Bone } from '@/anatomy/types'
import type { Observation } from '@faunosteo/domain'
import ObservationCard from './ObservationCard'
import Button from '@/components/ui/Button'
import type { SheetIndex } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
export interface ObservationListProps {
@@ -14,8 +13,7 @@ export interface ObservationListProps {
onMoveUp: (i: number) => void
onMoveDown: (i: number) => void
// Editor body props forwarded to each card
bones: Map<string, Bone>
findings: SpeciesFindings | null
sheet: SheetIndex
onChange: (i: number, next: Observation) => void
onOpenVertebraPicker: (i: number, zoneIndex: number) => void
onRemoveZone: (i: number, zoneIndex: number) => void
@@ -29,8 +27,7 @@ export default function ObservationList({
onDelete,
onMoveUp,
onMoveDown,
bones,
findings,
sheet,
onChange,
onOpenVertebraPicker,
onRemoveZone,
@@ -64,8 +61,7 @@ export default function ObservationList({
onMoveDown={() => onMoveDown(i)}
canMoveUp={i > 0}
canMoveDown={i < observations.length - 1}
bones={bones}
findings={findings}
sheet={sheet}
onChange={(next) => onChange(i, next)}
onOpenVertebraPicker={(zoneIndex) =>
onOpenVertebraPicker(i, zoneIndex)
@@ -0,0 +1,95 @@
import type { LateralSide, Observation } from '@faunosteo/domain'
import VertebraPicker from '@/components/observation/VertebraPicker'
import LateralityPicker from '@/components/observation/LateralityPicker'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { isObservable, pickLabel, type SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
sidesPresent,
syncVertebrae,
type ZoneRef,
} from '@/services/zoneInteraction'
import { useT } from '@/i18n/useT'
export interface ObservationPickersProps {
sheet: SheetIndex
activeIndex: number
activeObs: Observation | undefined
vertebraTarget: number | null
lateralTarget: ZoneRef | null
onCloseVertebra: () => void
onCloseLateral: () => void
}
/** Vertebra and laterality pickers of the active observation. */
export default function ObservationPickers({
sheet,
activeIndex,
activeObs,
vertebraTarget,
lateralTarget,
onCloseVertebra,
onCloseLateral,
}: ObservationPickersProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const updateObservation = useReportStore((s) => s.updateObservation)
const vertebraZone =
vertebraTarget !== null ? activeObs?.zones[vertebraTarget] : undefined
const vertebraAnnotation =
vertebraZone && sheet.annotation(vertebraZone.annotationId)
const lateralAnnotation =
lateralTarget && sheet.annotation(lateralTarget.annotationId)
return (
<>
{vertebraTarget !== null &&
activeObs &&
vertebraZone &&
isObservable(vertebraAnnotation) && (
<VertebraPicker
open
onClose={onCloseVertebra}
onConfirm={(vertebrae) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh) {
updateObservation(
activeIndex,
syncVertebrae(fresh, vertebrae, sheet, vertebraZone.viewId),
)
}
onCloseVertebra()
}}
initial={collectVertebrae(activeObs, sheet, vertebraTarget)}
regions={sheet.regions()}
title={`${t('vertebra.title_prefix')}${pickLabel(vertebraAnnotation.name, locale)}`}
initialRegion={
vertebraAnnotation.vertebral_region_code ?? undefined
}
/>
)}
{lateralTarget && activeObs && lateralAnnotation && (
<LateralityPicker
open
onClose={onCloseLateral}
title={pickLabel(sheet.name(lateralAnnotation), locale)}
existingSides={sidesPresent(activeObs, lateralTarget)}
onSelect={(sides: LateralSide[]) => {
const fresh =
useReportStore.getState().report?.observations[activeIndex]
if (fresh)
updateObservation(
activeIndex,
addSides(fresh, lateralAnnotation, sides),
)
onCloseLateral()
}}
/>
)}
</>
)
}
@@ -1,4 +1,4 @@
import type { Severity } from '@/domain/schema/observation'
import type { Severity } from '@faunosteo/domain'
import { useT } from '@/i18n/useT'
export interface SeveritySelectorProps {
@@ -6,17 +6,25 @@ export interface SeveritySelectorProps {
onChange: (s: Severity | undefined) => void
}
const SEVERITIES: Severity[] = ['légère', 'modérée', 'sévère']
export const SEVERITIES: Severity[] = ['mild', 'moderate', 'severe']
const COLORS: Record<Severity, string> = {
'légère': 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
'modérée': 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
'sévère': 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
mild: 'border-[var(--severity-mild)] text-[var(--severity-mild)]',
moderate: 'border-[var(--severity-moderate)] text-[var(--severity-moderate)]',
severe: 'border-[var(--severity-severe)] text-[var(--severity-severe)]',
}
export default function SeveritySelector({ value, onChange }: SeveritySelectorProps) {
/** Severity codes are persisted; labels come from the dictionary (D8). */
export default function SeveritySelector({
value,
onChange,
}: SeveritySelectorProps) {
const t = useT()
return (
<div role="radiogroup" aria-label={t('severity.aria')} className="flex gap-2">
<div
role="radiogroup"
aria-label={t('severity.aria')}
className="flex gap-2"
>
{SEVERITIES.map((s) => (
<button
key={s}
@@ -0,0 +1,148 @@
import { useState } from 'react'
import type { Vertebra, VertebralRegion } from '@faunosteo/domain'
import Dialog from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import Chip from '@/components/ui/Chip'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface VertebraPickerProps {
open: boolean
onClose: () => void
onConfirm: (vertebrae: Vertebra[]) => void
initial: Vertebra[]
/** Ordered regions of the sheet (`vertebral_config.regions`). */
regions: readonly VertebralRegion[]
title: string
/** Tab to open on. Takes priority so a click always lands on its own zone. */
initialRegion?: string
}
const sameVertebra = (a: Vertebra, r: string, i: number) =>
a.region === r && a.index === i
/**
* Picks vertebrae across every region of the sheet. A region shows its
* usual count; when the sheet documents a wider range (D6), one control
* extends the grid to the documented maximum. Nothing horse-specific here.
*/
export default function VertebraPicker({
open,
onClose,
onConfirm,
initial,
regions,
title,
initialRegion,
}: VertebraPickerProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const [selected, setSelected] = useState<Vertebra[]>(initial)
const [activeCode, setActiveCode] = useState<string>(
() => initialRegion ?? initial[0]?.region ?? regions[0]?.code ?? '',
)
const [extended, setExtended] = useState<Set<string>>(() => new Set())
const active = regions.find((r) => r.code === activeCode) ?? regions[0]
if (!active) return null
const maxCount = active.count_range?.max ?? active.count
const highestPicked = Math.max(
0,
...selected.filter((v) => v.region === active.code).map((v) => v.index),
)
const canExtend = maxCount > active.count
const showExtended = extended.has(active.code) || highestPicked > active.count
const count = showExtended ? maxCount : active.count
const has = (r: string, i: number) =>
selected.some((v) => sameVertebra(v, r, i))
const toggle = (r: string, i: number) =>
setSelected((cur) =>
has(r, i)
? cur.filter((v) => !sameVertebra(v, r, i))
: [...cur, { region: r, index: i }],
)
const all = (r: string, n: number) =>
setSelected((cur) => [
...cur.filter((v) => v.region !== r),
...Array.from({ length: n }, (_, k) => ({ region: r, index: k + 1 })),
])
const none = (r: string) =>
setSelected((cur) => cur.filter((v) => v.region !== r))
return (
<Dialog open={open} onClose={onClose} title={title} size="lg">
<div role="tablist" className="flex flex-wrap gap-2 mb-4">
{regions.map((r) => (
<button
key={r.code}
role="tab"
aria-selected={active.code === r.code}
onClick={() => setActiveCode(r.code)}
className={[
'rounded-full px-4 py-2.5 sm:py-1.5 text-sm font-medium border min-h-[2.75rem]',
active.code === r.code
? 'bg-[var(--color-accent)] text-white border-[var(--color-accent)]'
: 'bg-white text-[var(--color-ink)] border-[var(--color-border)]',
].join(' ')}
>
{pickLabel(r.name, locale)}
</button>
))}
</div>
<div className="flex flex-wrap gap-2 mb-4 max-h-64 overflow-auto">
{Array.from({ length: count }, (_, k) => k + 1).map((i) => (
<Chip
key={i}
active={has(active.code, i)}
onClick={() => toggle(active.code, i)}
>
{active.code}
{i}
</Chip>
))}
</div>
<div className="flex flex-wrap items-center gap-2 mb-6">
<Button
variant="ghost"
size="sm"
onClick={() => all(active.code, active.count)}
>
{t('vertebra.check_all')}
</Button>
<Button variant="ghost" size="sm" onClick={() => none(active.code)}>
{t('vertebra.uncheck_all')}
</Button>
{canExtend && !showExtended && (
<Button
variant="ghost"
size="sm"
onClick={() => setExtended((cur) => new Set(cur).add(active.code))}
>
{t('vertebra.extend_to').replace('{max}', String(maxCount))}
</Button>
)}
{canExtend && showExtended && (
<span className="text-xs text-[var(--color-ink-muted)]">
{t('vertebra.range_note')
.replace('{usual}', String(active.count))
.replace('{min}', String(active.count_range?.min ?? active.count))
.replace('{max}', String(maxCount))}
</span>
)}
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={onClose}>
{t('common.cancel')}
</Button>
<Button onClick={() => onConfirm(selected)}>
{t('common.confirm')}
</Button>
</div>
</Dialog>
)
}
@@ -0,0 +1,89 @@
import type { Animal, LocalizedText, Owner } from '@faunosteo/domain'
import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input'
import Select from '@/components/ui/Select'
import { pickLabel } from '@/services/sheetIndex'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
export interface SpeciesOption {
id: string
name: LocalizedText
}
export interface AnimalFormProps {
animal: Animal
owner: Owner
/** Species that have a sheet in this build (one today). */
species: readonly SpeciesOption[]
onChangeAnimal: (next: Animal) => void
onChangeOwner: (next: Owner) => void
}
export default function AnimalForm({
animal,
owner,
species,
onChangeAnimal,
onChangeOwner,
}: AnimalFormProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const setA = (patch: Partial<Animal>) =>
onChangeAnimal({ ...animal, ...patch })
return (
<fieldset className="space-y-3">
<legend className="font-serif text-xl mb-2 text-[var(--color-ink)]">
{t('form.animal.legend')}
</legend>
<div>
<Label htmlFor="an-species">{t('form.animal.species')}</Label>
<Select
id="an-species"
value={animal.speciesId}
onChange={(e) => setA({ speciesId: e.target.value })}
>
{species.map((s) => (
<option key={s.id} value={s.id}>
{pickLabel(s.name, locale)}
</option>
))}
</Select>
</div>
<div>
<Label htmlFor="an-name">{t('form.animal.name')}</Label>
<Input
id="an-name"
required
value={animal.name}
onChange={(e) => setA({ name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="an-breed">{t('form.animal.breed')}</Label>
<Input
id="an-breed"
value={animal.breed ?? ''}
onChange={(e) => setA({ breed: e.target.value || undefined })}
/>
</div>
<div>
<Label htmlFor="an-age">{t('form.animal.age')}</Label>
<Input
id="an-age"
value={animal.age ?? ''}
onChange={(e) => setA({ age: e.target.value || undefined })}
/>
</div>
<div>
<Label htmlFor="own-name">{t('form.owner.name')}</Label>
<Input
id="own-name"
required
value={owner.name}
onChange={(e) => onChangeOwner({ name: e.target.value })}
/>
</div>
</fieldset>
)
}
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report'
import type { Report } from '@faunosteo/domain'
import Label from '@/components/ui/Label'
import Textarea from '@/components/ui/Textarea'
import NextAppointmentPicker from './NextAppointmentPicker'
@@ -29,13 +29,26 @@ export default function ConclusionPanel({
</h2>
<div>
<Label htmlFor="conclusion">{t('conclusion.conclusion')}</Label>
<Textarea id="conclusion" value={conclusion} onChange={(e) => onChangeConclusion(e.target.value)} />
<Textarea
id="conclusion"
value={conclusion}
onChange={(e) => onChangeConclusion(e.target.value)}
/>
</div>
<div>
<Label htmlFor="recommendations">{t('conclusion.recommendations')}</Label>
<Textarea id="recommendations" value={recommendations} onChange={(e) => onChangeRecommendations(e.target.value)} />
<Label htmlFor="recommendations">
{t('conclusion.recommendations')}
</Label>
<Textarea
id="recommendations"
value={recommendations}
onChange={(e) => onChangeRecommendations(e.target.value)}
/>
</div>
<NextAppointmentPicker value={nextAppointment} onChange={onChangeNextAppointment} />
<NextAppointmentPicker
value={nextAppointment}
onChange={onChangeNextAppointment}
/>
</section>
)
}
@@ -0,0 +1,31 @@
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import { useT } from '@/i18n/useT'
export interface DisclaimerDialogProps {
text: string
onAcknowledge: () => void
}
/** Scope disclaimer of the sheet, shown once per tab session. */
export default function DisclaimerDialog({
text,
onAcknowledge,
}: DisclaimerDialogProps) {
const t = useT()
return (
<Dialog
open
onClose={onAcknowledge}
title={t('editor.disclaimer_title')}
size="md"
>
<div className="space-y-4">
<p className="text-sm text-[var(--color-ink)]">{text}</p>
<div className="flex justify-end">
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
</div>
</div>
</Dialog>
)
}
@@ -0,0 +1,71 @@
import type { ComponentProps } from 'react'
import type { Animal, Owner, Practitioner } from '@faunosteo/domain'
import Button from '@/components/ui/Button'
import Dialog from '@/components/ui/Dialog'
import PractitionerForm from '@/components/report/PractitionerForm'
import AnimalForm from '@/components/report/AnimalForm'
import { useT } from '@/i18n/useT'
export interface Identity {
practitioner: Practitioner
animal: Animal
owner: Owner
}
export interface EditInfosDialogProps {
draft: Identity
species: ComponentProps<typeof AnimalForm>['species']
onChange: (next: Identity) => void
onCancel: () => void
onSave: () => void
}
/** The three names are mandatory to save the identity block. */
export function isIdentityComplete(identity: Identity): boolean {
return [
identity.practitioner.name,
identity.animal.name,
identity.owner.name,
].every((v) => v.trim())
}
/** Identity edit dialog of the editor: practitioner, animal and owner. */
export default function EditInfosDialog({
draft,
species,
onChange,
onCancel,
onSave,
}: EditInfosDialogProps) {
const t = useT()
return (
<Dialog
open
onClose={onCancel}
title={t('editor.edit_dialog_title')}
size="lg"
>
<div className="space-y-8">
<PractitionerForm
value={draft.practitioner}
onChange={(next) => onChange({ ...draft, practitioner: next })}
/>
<AnimalForm
animal={draft.animal}
owner={draft.owner}
species={species}
onChangeAnimal={(next) => onChange({ ...draft, animal: next })}
onChangeOwner={(next) => onChange({ ...draft, owner: next })}
/>
<div className="flex gap-3 justify-end pt-2 border-t border-[var(--color-border)]">
<Button variant="ghost" onClick={onCancel}>
{t('common.cancel')}
</Button>
<Button onClick={onSave} disabled={!isIdentityComplete(draft)}>
{t('common.save')}
</Button>
</div>
</div>
</Dialog>
)
}
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report'
import type { Report } from '@faunosteo/domain'
import Input from '@/components/ui/Input'
import Label from '@/components/ui/Label'
import { useT } from '@/i18n/useT'
@@ -1,4 +1,4 @@
import type { Practitioner } from '@/domain/schema/practitioner'
import type { Practitioner } from '@faunosteo/domain'
import Label from '@/components/ui/Label'
import Input from '@/components/ui/Input'
import { useT } from '@/i18n/useT'
@@ -8,7 +8,10 @@ export interface PractitionerFormProps {
onChange: (next: Practitioner) => void
}
export default function PractitionerForm({ value, onChange }: PractitionerFormProps) {
export default function PractitionerForm({
value,
onChange,
}: PractitionerFormProps) {
const t = useT()
const set = (patch: Partial<Practitioner>) => onChange({ ...value, ...patch })
return (
@@ -18,19 +21,36 @@ export default function PractitionerForm({ value, onChange }: PractitionerFormPr
</legend>
<div>
<Label htmlFor="prac-name">{t('form.practitioner.name')}</Label>
<Input id="prac-name" required value={value.name} onChange={(e) => set({ name: e.target.value })} />
<Input
id="prac-name"
required
value={value.name}
onChange={(e) => set({ name: e.target.value })}
/>
</div>
<div>
<Label htmlFor="prac-cabinet">{t('form.practitioner.cabinet')}</Label>
<Input id="prac-cabinet" value={value.cabinet ?? ''} onChange={(e) => set({ cabinet: e.target.value || undefined })} />
<Input
id="prac-cabinet"
value={value.cabinet ?? ''}
onChange={(e) => set({ cabinet: e.target.value || undefined })}
/>
</div>
<div>
<Label htmlFor="prac-contact">{t('form.practitioner.contact')}</Label>
<Input id="prac-contact" value={value.contact ?? ''} onChange={(e) => set({ contact: e.target.value || undefined })} />
<Input
id="prac-contact"
value={value.contact ?? ''}
onChange={(e) => set({ contact: e.target.value || undefined })}
/>
</div>
<div>
<Label htmlFor="prac-siret">{t('form.practitioner.siret')}</Label>
<Input id="prac-siret" value={value.siret ?? ''} onChange={(e) => set({ siret: e.target.value || undefined })} />
<Input
id="prac-siret"
value={value.siret ?? ''}
onChange={(e) => set({ siret: e.target.value || undefined })}
/>
</div>
</fieldset>
)
@@ -1,4 +1,4 @@
import type { Report } from '@/domain/schema/report'
import type { Report } from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader'
import Button from '@/components/ui/Button'
import { formatDate } from '@/lib/dates'
@@ -10,7 +10,10 @@ export interface ReportHeaderProps {
onEditInfos?: () => void
}
export default function ReportHeader({ report, onEditInfos }: ReportHeaderProps) {
export default function ReportHeader({
report,
onEditInfos,
}: ReportHeaderProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return (
File renamed without changes.
File renamed without changes.
@@ -6,7 +6,11 @@ export interface CardProps {
as?: 'div' | 'section' | 'article'
}
export default function Card({ children, className = '', as: Tag = 'div' }: CardProps) {
export default function Card({
children,
className = '',
as: Tag = 'div',
}: CardProps) {
return (
<Tag
className={[
@@ -5,7 +5,10 @@ export default function Chip({
children,
className = '',
...rest
}: ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean; children: ReactNode }) {
}: ButtonHTMLAttributes<HTMLButtonElement> & {
active?: boolean
children: ReactNode
}) {
return (
<button
type="button"
@@ -1,5 +1,6 @@
import { useEffect, type ReactNode } from 'react'
import { AnimatePresence, motion } from 'motion/react'
import { useT } from '@/i18n/useT'
export interface DialogProps {
open: boolean
@@ -16,7 +17,14 @@ const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
xl: 'max-w-4xl',
}
export default function Dialog({ open, onClose, title, children, size = 'md' }: DialogProps) {
export default function Dialog({
open,
onClose,
title,
children,
size = 'md',
}: DialogProps) {
const t = useT()
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
@@ -48,10 +56,12 @@ export default function Dialog({ open, onClose, title, children, size = 'md' }:
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
>
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
<h2 className="text-lg font-semibold text-[var(--color-ink)]">{title}</h2>
<h2 className="text-lg font-semibold text-[var(--color-ink)]">
{title}
</h2>
<button
type="button"
aria-label="Fermer"
aria-label={t('common.close')}
onClick={onClose}
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
>
+17
View File
@@ -0,0 +1,17 @@
import { forwardRef, type InputHTMLAttributes } from 'react'
const Input = forwardRef<
HTMLInputElement,
InputHTMLAttributes<HTMLInputElement>
>(({ className = '', ...rest }, ref) => (
<input
ref={ref}
className={[
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
className,
].join(' ')}
{...rest}
/>
))
Input.displayName = 'Input'
export default Input
File renamed without changes.
+19
View File
@@ -0,0 +1,19 @@
import { forwardRef, type SelectHTMLAttributes } from 'react'
const Select = forwardRef<
HTMLSelectElement,
SelectHTMLAttributes<HTMLSelectElement>
>(({ className = '', children, ...rest }, ref) => (
<select
ref={ref}
className={[
'h-10 w-full rounded-lg border border-[var(--color-border)] bg-white px-3 text-base text-[var(--color-ink)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
className,
].join(' ')}
{...rest}
>
{children}
</select>
))
Select.displayName = 'Select'
export default Select
+17
View File
@@ -0,0 +1,17 @@
import { forwardRef, type TextareaHTMLAttributes } from 'react'
const Textarea = forwardRef<
HTMLTextAreaElement,
TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className = '', ...rest }, ref) => (
<textarea
ref={ref}
className={[
'w-full min-h-[96px] rounded-lg border border-[var(--color-border)] bg-white p-3 text-base text-[var(--color-ink)] placeholder:text-[var(--color-ink-muted)] focus-visible:border-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]/30',
className,
].join(' ')}
{...rest}
/>
))
Textarea.displayName = 'Textarea'
export default Textarea
+89
View File
@@ -0,0 +1,89 @@
/// <reference types="vite/client" />
import type { SupabaseConnection } from '@faunosteo/supabase'
/**
* Runtime application config.
* Resolution order:
* 1. window.__APP_CONFIG__ (injected by docker/entrypoint.sh)
* 2. import.meta.env.VITE_* (build-time Vite defines)
* 3. Hard-coded defaults
*/
export interface AppConfig {
siteName: string
brandName: string
footerName: string
tagline: string
/** null = no backend configured; the app keeps its local-only behaviour. */
supabase: SupabaseConnection | null
}
/** Shape written by docker/entrypoint.sh (flat strings, empty = unset). */
export interface RuntimeConfig {
siteName?: string
brandName?: string
footerName?: string
tagline?: string
supabaseUrl?: string
supabaseAnonKey?: string
}
declare global {
interface Window {
__APP_CONFIG__?: RuntimeConfig
}
}
const DEFAULTS: Omit<AppConfig, 'supabase'> = {
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
tagline: 'Outils pour ostéopathes animaliers',
}
/** Empty strings from env.js or Vite count as "not set". */
function nonEmpty(value: string | undefined): string | undefined {
return value && value.trim() !== '' ? value : undefined
}
/** Both settings are required; one without the other is a misconfiguration. */
export function resolveSupabaseConnection(
url: string | undefined,
anonKey: string | undefined,
): SupabaseConnection | null {
const cleanUrl = nonEmpty(url)
const cleanKey = nonEmpty(anonKey)
if (cleanUrl && cleanKey) return { url: cleanUrl, anonKey: cleanKey }
if ((cleanUrl || cleanKey) && import.meta.env.DEV) {
console.warn(
'[config] supabaseUrl and supabaseAnonKey must be set together; Supabase disabled',
)
}
return null
}
export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
return {
siteName:
runtime.siteName ??
import.meta.env.VITE_APP_SITE_NAME ??
DEFAULTS.siteName,
brandName:
runtime.brandName ??
import.meta.env.VITE_APP_BRAND_NAME ??
DEFAULTS.brandName,
footerName:
runtime.footerName ??
import.meta.env.VITE_APP_FOOTER_NAME ??
DEFAULTS.footerName,
tagline:
runtime.tagline ?? import.meta.env.VITE_APP_TAGLINE ?? DEFAULTS.tagline,
supabase: resolveSupabaseConnection(
runtime.supabaseUrl ?? import.meta.env.VITE_SUPABASE_URL,
runtime.supabaseAnonKey ?? import.meta.env.VITE_SUPABASE_ANON_KEY,
),
}
}
export const appConfig: AppConfig = resolveConfig(
typeof window !== 'undefined' ? window.__APP_CONFIG__ : undefined,
)
+180
View File
@@ -0,0 +1,180 @@
import type { Dict } from './types'
export const en: Dict = {
'common.cancel': 'Cancel',
'common.close': 'Close',
'common.save': 'Save',
'common.confirm': 'Confirm',
'common.delete': 'Delete',
'common.add': 'Add',
'common.home': 'Home',
'common.understood': 'Got it',
'common.collapse': 'Collapse',
'common.expand': 'Expand',
'common.move_up': 'Move up',
'common.move_down': 'Move down',
'common.back_to_home': 'Back to home',
'home.new_report.title': 'New report',
'home.new_report.description':
'Start a new osteopathic report for an animal.',
'home.new_report.cta': 'Start',
'home.import.title': 'Import a PDF',
'home.import.description':
'Reopen a previous report generated by this app to follow up.',
'home.import.cta': 'Choose a PDF',
'home.import.loading': 'Reading…',
'home.import.error_generic': 'Failed to read the PDF.',
'home.import.error_invalid_pdf': 'This file is not a readable PDF.',
'home.import.error_no_attachment':
'This PDF was not generated by Faunosteo (no data detected).',
'home.import.error_incompatible_version':
'This PDF uses format v{version}, which this version of the application cannot read (accepted formats: v2 and v3).',
'home.import.complete': 'Full restoration.',
'home.import.degraded':
'Partial recovery: check the items flagged below.',
'home.import.migrated':
'Report imported from an older format. Findings not found in the current sheet: {count} (kept with their labels).',
'home.import.archive_ok':
'Faunosteo archive imported: report and the original sheet snapshot kept.',
'home.import.snapshot_rejected':
'Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is.',
'home.import.snapshot_reason.unsupported_envelope':
'archive from a newer version',
'home.import.snapshot_reason.schema': 'invalid content',
'home.import.snapshot_reason.caps': 'size or complexity over the limits',
'home.import.snapshot_reason.integrity': 'inconsistent sheet',
'home.import.snapshot_reason.sheet_mismatch':
"sheet differs from the report's",
'home.import.rebased':
"Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels).",
'home.import.error_attachment_stripped':
'This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file.',
'home.no_sheet.title': 'No anatomical sheet',
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
// footer
'footer.all_rights_reserved': 'All rights reserved.',
'footer.powered_by': 'Powered by',
'footer.in_partnership': 'In partnership with',
'not_found.title': 'Page not found',
'not_found.description': 'The requested path does not exist.',
'new_report.title': 'New report',
'new_report.date_label': 'Report date',
'new_report.submit': 'Start the report',
'editor.export': 'Export as PDF',
'editor.exporting': 'Generating…',
'editor.export_failed': 'PDF generation failed. Retry or contact support.',
'editor.export_warnings':
'PDF exported with missing elements: {items}. Check the browser console.',
'editor.draft_rebased':
'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).',
'editor.edit_infos': 'Edit info',
'editor.edit_dialog_title': 'Edit information',
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
'detail.click_to_add':
'Click the zones to add them to the current observation.',
'observation.section_title': 'Observations',
'observation.add': '+ New observation',
'observation.empty':
'No observation. Click "+ New observation" then on the zones in the diagram.',
'observation.badge_n': 'Observation #',
'observation.zone_label_singular': 'zone',
'observation.zone_label_plural': 'zones',
'observation.finding_label_singular': 'finding',
'observation.finding_label_plural': 'findings',
'observation.zones_label': 'Selected zones',
'observation.zones_empty':
'Click on the zones in the diagram to add them to this observation.',
'observation.findings_catalog_label': 'Findings (catalog)',
'observation.findings_pick_zone_first': 'Pick a zone to access the catalog.',
'observation.findings_no_catalog':
'No catalog available for these zones. Use the free text below.',
'observation.findings_free_label': 'Findings (free text)',
'observation.free_placeholder': 'Additional observation (free text)',
'observation.free_aria': 'Free observation',
'observation.severity_label': 'Severity',
'observation.comment_label': 'Comment',
'observation.comment_placeholder': 'Detailed clinical notes…',
'observation.vertebrae_button': 'Vertebrae…',
'observation.vertebrae_button_title': 'Specify vertebrae for this zone',
'observation.remove_zone': 'Remove',
'observation.expand_aria': 'Expand observation',
'observation.collapse_aria': 'Collapse observation',
'findings.back_to_parent': 'Back to previous level',
'findings.back': '← Back',
'findings.no_options': 'No option available at this level.',
'findings.open': 'Open',
'findings.vet_referral': 'Refer to a veterinarian',
'findings.selected_singular': 'finding selected',
'findings.selected_plural': 'findings selected',
'form.practitioner.legend': 'Practitioner',
'form.practitioner.name': 'Full name *',
'form.practitioner.cabinet': 'Practice / clinic',
'form.practitioner.contact': 'Contact (phone, email…)',
'form.practitioner.siret': 'SIRET',
'form.animal.legend': 'Animal & owner',
'form.animal.species': 'Species *',
'form.animal.name': 'Animal name *',
'form.animal.breed': 'Breed',
'form.animal.age': 'Age',
'form.owner.name': 'Owner name *',
'conclusion.section_title': 'Conclusion & recommendations',
'conclusion.conclusion': 'Conclusion',
'conclusion.recommendations': 'Recommendations',
'conclusion.next_appointment': 'Next appointment',
'conclusion.next_kind_date': 'Date',
'conclusion.next_kind_period': 'Free period',
'conclusion.next_kind_none': 'None',
'conclusion.next_period_placeholder': 'e.g. in 3 weeks',
'vertebra.title_prefix': 'Specify vertebrae — ',
'vertebra.check_all': 'Select all',
'vertebra.uncheck_all': 'Clear all',
'vertebra.extend_to': 'Show up to {max}',
'vertebra.range_note':
'Usual count: {usual}; documented variation: {min} to {max}.',
// sheet
'sheet.status.draft':
'Anatomical sheet: reference draft, not medically validated',
'sheet.status.published': 'Official anatomical sheet',
'sheet.loading': 'Loading the anatomical sheet…',
// unresolved (migrated) data
'observation.unresolved_short': 'inherited',
'observation.zone_unresolved':
'Zone inherited from an older report, absent from the current sheet',
'observation.findings_unresolved_label':
'Inherited findings (outside the current catalog)',
'observation.findings_unresolved_help':
'Findings imported from an older report whose path no longer exists in the sheet: kept with their original labels.',
// laterality
'lateral.which_side': 'Which side?',
'lateral.left': 'Left',
'lateral.right': 'Right',
'lateral.both': 'Both',
'lateral.left_short': 'L',
'lateral.right_short': 'R',
'severity.aria': 'Severity',
'severity.mild': 'mild',
'severity.moderate': 'moderate',
'severity.severe': 'severe',
'lang.group_label': 'Language',
'lang.switch_to_fr': 'Passer en français',
'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR',
'lang.en': 'EN',
}
+196
View File
@@ -0,0 +1,196 @@
import type { Dict } from './types'
export const fr: Dict = {
// common
'common.cancel': 'Annuler',
'common.close': 'Fermer',
'common.save': 'Enregistrer',
'common.confirm': 'Valider',
'common.delete': 'Supprimer',
'common.add': 'Ajouter',
'common.home': 'Accueil',
'common.understood': 'Compris',
'common.collapse': 'Réduire',
'common.expand': 'Développer',
'common.move_up': 'Monter',
'common.move_down': 'Descendre',
'common.back_to_home': "Retour à l'accueil",
// home
'home.new_report.title': 'Nouveau bilan',
'home.new_report.description':
"Démarrer un nouveau bilan d'ostéopathie sur un animal.",
'home.new_report.cta': 'Commencer',
'home.import.title': 'Importer un PDF',
'home.import.description':
'Reprendre un bilan précédent généré par cette application pour effectuer un suivi.',
'home.import.cta': 'Choisir un PDF',
'home.import.loading': 'Lecture…',
'home.import.error_generic': 'Erreur de lecture du PDF.',
'home.import.error_invalid_pdf': "Ce fichier n'est pas un PDF lisible.",
'home.import.error_no_attachment':
"Ce PDF n'a pas été généré par Faunosteo (pas de données détectées).",
'home.import.error_incompatible_version':
"Ce PDF est au format v{version}, que cette version de l'application ne sait pas lire (formats acceptés : v2 et v3).",
'home.import.complete': 'Restauration complète.',
'home.import.degraded':
'Récupération partielle : vérifiez les éléments signalés.',
'home.import.migrated':
'Bilan importé depuis un ancien format. Constats non retrouvés dans la fiche actuelle : {count} (conservés avec leurs libellés).',
'home.import.archive_ok':
"Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés.",
'home.import.snapshot_rejected':
"Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle.",
'home.import.snapshot_reason.unsupported_envelope':
"archive d'une version plus récente",
'home.import.snapshot_reason.schema': 'contenu invalide',
'home.import.snapshot_reason.caps': 'taille ou complexité excessive',
'home.import.snapshot_reason.integrity': 'fiche incohérente',
'home.import.snapshot_reason.sheet_mismatch':
'fiche différente de celle du bilan',
'home.import.rebased':
"Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés).",
'home.import.error_attachment_stripped':
"Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine.",
'home.no_sheet.title': 'Aucune fiche anatomique',
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
// footer
'footer.all_rights_reserved': 'Tous droits réservés.',
'footer.powered_by': 'Propulsé par',
'footer.in_partnership': 'En partenariat avec',
// not found
'not_found.title': 'Page introuvable',
'not_found.description': "Le chemin demandé n'existe pas.",
// new report
'new_report.title': 'Nouveau bilan',
'new_report.date_label': 'Date du bilan',
'new_report.submit': 'Démarrer le bilan',
// editor
'editor.export': 'Exporter en PDF',
'editor.exporting': 'Génération…',
'editor.export_failed':
'Échec de la génération du PDF. Réessayez ou contactez le support.',
'editor.export_warnings':
'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.',
'editor.draft_rebased':
'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).',
'editor.edit_infos': 'Modifier les infos',
'editor.edit_dialog_title': 'Modifier les informations',
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
// detail modal
'detail.click_to_add':
"Cliquez sur les zones pour les ajouter à l'observation en cours.",
// observation list / card
'observation.section_title': 'Observations',
'observation.add': '+ Nouvelle observation',
'observation.empty':
'Aucune observation. Cliquez sur "+ Nouvelle observation" puis sur les zones du schéma.',
'observation.badge_n': 'Observation #',
'observation.zone_label_singular': 'zone',
'observation.zone_label_plural': 'zones',
'observation.finding_label_singular': 'constat',
'observation.finding_label_plural': 'constats',
'observation.zones_label': 'Zones sélectionnées',
'observation.zones_empty':
'Cliquez sur les zones du schéma pour les ajouter à cette observation.',
'observation.findings_catalog_label': 'Constats (référentiel)',
'observation.findings_pick_zone_first':
'Sélectionnez une zone pour accéder au référentiel.',
'observation.findings_no_catalog':
'Aucun référentiel disponible pour ces zones. Utilisez le texte libre ci-dessous.',
'observation.findings_free_label': 'Constats (texte libre)',
'observation.free_placeholder': 'Observation additionnelle (texte libre)',
'observation.free_aria': 'Observation libre',
'observation.severity_label': 'Sévérité',
'observation.comment_label': 'Commentaire',
'observation.comment_placeholder': 'Notes cliniques détaillées…',
'observation.vertebrae_button': 'Vertèbres…',
'observation.vertebrae_button_title':
'Préciser les vertèbres pour cette zone',
'observation.remove_zone': 'Retirer',
'observation.expand_aria': "Développer l'observation",
'observation.collapse_aria': "Réduire l'observation",
// findings tree picker
'findings.back_to_parent': 'Retour au niveau précédent',
'findings.back': '← Retour',
'findings.no_options': 'Aucune option disponible à ce niveau.',
'findings.open': 'Ouvrir',
'findings.vet_referral': 'Référer au vétérinaire',
'findings.selected_singular': 'constat sélectionné',
'findings.selected_plural': 'constats sélectionnés',
// forms
'form.practitioner.legend': 'Praticien',
'form.practitioner.name': 'Nom complet *',
'form.practitioner.cabinet': 'Cabinet / clinique',
'form.practitioner.contact': 'Contact (téléphone, email…)',
'form.practitioner.siret': 'SIRET',
'form.animal.legend': 'Animal & propriétaire',
'form.animal.species': 'Espèce *',
'form.animal.name': "Nom de l'animal *",
'form.animal.breed': 'Race',
'form.animal.age': 'Âge',
'form.owner.name': 'Nom du propriétaire *',
// conclusion panel
'conclusion.section_title': 'Conclusion & recommandations',
'conclusion.conclusion': 'Conclusion',
'conclusion.recommendations': 'Recommandations',
'conclusion.next_appointment': 'Prochain rendez-vous',
'conclusion.next_kind_date': 'Date',
'conclusion.next_kind_period': 'Période libre',
'conclusion.next_kind_none': 'Aucun',
'conclusion.next_period_placeholder': 'ex. dans 3 semaines',
// vertebra picker
'vertebra.title_prefix': 'Préciser les vertèbres — ',
'vertebra.check_all': 'Tout cocher',
'vertebra.uncheck_all': 'Tout décocher',
'vertebra.extend_to': "Afficher jusqu'à {max}",
'vertebra.range_note':
'Nombre usuel : {usual} ; variation documentée : {min} à {max}.',
// sheet
'sheet.status.draft':
'Fiche anatomique : brouillon de référence, non validé médicalement',
'sheet.status.published': 'Fiche anatomique officielle',
'sheet.loading': 'Chargement de la fiche anatomique…',
// unresolved (migrated) data
'observation.unresolved_short': 'hérité',
'observation.zone_unresolved':
"Zone héritée d'un ancien bilan, absente de la fiche actuelle",
'observation.findings_unresolved_label':
'Constats hérités (hors référentiel actuel)',
'observation.findings_unresolved_help':
"Constats importés d'un ancien bilan dont le chemin n'existe plus dans la fiche : conservés avec leurs libellés d'origine.",
// laterality
'lateral.which_side': 'Quel côté ?',
'lateral.left': 'Gauche',
'lateral.right': 'Droite',
'lateral.both': 'Les deux',
'lateral.left_short': 'G',
'lateral.right_short': 'D',
// severity
'severity.aria': 'Sévérité',
'severity.mild': 'légère',
'severity.moderate': 'modérée',
'severity.severe': 'sévère',
// language switcher
'lang.group_label': 'Langue',
'lang.switch_to_fr': 'Passer en français',
'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR',
'lang.en': 'EN',
}
File renamed without changes.
+16
View File
@@ -0,0 +1,16 @@
import type { Locale } from './types'
/**
* Resolves a bilingual label for the active locale. Falls back to the
* opposite language when the preferred one is missing/empty, then to the
* provided fallback, so callers never render an empty string.
*/
export function pickLocaleLabel(
fr: string | undefined,
en: string | undefined,
locale: Locale,
fallback = '',
): string {
if (locale === 'en') return en || fr || fallback
return fr || en || fallback
}
File renamed without changes.
File renamed without changes.
@@ -7,11 +7,3 @@ export function assert(condition: unknown, message: string): asserts condition {
throw new Error(`Assertion failed: ${message}`)
}
}
/**
* Marks a code path as unreachable for exhaustive switch coverage.
* TypeScript will error at compile time if the path is reachable.
*/
export function assertNever(value: never, message?: string): never {
throw new Error(message ?? `Unexpected value: ${JSON.stringify(value)}`)
}
@@ -18,7 +18,8 @@ export function formatDate(isoDate: string, locale: Locale): string {
if (!match) throw new Error(`Invalid ISO date: ${isoDate}`)
const [, y, mo, d] = match
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)))
if (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date: ${isoDate}`)
if (Number.isNaN(date.getTime()))
throw new Error(`Invalid ISO date: ${isoDate}`)
return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
day: 'numeric',
month: 'long',
File renamed without changes.
+27
View File
@@ -0,0 +1,27 @@
import { createBrowserClient, type FaunosteoClient } from '@faunosteo/supabase'
import { appConfig, type AppConfig } from '@/config/env'
let cached: { connectionUrl: string; client: FaunosteoClient } | null = null
/**
* Lazily created Supabase client, or null when the deployment has no backend
* configured. Callers must handle null: the current local-only flows do not
* depend on Supabase. No UI uses this yet (foundation step).
*/
export function getSupabaseClient(
config: AppConfig = appConfig,
): FaunosteoClient | null {
if (!config.supabase) return null
if (cached?.connectionUrl !== config.supabase.url) {
cached = {
connectionUrl: config.supabase.url,
client: createBrowserClient(config.supabase),
}
}
return cached.client
}
/** True when the app can talk to Supabase. */
export function isSupabaseConfigured(config: AppConfig = appConfig): boolean {
return config.supabase !== null
}
File renamed without changes.
+44
View File
@@ -0,0 +1,44 @@
import type { Branding, ImageAsset } from '@faunosteo/domain'
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
import partnerLogoSvg from '@/assets/brand/paws-in-harmony.svg?raw'
/**
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
* the four logo files bundled with the application (`src/assets/brand`), so
* an export needs no network and no deployed file, plus the credit URLs. The
* result travels inside the archive, so a re-export never needs them again.
*/
// shortcut: the site URL and the credit constants belong to the runtime
// config (ConfigProvider); they live here until AppConfig carries them.
const SITE_URL = 'https://faunosteo.com'
const POWERED_BY = {
url: 'https://zenquality.fr',
fallbackText: 'zenquality.fr',
}
const PARTNER = {
url: 'https://www.instagram.com/paws.iin.harmony',
fallbackText: '@paws.iin.harmony',
}
const PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
/** A `?inline` PNG import is a base64 data URL; the engine wants the base64 alone. */
function pngAsset(dataUrl: string): ImageAsset {
if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
throw new Error('bundled logo is not a base64 PNG data URL')
}
return { kind: 'png', base64: dataUrl.slice(PNG_DATA_URL_PREFIX.length) }
}
export async function loadBranding(): Promise<Branding> {
return {
siteUrl: SITE_URL,
headerLogo: pngAsset(headerLogoDataUrl),
footerLogo: pngAsset(footerLogoDataUrl),
poweredBy: { logo: pngAsset(poweredByLogoDataUrl), ...POWERED_BY },
partner: { logo: { kind: 'svg', svg: partnerLogoSvg }, ...PARTNER },
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { Rasterizer } from '@faunosteo/pdf'
/**
* The browser side of the engine's rasterizer adapter: the engine has fixed
* the pixel size, this module only stamps it on the SVG root and lets the
* browser draw the SVG through an Image / canvas pair, which renders exactly
* what the practitioner sees in the inline anatomy canvas.
*/
const SVG_NS = 'http://www.w3.org/2000/svg'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
function startsWithPngSignature(bytes: Uint8Array): boolean {
if (bytes.length < PNG_SIGNATURE.length) return false
return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte)
}
/** The root carries the namespace and the engine's size; nothing else changes. */
function sizedSvg(svg: string, widthPx: number, heightPx: number): string {
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
).documentElement
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
root.setAttribute('width', String(widthPx))
root.setAttribute('height', String(heightPx))
return new XMLSerializer().serializeToString(root)
}
function loadImage(svg: string): Promise<HTMLImageElement> {
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const img = new Image()
img.decoding = 'sync'
img.crossOrigin = 'anonymous'
return new Promise<HTMLImageElement>((resolve, reject) => {
img.onload = () => resolve(img)
img.onerror = () =>
reject(new Error('Browser failed to render the SVG into an Image'))
img.src = url
}).finally(() => URL.revokeObjectURL(url))
}
function drawOnWhiteCanvas(
img: HTMLImageElement,
widthPx: number,
heightPx: number,
): HTMLCanvasElement {
const canvas = document.createElement('canvas')
canvas.width = widthPx
canvas.height = heightPx
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Canvas 2D context unavailable')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, widthPx, heightPx)
ctx.drawImage(img, 0, 0, widthPx, heightPx)
return canvas
}
function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
}
/** Fallback when toBlob yields nothing: decode the data URL by hand. */
function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array {
const dataUrl = canvas.toDataURL('image/png')
if (!dataUrl.startsWith('data:image/png')) {
throw new Error(
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
)
}
const comma = dataUrl.indexOf(',')
if (comma < 0) {
throw new Error('canvas.toDataURL returned a data URL without a payload')
}
const binary = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
if (!startsWithPngSignature(bytes)) {
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
}
return bytes
}
async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {
const blob = await canvasBlob(canvas)
if (blob) {
const bytes = new Uint8Array(await blob.arrayBuffer())
if (startsWithPngSignature(bytes)) return bytes
}
return pngFromDataUrl(canvas)
}
export const browserRasterizer: Rasterizer = async (
svg,
{ widthPx, heightPx },
) => {
const img = await loadImage(sizedSvg(svg, widthPx, heightPx))
return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx))
}
+46
View File
@@ -0,0 +1,46 @@
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
import {
defaultPdfLabels,
exportReportArchive,
type ExportWarning,
} from '@faunosteo/pdf'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadBranding } from './branding'
import { browserRasterizer } from './browserRasterizer'
export interface PdfExportOptions {
locale: Locale
}
export interface PdfExportResult {
pdf: Uint8Array
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
warnings: ExportWarning[]
}
/**
* Exports the report as an archive PDF through the engine: the loaded sheet
* becomes the snapshot the pages are drawn from and the attachment carries,
* the branding comes from the bundled logos, the browser rasterises the
* views. Warnings are logged and returned for the caller to surface.
*/
export async function exportReportToPdf(
report: Report,
index: SheetIndex,
opts: PdfExportOptions,
): Promise<PdfExportResult> {
const result = await exportReportArchive({
report,
sheet: buildSheetSnapshot(index.sheet, report),
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
rasterizer: browserRasterizer,
exportedAt: new Date(),
})
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
}
return { pdf: result.pdf, warnings: result.warnings }
}
Loaded 100 of 554 files, more files were not shown because too many files have changed in this diff. Show more