Merge chore/p0-doc-realignment into develop
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-25 18:09:27 +01:00
commit dae74e00dc
20 files changed
+924 -108

No files matched your search

+11
View File
@@ -524,3 +524,14 @@ Decision (owner go): `check_v3_shape` on raw value before `Report::deserialize`:
## BDR-070 | 2026-10-25 | D-R5.6 active: fingerprint `sha256-rfc8785-validated-v1`, registry alias, M1 option 1
Decision (owner, activation 9e87016): sheet fingerprint = SHA-256(JCS RFC 8785 of R2 typed reading, no integrity error, warnings allowed, depth 128). Equine canonical 12d78872…74e2; old 27c7383c…2660 = sole TRUSTED_ALIASES entry, bound to sheet 503dc301 + content. Alias honoured only via LoadedSheet::recognises_historical_stamp (loader-verified v1 private state + document recomputed at decision + one-way registry pair + same sheet id); equivalence pub(crate). M1 option 1: snapshot of old report keeps its stamp (build_sheet_snapshot); export, archive reader strict. v0 refs (no block) load unverified, no privilege; null/malformed block refused. Rust = sole seed writer, TS legacy until R5.7. Alternatives rejected: A file-bytes (Prettier-bound), C Prettier reproduction; re-stamp at rebase (rewrites reports); export-side alias (M1 defect, no proof). Status: active on feature branch; rollback not transparent for post-switch reports (rebased, nothing lost) → settle before user release.
## BDR-071 | 2026-10-25 | Product roadmap principle validated: P0 → V1-1 → V1-2 → V1-3 → V1-4 → V1-5
Decision (owner, brief « P0 : arbitrages documentaires et finalisation du contrat V1-1 »): order P0 docs → V1-1 clients + animals → V1-2 sheets from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 mobile + a11y pass; a11y + security apply at every step (IMPLEMENTATION_PLAN §0). Release readiness track RR-1..RR-10 stays separate: no V1 step authorises release or public exposure. C4 (records owned by workspace, no global client directory), C5 (writes = workspace members with write right), C6 (email confirmation ≠ pro verification) = owner orientations, awaiting business ratification. V1-1 orientations D1-D9, D16 recorded as proposals in `V1-1_OWNERS_ANIMALS.md` §9.1; no table, RPC, RLS or component before ratification. Owner also confirmed: anatomical reference changes only via curation sources + Rust pipeline until Step 17, no graphic sheet editor, equine draft unpublished until business review, no auto publication; bilan annotations ≠ reference changes.
Alt: plan's numeric step order (verification, cabinets, entitlements before any client screen).
Status: principle active; C4/C5/C6 + V1-1 orientations pending ratification; P0 merge awaits owner go.
## BDR-072 | 2026-10-25 | Correction of BDR-041: professional verification = plan Step 9, not Step 11
BDR-041 point (2) names Professional Verification "Step 11"; IMPLEMENTATION_PLAN numbers it Step 9 (Step 10 cabinets, Step 11 entitlement skeleton). Plan numbering kept. BDR-041 left as written (append-only); this entry supersedes its step number only, rest of BDR-041 unchanged. Docs cite Step 9: plan Step 7 note, V1-1 contract §5.2, OPEN_QUESTIONS C6.
Status: active.
+6
View File
@@ -241,3 +241,9 @@ Action: claim a guard per call site, not per design; owner decision on snapshot_
Method: ledger 407 TS cases case by case before `git rm`; fresh verifier + security (opus) twice; check:all on R5.7 state, then rerun on 27bf59c after post-check edits; verifier ran 14 scratch reintroduction probes against census.
Anomalies: round 1 verifier ECARTS(2): contract C6 "tsx gone" false vs pnpm optional peer (owner Clarification), digest typo `…dfe7` in docs. Two edits landed after first check:all → owner required full rerun. Census regex accepted `#[ignore]` targets (fixed) and still accepts ignore-before-test (LOW). Docs pointed to premerge record before it existed; `.bin/tsx` wording root-only; SUPABASE.md layout stale since R2. `pnpm audit` never run before this round (cargo advisories only): 57 pre-existing.
Action: LRN-078, LRN-079; rerun gate after any post-check edit; run `pnpm audit` in every pre-merge round; checkpoint to owner, STOP before merge.
## EVAL-034 | 2026-10-25 | Functional inventory put form validation in Rust, against D-R7
Method: P0 doc census + V1-1 contract drafting; inventory `.claude/audits/2026-10-25-functional-inventory.md` cross-checked with RUST_ARCHITECTURE_REVIEW Annex A.
Anomaly: inventory criterion 4 placed validation rules (formats, lengths, required fields) in `crates/core` behind wasm facade. D-R7: form constraints stay TypeScript (Zod, i18n keys), SQL CHECK = integrity boundary, constants module + PGlite parity test against `pg_constraint`. Contradiction caught and corrected before V1-1 implementation contract; no code written on it.
Action: V1-1 contract §1 + §8.3 follow D-R7. Check every proposal against Annex A D-R rows before writing it.
+8
View File
@@ -388,3 +388,11 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp
## 2026-10-25 (product survey)
- Owner closed R0-R5, asked read-only functional survey + roadmap. 4 parallel analyzers. Inventory `.claude/audits/2026-10-25-functional-inventory.md`; release readiness track RR-1..RR-10 in TODO.
- Finding: local tool and /app not linked; no client/animal/report tables; plan text drifted (step numbers, Node worker, Step 13 "published"). Proposed V1-1 owners + animals first, needs C4/C5/C6. STOP, no branch, no code.
## 2026-10-25 (P0 + V1-1 contract)
- Owner validated roadmap P0, V1-1..V1-5; C4/C5/C6 = hypotheses. Census agent: ~100 stale doc sites. P0 edits in working tree (plan §0 + Steps 13/15/17/19-26, BACKEND_ARCH D-R9, DOMAIN_MAP roles, OPEN_QUESTIONS status table, snapshot notices, design owners, README DEV origin). `gitflow start chore/p0-doc-realignment` refused by permission layer → uncommitted on develop.
- V1-1 contract `docs/development/V1-1_OWNERS_ANIMALS.md`: workspace model, clients + animals + link roles, RPC writes, archive only, 17 decisions. Inventory criterion 4 (validation in core) contradicted D-R7, withdrawn. STOP before migration.
## 2026-10-25 (P0 arbitration, branch chore/p0-doc-realignment)
- Owner created `chore/p0-doc-realignment` off develop by hand, P0 edits carried over; finalised on it. Owner orientations D1-D9, D16, C4-C6 into V1-1 contract as proposals (§9.1), sub-choices D4a/D6a/D6b/D7a/D9a, open D10-D15/D17. Contract fixes vs brief: no owner required on animal (was last-owner rule), birth year + optional date (was date + precision), display name sole required client field, staff access = no mechanism (was impersonation pointer).
- README split public 0.1.0 / develop / DEV-only / planned; CHANGELOG Unreleased note; DEPLOY status notice + CSP "not production-ready" markers (RR-5 keeps fixes). BDR-071, BDR-072 (BDR-041 step fix), EVAL-034. nginx `/species/` = code debt, untouched. No migration, code, manifest. STOP at checkpoint, merge on owner go.
+16 -1
View File
@@ -125,7 +125,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] 7.7 Home coexistence: "Mon espace / Se connecter" entry on the header when configured; characterisation tests T12 unchanged with default config
- [x] 7.8 tests: config, authStore (fake client), locale sync, forms, guards, shell, dashboard, account; i18n parity; pgTAP 009 (PGlite + real stack 280/280); root check + docker build green; headless e2e vs local stack 20/20 (signup via Mailpit, recovery, logout, mobile)
- [x] 7.9 docs (IDENTITY.md, SUPABASE.md, CLAUDE.md, CHANGELOG, plan note); memory BDR-041, LRN-047, EVAL-015, journal; gates: verifier ECARTS(2) → open-redirect fix + contract CHECK → CONFORME 16/16; security PASS (MEDIUM fixed, 3 LOW closed, TOTP enforcement = documented gap). User validated 2026-10-12; user action still open: `.env.example` += `APP_AUTH_PROVIDERS=` (file edit denied here)
- [ ] 7.10 follow-ups kept by the user (2026-10-12), each owned by a later step: MFA mandatory before any sensitive admin feature (has_mfa helper + enrolment UI, IDENTITY.md §4; first admin screen); professional verification distinct from the SIRET format check (Step 11); real tests of Google and Apple once the provider ids exist (config.toml env(), APP_AUTH_PROVIDERS); integration of the report tool into the signed-in /app space (Step 14 gating); mockup elements not built yet listed in docs/design/README.md (bell, avatar photo → Step 8, stat tiles, tabs, mobile tab bar)
- [ ] 7.10 follow-ups kept by the user (2026-10-12), each owned by a later step: MFA mandatory before any sensitive admin feature (has_mfa helper + enrolment UI, IDENTITY.md §4; first admin screen); professional verification distinct from the SIRET format check (Step 9, BDR-072); real tests of Google and Apple once the provider ids exist (config.toml env(), APP_AUTH_PROVIDERS); integration of the report tool into the signed-in /app space (Step 14 gating); mockup elements not built yet listed in docs/design/README.md (bell, avatar photo → Step 8, stat tiles, tabs, mobile tab bar)
- [ ] Step 8 = Rust R1 — files foundation + Supabase Storage + avatar (GO 2026-10-13: R0 validated, D1–D9 validated with D1 = Rust worker, D3 = top-bar avatar + name linking to Mon compte; branch feature/step-08-files-foundation, cut from the R0 tip because `gitflow finish` of R0 was refused by the harness classifier: the owner runs it). Analysis: docs/development/STEP8_FILES_ANALYSIS.md; contract-level spec written first in docs/development/STORAGE.md. Out: SVG upload (Step 13), other buckets' flows, PDF/anatomy ports, webhooks, CI/CD, VPS deploy, release 0.2.0
- [x] 8.0 analysis: facts (existing bucket + policy pattern, sanitiser, edge runtime off, CSP, deploy), design (assets table authority, server-built keys, quarantine prefix, worker `faunosteo_worker` with sharp + pdf sanitiser, storage.objects policies through assets, Storage API signing under RLS, sweeper/reconcile, backups file volume + restic, managed migration by rows), 10 security answers, scope, tests, risks, D1–D8
- [x] 8.1 migration 20261013100000_files_foundation: `asset_status`, `assets` (lease token added for stale-task refusal), 7 buckets (avatars open: 5 MiB, jpeg/png/webp; 6 closed; sheet bucket untouched), `private.can_read_avatar_object` / `can_upload_avatar_object`, storage.objects SELECT + INSERT policies, `private.object_purge_queue` + status/delete triggers (48 h final key of a deleted row, 1 h quarantine and rejected), `private.storage_ceiling()`, RPCs begin_avatar_upload / confirm_asset_upload / remove_avatar (authenticated), claim_avatar_jobs / complete_avatar_job / reject_avatar_job / mark_quarantine_purged / claim_purges / ack_purge / claim_quarantine_leftovers / expire_pending_uploads (service_role), closed error messages (P0001), explicit revokes, column grants
@@ -367,6 +367,21 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] Release 0.2.0 (branch release/0.2.0 = Steps 3–6, version.txt + package versions 0.2.0, CHANGELOG [0.2.0] 2026-10-11): deploy-trigger check done 2026-10-12 (CI = branches main/develop only, no tag trigger, no deploy job, docker job builds `faunosteo:ci` locally; hooks push only; DEPLOY.md deploy = manual on the VPS). Default 0.2.0 build carries NO sheet (SHEET_BUNDLE=none) → the live local tool must not be redeployed from main without `--build-arg SHEET_BUNDLE=draft`. Finish via /release-candidate (finish + tag span, tag push on explicit go); CHANGELOG back-merge conflict expected (Unreleased Step 7 above [0.2.0]). Awaiting the user's go.
---
## Product roadmap V1 (owner 2026-10-25 « Validation de l'inventaire et cadrage P0 / V1-1 »)
Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheets served from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 cross-cutting mobile + a11y pass (a11y and security apply at every step). C4/C5/C6 and the V1-1 orientations (owner brief « P0 : arbitrages documentaires et finalisation du contrat V1-1 ») = proposed, awaiting ratification. No migration, component, API or table before the owner ratifies the V1-1 contract; no merge into main, no release/0.2.0 change, no deploy, no Supabase DEV change; equine draft stays unpublished.
- [ ] P0 docs realignment (docs only; branch `chore/p0-doc-realignment` created by the owner off develop, the working-tree edits carried over; merge into develop on the owner's go only)
- [x] census of stale text in active docs (worker Node / Edge Functions, step numbers, roles, Step 13 "published", deleted tools, OPEN_QUESTIONS statuses)
- [x] IMPLEMENTATION_PLAN: roadmap V1 section, step statuses, D-R9 in Steps 8/15/19/21/23/24/26, Step 13 DoD draft-only, deleted tools, Step 22 D-R8
- [x] BACKEND_ARCHITECTURE §1/§5/§6/§7/§9, DOMAIN_MAP §1/§6/§7/§12/§18, design README owners, snapshot notices (FRONTEND_ARCHITECTURE, MIGRATION_STRATEGY, REPOSITORY_MIGRATION_MAP, TEST_STRATEGY), PDF_IMPORT_HARDENING step numbers, README DEV origin, CLAUDE.md roadmap line
- [x] OPEN_QUESTIONS: status per item with the deciding BDR / D-R, C4/C5/C6 owner hypotheses, real conflicts listed for arbitration
- [x] owner arbitration 2026-10-25: README separates public 0.1.0 / develop / DEV-only / planned; CHANGELOG Unreleased note (nothing deployed, 0.2.0 section on its branch); DEPLOY status notice (historical, unverified, would-break, security prerequisites) + CSP examples marked not production-ready (fixes stay RR-5); OPEN_QUESTIONS conflicts 1-4 resolved (curation-only path until Step 17 confirmed); BDR-071, BDR-072 (BDR-041 step number), EVAL-034
- [x] commit on the branch, push
- [ ] merge into develop on the owner's go
- [x] V1-1 functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` (no code); correction: inventory criterion 4 (validation in crates/core) contradicted D-R7 → form constraints TS + SQL CHECK + parity test (EVAL-034)
- [x] owner orientations D1-D9, D16, C4-C6 integrated as proposals (§9.1, SQL / permission impact marked); sub-choices D4a, D6a, D6b, D7a, D9a (§9.2); D10-D15, D17 kept open (§9.3); legal basis, client information, retention framed before public exposure (§9.4)
- [ ] owner ratification of §9.1, answers to §9.2 and D15 → first migration on a `feature/` branch
- [ ] Code debt (not P0, no change on the doc branch): `docker/nginx.conf` still has `location /species/` (public/species deleted at Step 5); remove with its own `chore/` or `bugfix/` branch
## Release readiness track (owner 2026-10-25, distinct from the functional roadmap; nothing here authorises a release or exposure)
Inventory: `.claude/audits/2026-10-25-functional-inventory.md`. Each item: treat or qualify before any release or public exposure; not fixed now unless an active critical flaw is shown.
- [ ] RR-1 npm advisories (57, pre-existing; published severity kept apart from Faunosteo exposure). Zod 3.25.76 GHSA-mrhx-c7xc-m3w5 first: Zod parses only forms, the practitioner cache and one RPC result, no collection schema found; untrusted files go through the Rust core caps (PDF 50 MiB / 16 MiB attachment, depth 64, 400k values; sessionStorage value budget). Plan zod 4 as its own chore; drop zod from core-wasm `dependencies` if only its tests use it
+7
View File
@@ -6,6 +6,13 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
Nothing in this section is released or deployed: faunosteo.com runs 0.1.0.
Everything below is on `develop` only, accumulated since 0.1.0: the SaaS
Steps 0 to 8 and the Rust migration R0 to R5 included. `release/0.2.0` (Steps
3 to 6) was cut on 2026-10-11 and never finished; its `[0.2.0]` section lives
on that branch and reaches this file only if the release is finished (TODO
RR-9).
### Removed (2026-10-25, Rust R5.7: the TypeScript pipeline and domain packages)
- `packages/anatomy` (legacy importer, curation pipeline, TypeScript renderer, `import-equine` CLI) and `packages/domain` (Zod schemas and rules) are deleted, with the TypeScript upload script `packages/supabase/scripts/upload-sheet-assets.ts` and the scripts `pnpm import:equine:legacy` and `assets:upload:legacy`. The Rust core does all of it: `pnpm import:equine` and `pnpm assets:upload` are unchanged for the user. `@xmldom/xmldom` leaves the lockfile; `tsx` is no longer a dependency of any package (pnpm keeps it only as an optional peer of vite); root Prettier stays (`pnpm format`, `db:types`).
+4
View File
@@ -46,6 +46,10 @@ importer, curation, migration map, review files, seed SQL, upload tool) into the
R5.7 deleted `packages/anatomy` and `packages/domain` (`RUST.md` §11.23, test ledger
`crates/core/tests/curation/LEDGER.tsv`).
MVP species: equine only. Open-source MIT.
Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1-2 sheets from Supabase,
V1-3 cloud bilans, V1-4 stored PDF and sharing, V1-5 mobile and accessibility pass
(`docs/development/IMPLEMENTATION_PLAN.md` §0; V1-1 contract `docs/development/V1-1_OWNERS_ANIMALS.md`:
owner orientations proposed, awaiting ratification; nothing built).
---
+70
View File
@@ -1,5 +1,56 @@
# Deploy
## Status of this guide (2026-10-25)
This guide was written for the static deployment of 0.1.0, the version
faunosteo.com runs, and is kept as that record. It is not a procedure for
`develop`: nothing authorises deploying it (release readiness track, TODO
RR-1 to RR-10). The corrections this file needs are TODO RR-5.
Historical, true for 0.1.0 and wrong for an image with a backend: the
introduction below ("no backend, no database"), "Data persistence",
"Backups", "Backend CORS", "Frontend API base URL", the rollback's "no
server-side state", and the troubleshooting entries "CORS rejected in
browser" and "volume / data unexpectedly empty".
Not verified for the current code:
- the loopback claim: `docker-compose.yml` publishes `${PORT:-8080}` on every
interface, and rootful Docker bypasses UFW;
- "First-time VPS setup", "Routine deploys" and "Rollback" build the image on
the VPS; an image from R2 on compiles the Rust core and is never built there
(see "Image deploy by digest");
- the fallback that serves `apps/app/dist/` from a plain `nginx:alpine` drops
`docker/nginx.conf` (the `env.js` no-cache rule, the `.wasm.gz` served with
`gzip_static`);
- the VPS sizing table, written before the Rust build stages.
Would break the current application if applied as written:
- the two CSP examples (Option A nginx, Option B Caddy), marked below as not
production-ready: without `'wasm-unsafe-eval'` the editor, the export and
the import cannot load the Rust core; without the Supabase origin in
`connect-src` (it falls back to `default-src 'self'`), sign-in and the
`/app` space fail unless Supabase is served from the same origin;
- a default build (`SHEET_BUNDLE=none`): no anatomical sheet, the editor
refuses to create or import a report.
Security prerequisites before deploying anything built from `develop`:
- the CSP of "WebAssembly and the CSP" with `connect-src` naming the Supabase
origin, checked on the image (`docker/csp-proof/app-image.sh`);
- the container port bound to loopback in fact, checked from outside the VPS;
- a hosting decision for Supabase (`docs/development/OPEN_QUESTIONS.md` Q2),
production SMTP with French auth email templates, captcha, OAuth ids, MFA
for platform roles (RR-3, RR-5);
- the worker's service key out of `.env`, its exposure to the `docker` group
settled (RR-4);
- images built off the VPS and pulled by digest, base images pinned (RR-6);
- the RLS and API items of RR-3 and RR-4 and the dependency advisories of
RR-1 treated or qualified.
---
Single nginx:alpine container behind a host reverse proxy that terminates
TLS. The container serves a static SPA bundle (built from `apps/app`, Node 24,
pnpm 10.13.1) from `/usr/share/nginx/html`
@@ -298,6 +349,10 @@ previous image, never a rebuild of the old engine.
## Data persistence
Historical (0.1.0, no backend): once Supabase or the worker run beside the
application, the database and the Storage objects are server-side state that
this section and the next do not cover.
There are no server-side volumes to back up:
- **In-flight session data** lives in the praticien's browser
@@ -314,6 +369,10 @@ regenerated on every build.
## Backups (cron + retention)
Historical (0.1.0): the `.env` snapshot below is the whole backup only while
the server holds no data; `docs/development/STORAGE.md` §5.2 sets the order
for a backend (database dump first, files within 48 h).
Because there is no server-side state, the backup target is the source
repository plus the `.env` file.
@@ -430,6 +489,11 @@ systemctl status certbot.timer # auto-renew preinstalled on Ubuntu
#### Security headers (Option A only)
Not production-ready (2026-10-25): the `Content-Security-Policy` line below is
the 0.1.0 header. It lacks `'wasm-unsafe-eval'` and the Supabase origin in
`connect-src`; any later image needs "WebAssembly and the CSP" below first
(correction tracked as TODO RR-5).
Add inside the `listen 443` block (under any existing `location` rules
the certbot template inserted):
@@ -460,6 +524,9 @@ the PDF preview emits data URLs.
### Option B — Caddy (auto-TLS, single file)
Not production-ready (2026-10-25): the `Content-Security-Policy` of this
Caddyfile is the 0.1.0 header, with the same gaps as Option A (TODO RR-5).
```bash
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf https://dl.cloudsmith.io/public/caddy/stable/gpg.key | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
@@ -489,6 +556,9 @@ Caddy handles TLS issuance + renewal automatically.
### Backend CORS
Historical (0.1.0): since Step 7 the browser calls the Supabase API, a
cross-origin request unless Supabase is served from the same origin.
N/A. The app has no backend and makes no cross-origin requests. The only
runtime fetches target the same origin (SVG assets, `env.js`).
+50 -15
View File
@@ -11,15 +11,52 @@ 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
optional praticien accounts + server-side persistence on the same data
contract.
---
## Versions: what is public, what is in development
| Where | What it is |
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Public, on faunosteo.com: **0.1.0** (2026-05-21) | The local tool alone, open to every praticien: a static application with no account, no backend and no central server. The exported PDF is the long-term record. |
| `develop` (not released, not deployed) | The local tool on the canonical anatomical sheet and Report v3, the PDF archive envelope, the Rust migration R0 to R5 (domain rules, SVG reader, PDF reader and writer, curation pipeline and files worker in `crates/`), and the SaaS foundations: Supabase schema under RLS, accounts, the `/app` space, the profile photo. |
| `release/0.2.0` | Cut on 2026-10-11 from plan Steps 3 to 6, never finished or deployed; its fate is TODO RR-9. |
Available only in a development environment (they need the local Supabase
stack, `pnpm db:start`, and for the photo the worker container; no production
Supabase exists and hosting is undecided, `docs/development/OPEN_QUESTIONS.md`
Q2):
- sign-up with email confirmation, sign-in, password recovery, OAuth buttons
behind configuration;
- the `/app` space: dashboard and Mon compte (personal, professional,
preferences, security sections);
- the profile photo, processed by the Rust worker;
- the curated equine sheet DRAFT in the editor, bundled only with
`SHEET_BUNDLE=draft` (`pnpm dev`, `pnpm build:preview`): not medically
validated, not published; a default build carries no sheet;
- the anatomical pipeline and archive tools (`pnpm import:equine`,
`pnpm assets:upload`, `pnpm report:compare`).
Planned, not implemented (roadmap in
`docs/development/IMPLEMENTATION_PLAN.md` §0): V1-1 clients and animals (its
contract awaits the owner's ratification), V1-2 sheets served from Supabase,
V1-3 bilans stored in the cloud with history, V1-4 stored PDFs and authorised
sharing, V1-5 mobile and accessibility pass; then professional verification,
cabinets, entitlements, agenda, public site and the rest of the plan. Nothing
on `develop` authorises a release: the release readiness track (TODO RR-1 to
RR-10) comes first.
---
## Features
The local tool as it stands on `develop`. The public 0.1.0 has the canvas,
the detail view, the vertebra picker, the findings tree, PDF export and
re-import (report v2), the bilingual UI, the configurable identity and the
practitioner cache; laterality, the footer branding, Report v3 with the v2
migration, the sheet document and the rescue copy came after it (CHANGELOG
`Unreleased`).
- **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
@@ -61,13 +98,13 @@ corepack enable
pnpm install
cp .env.example .env # edit APP_* vars if desired
pnpm dev # http://localhost:5173
pnpm dev # http://<FAUNOSTEO_DEV_HOST>:5173 (the DEV origin, never localhost)
```
Development server on the private network (the DEV origin is the machine's
LAN address, `scripts/dev-env.sh`): `pnpm db:start`, then `pnpm dev` and open
`http://<lan-address>:5173` from any device of the network; Mailpit for the
sign-up mails on `:54324` (`docs/development/ENVIRONMENTS.md`).
sign-up mails through the DEV gateway on `:54325` behind basic auth, `pnpm dev:gateway` (`docs/development/ENVIRONMENTS.md`).
Rust (core, browser module, worker): a user-level `rustup` installs the
pinned toolchain from `rust-toolchain.toml` on first use; see
@@ -114,7 +151,7 @@ docker build -t faunosteo . # multi-stage Docker image
docker compose up --build # run with env_file: .env
```
For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy, backups, hardening) — see [DEPLOY.md](DEPLOY.md).
For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy, backups, hardening) — see [DEPLOY.md](DEPLOY.md). It describes the static 0.1.0 deployment; read its status notice before deploying anything built from `develop`.
---
@@ -128,9 +165,10 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
- [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)
- [docs/development/IMPLEMENTATION_PLAN.md](docs/development/IMPLEMENTATION_PLAN.md) — SaaS plan; §0 holds the product roadmap and where each step stands
- [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening), written for the static 0.1.0
- [CHANGELOG.md](CHANGELOG.md) — versioned release notes
- [.claude/tasks/TODO.md](.claude/tasks/TODO.md) — implementation roadmap
- [.claude/tasks/TODO.md](.claude/tasks/TODO.md) — task list and release readiness track
---
@@ -165,12 +203,9 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
## Status
v0.1.0 MVP — implementation complete.
- `pnpm typecheck` ✅
- `pnpm lint` ✅
- `pnpm test:run` ✅ — the vitest suites of the workspace (core-wasm, supabase, app); `pnpm rust:check` runs the Rust ones
- `pnpm build` ✅
Public: 0.1.0 (2026-05-21), the local tool with no backend. `develop`: plan
Steps 0 to 8 and the Rust migration R0 to R5, merged, not released. The merge
gate is `pnpm check:all` (see "Verifying a change"); no CI runs on the forge.
The first species ships as the equine anatomical sheet: the historical
`Horse.svg`, `Horse_head.svg` and findings catalog (26 zones, 792 nodes)
+4 -1
View File
@@ -30,7 +30,10 @@ step has built yet, with the step that owns them:
| Element | Owner |
|---|---|
| Bilans, Clients, Animaux, Agenda, Fiches anatomiques entries and screens | Steps 9 to 16 (clients/animals, cloud reports, agenda) |
| Clients and Animaux entries and screens | roadmap V1-1 (plan Step 12 reduced, `docs/development/V1-1_OWNERS_ANIMALS.md`) |
| Fiches anatomiques entry and screen | roadmap V1-2 (plan Step 13 reduced) |
| Bilans entry and screens | roadmap V1-3 (plan Step 14) |
| Agenda entry and screens | plan Step 20 |
| Stat tiles (bilans créés, clients, animaux, rendez-vous) and "Derniers bilans" | once the reports and agenda tables exist; never invented numbers |
| Notification bell | notifications step |
| Avatar photo and "Modifier la photo" | built in Step 8 (2026-10-13): circle + "Modifier la photo" in Informations personnelles, photo in the sidebar / drawer badge and in the top bar with the name on desktop (link to Mon compte, no dropdown) |
+1 -1
View File
@@ -298,7 +298,7 @@ the decision lands; only the naming one is implemented in this document.
| 3 | A new publication becomes the current version; older versions are **not deprecated automatically** and stay readable under the access rules. | Already the behaviour of `publish_sheet_version`; deprecation stays a manual act. |
| 4 | Official sheets are **platform-owned**, administered by authorised accounts. | Already the model: `creator_user_id = null`, `is_official = true`, platform admins edit. |
| 5 | Name anatomical findings apart from the observations typed during a report. | Finding category kind `observation` renamed **`consultation_reason`** (`dysfunction` / `consultation_reason` / `anamnesis` / `custom`). The report-side object keeps the name Observation. |
| 6 | Server-side validation and integrity for every publication; the frontend is never a security boundary. | SQL already re-checks references, sizes and species. The full shape check (Zod) moves server-side before community publication: plpgsql shape rules or an Edge Function gate, decided at the community step. |
| 6 | Server-side validation and integrity for every publication; the frontend is never a security boundary. | SQL already re-checks references, sizes and species. The full shape check (the Rust core's `sheet.check` since R2) moves server-side before community publication: plpgsql shape rules or a Rust service gate (Edge Functions retired, D-R9), decided at the community step. |
| 7 | Account deletion handles dependencies and transfers explicitly (RGPD); no dependency may block the erasure of personal data forever. | Retention step (§16): published versions get their `created_by` / `published_by` anonymised through a dedicated system path (the immutability guard will allow that single transition), personal sheets are transferred or archived, `creator_user_id` keeps `on delete restrict` only as the backstop that forces the explicit path. |
## 6. Official equine sheet: import (Step 4b) and curation (Step 4c)
+55 -42
View File
@@ -3,25 +3,32 @@
Status: Step 0 deliverable, 2026-10-08. Conceptual only. No migration, table,
policy or function is created by this document. Table and function names
follow `faunosteo-business-architecture.md` §4–§20.
Revised 2026-10-25 (P0): Edge Functions retired (D-R9, BDR-045), worker =
`crates/worker` in Rust, data contracts in `crates/core` (R2), bucket list and
signed-URL rule as built at Step 8 (`STORAGE.md`). Hosting stays open
(`OPEN_QUESTIONS.md` Q2).
## 1. Components and what runs where
```text
Browser (apps/app, anon key + user JWT)
│ tables via RLS, RPC (security definer), Storage signed URLs
Browser (apps/app, anon key + user JWT, Rust core as WebAssembly)
│ tables via RLS, RPC (security definer), Storage under storage.objects policies
▼
Supabase (self-hosted on Scaleway at launch, §31)
├─ Auth (GoTrue): email/password, Google, Apple, OTP, phone
Supabase (self-hosted on Scaleway at launch, §31; hosting open, Q2)
├─ Auth (GoTrue): email/password, OAuth providers (Google, Apple), OTP, phone; keeps the OAuth flows (D-R9)
├─ PostgreSQL: schemas public / private / audit, RLS, functions, pg_cron
├─ Storage: private buckets, storage.objects policies
├─ Edge Functions (Deno): public endpoints, webhooks, signed-URL issuance
└─ Realtime (optional): report sync state
Worker (apps/worker, service key, same host)
└─ jobs table in PostgreSQL, no Redis
public-web (anon key, SSR)
└─ Storage: private buckets, storage.objects policies evaluated on public.assets
Rust worker (crates/worker, container faunosteo_worker, service key, same host)
└─ jobs claimed from PostgreSQL through RPCs (lease token), no Redis; decode child sandboxed
Rust HTTP services (same image, other subcommands, own secrets; from the first inbound need)
└─ webhooks (Stripe), OAuth callbacks of external calendars, public endpoints that SQL cannot serve
public-web (Astro, D-R8; anon key)
└─ public views / RPCs only
```
Edge Functions are not used (D-R9): limits on the self-hosted edge runtime, hand
deployment, and one Rust runtime for every server process.
The browser never holds a service-role key, admin credential, storage master
key or third-party refresh token (§17.1).
@@ -33,8 +40,8 @@ key or third-party refresh token (§17.1).
| Google, Apple | GoTrue OAuth providers | Apple requires a paid developer account and a services id: dependency to confirm |
| Phone verification | GoTrue phone OTP needs an SMS provider (Twilio, MessageBird, Vonage) | cost and EU processing to confirm; see `OPEN_QUESTIONS.md` Q7 |
| Email verification | GoTrue, mandatory before professional features | |
| MFA | GoTrue TOTP; mandatory for owner/admin/moderator/support roles, enforced by RLS helper `has_mfa()` on admin tables | |
| Roles | `profile_roles` table, never JWT custom claims as the only source (claims can lag) | helpers read the table |
| MFA | GoTrue TOTP; mandatory for owner/admin/moderator/support roles, enforced by RLS helper `has_mfa()` on admin tables | TOTP enabled server-side; `has_mfa()`, enrolment and enforcement not built (`IDENTITY.md` §4, TODO RR-3) |
| Roles | `profile_roles` table with the `platform_role` enum (owner, admin, moderator, support: BDR-026), never JWT custom claims as the only source (claims can lag) | helpers read the table; professional statuses (practitioner, student, professor) come from verification, cabinet roles from membership, never from this enum |
| Impersonation | dedicated RPC issuing a short-lived scoped session, audited, banner in UI (§17.5) | after MVP core |
`profiles.id = auth.users.id`, created by a trigger on `auth.users` insert.
@@ -51,7 +58,7 @@ Conventions fixed now so every step follows them:
- UUID primary keys (`gen_random_uuid()`), `created_at` / `updated_at` with a shared trigger, soft delete `deleted_at` where the architecture names it.
- Enums as PostgreSQL `enum` types when the value set is closed by the business (report status, appointment status), `text` + CHECK when the set is expected to grow (document types).
- JSONB documents (`reports.current_document`, `anatomical_sheet_versions.content_jsonb`) carry their own `schema_version` and are validated by the matching Zod schema at the application boundary and by a CHECK on `schema_version` in SQL. SQL does not re-implement Zod.
- JSONB documents (`reports.current_document`, `anatomical_sheet_versions.content`) carry their own `schema_version` and are validated by the Rust core's contracts (`crates/core/src/domain`, since R2) at the application boundary and by a CHECK on `schema_version` in SQL. SQL re-checks only what publication needs (`private.sheet_document_issues`, BDR-032), with the same rule codes as the core.
- Every table exposed to the browser: RLS enabled, no `USING (true)` policy for `authenticated`, no anonymous policy on core tables (§17.4).
## 4. RLS strategy
@@ -102,40 +109,42 @@ EXECUTE on those functions and nothing else.
## 5. Storage
Buckets, all private: `avatars`, `logos`, `professional-documents`,
`client-files`, `animal-files`, `report-files`, `anatomical-sheets`, `imports`.
Buckets, all private, as built (`STORAGE.md`): `avatars` (the only one with
policies), `logos`, `professional-documents`, `client-files`, `animal-files`,
`report-files`, `imports` (closed until their step writes the rules), and
`anatomical-sheet-assets` (sheet drawings, its own policy).
Object key: `<resource-type>/<resource-id>/<asset-id>/<safe-filename>`. The
`assets` table is authoritative; `storage.objects` policies call the owning
helper (`can_view_report` for `report-files/...`). Reads go through signed
URLs issued by an RPC/Edge Function after the same check.
Object keys are built by the server from uuids
(`profiles/<owner>/<id>/avatar.webp`, `quarantine/<owner>/<id>/upload`). The
`assets` table is authoritative; `storage.objects` policies compare whole keys
through `assets`. Owner-only files are downloaded under the SELECT policy with
no signed URL (BDR-048); a shared kind may use a short-lived signed URL issued
by the Storage API after the same policy. There is no `issue_signed_url` RPC.
SVG pipeline (§15.3): upload lands in a quarantine prefix with
`assets.sanitization_status = pending`; a server sanitizer (Edge Function or
worker) rewrites the file (strip `<script>`, `<foreignObject>`, `on*`,
`javascript:`/external hrefs, `<use>` to external documents, CSS `url()`),
stores the clean bytes under the final key and sets `status = clean`. Policies
only allow reading `clean` assets to anyone other than the uploader. The
current 10-line client sanitizer stays as a pre-check in the editor, not as
the boundary.
Untrusted uploads (§15.3) land under a quarantine key; the Rust worker's
sandboxed child decodes them and writes the clean object; a quarantine object
is never readable by an API role. User SVG uploads arrive with Step 13 and go
through the Rust core's one SVG reader (prescan caps, allowlist, reference
graph), never a browser sanitiser as the boundary.
Archive (§15.4, §16): S3-compatible cold storage with lifecycle rules, no
Object Lock by default. Out of MVP core; designed at the data-lifecycle step.
## 6. Edge Functions vs PostgreSQL functions vs worker
## 6. PostgreSQL functions vs Rust worker vs Rust HTTP services
Decision rule for each server-side behaviour:
Decision rule for each server-side behaviour (D-R9 replaced the Edge
Functions row):
| Put it in | When |
|---|---|
| PostgreSQL function / trigger (RPC) | Needs transactional guarantees with the data: report numbering, completion + quota, booking slot lock, grant evaluation, version publication, GC preconditions |
| Edge Function | Needs HTTP from outside or secrets: Stripe webhooks, public widget endpoints, signed-URL issuance, calendar OAuth callbacks, email send trigger, SVG sanitization (small files), import preflight (small files) |
| Worker | Long or scheduled: reminders, expiry sweeps (unless `pg_cron`), calendar sync, route cache, long imports, archive, GC sweeps, server PDF (later) |
| Rust HTTP service (`crates/worker` image, `serve` subcommand behind the reverse proxy) | Needs inbound HTTP from outside or third-party secrets: Stripe webhooks, public widget endpoints SQL cannot serve, external calendar OAuth callbacks; each service holds only its own secrets |
| Rust worker (`crates/worker`, job loop) | Long, scheduled or untrusted-bytes work: file decoding (avatar since Step 8), reminders and email sending, expiry sweeps (unless `pg_cron`), calendar sync, route cache, long imports, archive, GC sweeps, server PDF (later) |
Self-hosted note: Edge Functions on a self-hosted stack run in the
`edge-runtime` container and must be deployed by hand. The first steps lean
on PostgreSQL functions, which the CLI migrates and tests natively. See
`OPEN_QUESTIONS.md` Q2 on VPS sizing.
Supabase Auth keeps the OAuth sign-in flows it already handles. Shared rules
come from `crates/core`; the worker and the HTTP services are distinct
processes with their own least privilege. See `OPEN_QUESTIONS.md` Q2 on VPS
sizing.
## 7. Migrations
@@ -146,9 +155,12 @@ on PostgreSQL functions, which the CLI migrates and tests natively. See
listed in §32 of the architecture, pgTAP tests, and regenerated types.
- `supabase db reset` must succeed from zero on CI, then `supabase test db`,
then the app test suite (§36).
- Seed data (`supabase/seed/`): species list, plans, the official equine sheet
v1 produced by the importer from the two SVGs and the catalog. Seeds are
idempotent and versioned like migrations.
- Seed data (`supabase/seed/`): the official equine sheet as a DRAFT,
generated by the Rust pipeline (`pnpm import:equine`) from the legacy
sources and the curation changeset; it is published only by a platform admin
after business review (BDR-034, BDR-037). Reference lists (species, later
plans) are written by migrations. Seeds are idempotent and versioned like
migrations.
- Production changes follow expand/contract when a column is renamed or
dropped (the `deprecation-and-migration` skill applies).
@@ -167,9 +179,10 @@ Representative cross-tenant cases are a release gate (§30).
## 9. Generated types
`supabase gen types typescript --local > packages/supabase/src/database.types.ts`
after every migration. CI regenerates and fails on diff. Zod schemas in
`packages/domain` remain the contract for JSONB documents; generated types
`pnpm db:types` regenerates `packages/supabase/src/database.types.ts` after
every migration; `pnpm db:types:check` diffs it (no CI runs on the forge,
BDR-047). The Rust contracts of `crates/core/src/domain`, exported to
TypeScript by ts-rs, are the contract for JSONB documents; generated types
cover columns and RPC signatures.
## 10. What must stay server-side (brief §19, architecture principles 6–13)
@@ -182,7 +195,7 @@ cover columns and RPC signatures.
6. Entitlement computation and Stripe state.
7. Referral eligibility and caps.
8. Client candidate matching and sharing consent flows.
9. SVG sanitization and signed URL issuance.
9. Untrusted file decoding (worker child), SVG reading by the core on every product drawing, Storage access through policies.
10. Import preflight, quota check and atomic commit.
11. Audit logging, impersonation, moderation.
12. Archive and deletion workflows.
+15 -8
View File
@@ -5,6 +5,13 @@ Status: Step 0 deliverable, 2026-10-08. Derived from
current code (`docs/faunosteo-audit/`). No SQL here: entity names are the
conceptual tables of the architecture document, listed so that each
implementation step knows which domain it touches.
Revised 2026-10-25 (P0): platform roles (BDR-026), sheet document fields
(BDR-031), Storage as built (`STORAGE.md`). The "Reuse" rows and §19 describe
the code of 2026-10-08: the TypeScript modules they name have since moved into
`crates/core` or been deleted (Steps 5 to 8, R2 to R5); `CLAUDE.md` holds the
current map. Clients and Animals (§4, §5) are being reframed by the V1-1
contract (`V1-1_OWNERS_ANIMALS.md`): workspaces, no global client record,
client-animal links with roles; owner orientations awaiting ratification.
Conventions used below:
@@ -54,7 +61,7 @@ Animals, Identity and (optionally) Organizations.
| Item | Content |
|---|---|
| Entities | `profiles` (= `auth.users.id`), `profile_roles` (additive roles: practitioner, student, professor, owner, admin, moderator, support), `platform_invitations` |
| Entities | `profiles` (= `auth.users.id`), `profile_roles` (enum `platform_role`: owner, admin, moderator, support; BDR-026), `platform_invitations` (not built). Professional statuses (practitioner, student, professor) are outcomes of Professional Verification, cabinet roles live in the cabinet membership: neither is a platform role. |
| Depends on | Supabase Auth (email/password, Google, Apple, OTP/magic link, phone verification) |
| Depended on by | every other domain |
| Server-only | role grants (admin action, never a browser update), phone/email verification state, invitation acceptance |
@@ -109,10 +116,10 @@ Animals, Identity and (optionally) Organizations.
| Item | Content |
|---|---|
| Entities | `species` (list: id, labels), `anatomical_sheets` (identity, creator, visibility, status, provenance `based_on_sheet_id`/`based_on_version_id`, `current_version_id`), `anatomical_sheet_versions` (version number, status draft/published/deprecated, `document_schema_version`, `content_jsonb`, assets, publication metadata), sheet assets in Storage (SVG per view) |
| Canonical document (JSONB) | `schema_version`, `species_id`, `vertebral_config` (ordered regions: code, label FR/EN, count), `views[]` (id, kind main/detail, `parent_view_id`, `opened_by_annotation_id`, `view_box`, `svg_asset_id`), `annotations[]` (stable id, view id, kind point/zone/detail-trigger, category id, names FR/EN, laterality, special, geometry), `categories[]` (id, label, colour), `finding_tree.zones{}` (current `ZoneFindings` shape), `annotation_finding_map[]` (annotation id → finding zone id), `scope_disclaimer`, legacy id map (old `data-anno-id` → new id) kept for migration only |
| Canonical document (JSONB) | `schema_version`, `species_id`, `vertebral_config` (ordered regions: code, label FR/EN, count), `views[]` (id, kind main/detail, `parent_view_id`, `opened_by_annotation_id`, `view_box`, `svg_asset_id`), `annotations[]` (stable id, view id, kind point/zone/detail-trigger, category id, names FR/EN, laterality, special, geometry), `categories[]` (id, label, colour), finding tree by finding zone, `finding_zone_id` inline on each annotation (no separate map, BDR-031), `scope_disclaimer`; legacy id mapping kept in the seed's generated files and the report migration map. Exact shape: `ANATOMICAL_SHEET_MODEL.md` |
| Depends on | Identity (creator), Files (SVG assets), Community (visibility/grants read at use time), Billing (private visibility add-on) |
| Depended on by | Reports (exact version reference), Community, Animals (species list), Imports (none) |
| Server-only | version immutability once published, version numbering, garbage collection preconditions (no report, no fork, no grant, no pending process), SVG sanitization before any other user can read the asset, "can use / can fork" evaluation |
| Server-only | version immutability once published, version numbering, garbage collection preconditions (no report, no fork, no grant, no pending process), SVG reading by the core before any other user can read the asset, "can use / can fork" evaluation |
| Reuse | `parseSvgBones` (importer and renderer), `findings.ts` schema (finding tree), `zoneMatch.ts` (importer only), `regionFromLabel` (importer only), `AnatomyCanvas`, `DetailModal`, `VertebraPicker`, `FindingsTreePicker`, the two equine SVGs and the catalog as seed, the tree-edit behaviour of `pathology-editor.html` and the annotation operations of `SvgEditorRoute` as functional references |
| Notes | Rules 2–8 of the brief (§18) all live here. The current code has no sheet object at all (audit 02 §6): no id, no version, no author, no persisted SVG ↔ catalog link. |
@@ -121,7 +128,7 @@ Animals, Identity and (optionally) Organizations.
| Item | Content |
|---|---|
| Entities | `reports` (report number, animal, practitioner, organization nullable, ownership scope, status draft/completed/archived, report date, `anatomical_sheet_version_id`, `current_document`, revision counter, `completed_at`, `free_edit_until`, soft delete), `report_revisions` (document snapshots with reason), `report_access_grants`, `practitioner_report_counters` (row-locked numbering), report PDF artifacts (Files) |
| Report document (JSONB) | current `Report` v2 shape evolved to v3: observations with zones keyed by `annotationId` + `viewId`, vertebrae with region code, findings with snapshots, free text, severity, comment, conclusion, recommendations, next appointment, identity snapshots (practitioner, animal, client), `localAnnotations[]` (report-only points, see `OPEN_QUESTIONS.md` Q6), locale used for the last PDF |
| Report document (JSONB) | current `Report` v2 shape evolved to v3: observations with zones keyed by `annotationId` + `viewId`, vertebrae with region code, findings with snapshots, free text, severity, comment, conclusion, recommendations, next appointment, identity snapshots (practitioner, animal, client), `localAnnotations[]` (report-only points, see `OPEN_QUESTIONS.md` Q6); the locale stays out of the report (BDR-014), the PDF envelope records it |
| Depends on | Animals (and Clients through them), Identity, Organizations, Anatomical Sheets (exact version), Billing & Entitlements (quota, free edit window), Files (PDF artifacts) |
| Depended on by | Community (shared report revisions), Booking (appointment ↔ report link, optional), Imports, Notifications (secure sending to the owner) |
| Server-only | report numbering, completion (quota check, `free_edit_until`), revision checkpoints, "deleted completed reports still count", shared-practitioner revision acceptance, import quota preflight |
@@ -173,10 +180,10 @@ Animals, Identity and (optionally) Organizations.
| Item | Content |
|---|---|
| Entities | `assets` (bucket, object key, owner scope, resource type/id, mime, size, checksum, sanitization status), buckets `avatars/ logos/ professional-documents/ client-files/ animal-files/ report-files/ anatomical-sheets/ imports/` |
| Entities | `assets` (status, owner, server-built keys, lease; `STORAGE.md`), buckets `avatars` (policies), `logos`, `professional-documents`, `client-files`, `animal-files`, `report-files`, `imports` (closed), `anatomical-sheet-assets` (sheet drawings) |
| Depends on | Identity, and every owning domain for access rules |
| Depended on by | Verification, Clients, Animals, Reports (PDF artifacts), Anatomical Sheets (SVG), Imports, Public Profile (photos, logos) |
| Server-only | object key generation (`<resource>/<resource-id>/<asset-id>/<safe-filename>`), signed URL issuance, SVG sanitization and quarantine, `storage.objects` RLS |
| Server-only | object key generation from uuids, quarantine and decoding in the Rust worker's sandboxed child, `storage.objects` RLS through `assets`; owner-only files read under RLS with no signed URL (BDR-048) |
| Reuse | `sanitizeSvg` (10 lines in `SvgEditorRoute` and duplicated in `pathology-editor.html`) as the *client-side* pre-check only; the server sanitizer is new. |
## 13. Billing & Entitlements
@@ -235,8 +242,8 @@ Animals, Identity and (optionally) Organizations.
| Item | Content |
|---|---|
| Entities | `student_professor_links`, `student_access_periods`, student-owned educational reports |
| Depends on | Identity (student/professor roles), Reports, Billing (student entitlement), Anatomical Sheets |
| Notes | Must not be built in the MVP, but `profile_roles` and `entitlement_grants` are shaped so it fits later without migration pain. |
| Depends on | Identity and Professional Verification (student/professor statuses, not platform roles: BDR-026), Reports, Billing (student entitlement), Anatomical Sheets |
| Notes | Must not be built in the MVP, but verification statuses and `entitlement_grants` are shaped so it fits later without migration pain. No plan step owns education yet. |
## 19. Reuse matrix (current code → domain)
@@ -2,6 +2,14 @@
Status: Step 0 deliverable, 2026-10-08. Proposal only; the repository is not
transformed by this document.
Snapshot notice (2026-10-25, P0): this text describes the app of 2026-10-08
and its planned target. Since then: auth and the `/app` shell exist (Step 7,
`IDENTITY.md`), the worker is the Rust `crates/worker` (not a Node `apps/worker`),
Edge Functions are retired (D-R9), the packages `domain`, `anatomy`, `pdf` and
pdf-lib were replaced by `crates/core` and deleted (R4.8, R5.7), the legacy
editors and `public/species` were deleted at Step 5, no TanStack Query
(BDR-041), the public site framework is Astro (D-R8). `CLAUDE.md` (folder map,
architecture) is the current description.
## 1. Starting point
+90 -37
View File
@@ -12,6 +12,39 @@ Reference product/architecture: `faunosteo-business-architecture.md`
does today; the architecture document is the source of truth for what it
must become. Where the two disagree, `OPEN_QUESTIONS.md` records it.
## 0. Where the plan stands (2026-10-25)
Done on `develop`: Steps 0 to 8 (Step 4 in three parts 4, 4b, 4c) and the Rust
migration R0 to R5 (`RUST_ARCHITECTURE_REVIEW.md`, `RUST.md`): every domain
rule, the SVG reader, the PDF reader and writer, the curation pipeline and the
files worker are Rust (`crates/`). Merging into `develop` authorises nothing in
production; release 0.2.0 (Steps 3 to 6) is still waiting (TODO RR-9).
The product roadmap validated by the owner on 2026-10-25 regroups the
remaining steps toward a first usable version: a signed-in practitioner keeps
clients, animals and bilans in the cloud, with history and PDF, on phone and
computer. Inventory: `.claude/audits/2026-10-25-functional-inventory.md`.
| Order | Content | Plan steps |
|---|---|---|
| P0 | Documents realigned on the code, decisions recorded (`OPEN_QUESTIONS.md` statuses) | none |
| V1-1 | Clients and animals of a practitioner's workspace, with the permission frame of future cabinets (`V1-1_OWNERS_ANIMALS.md`) | 12 reduced, frame of 10 |
| V1-2 | Anatomical sheets loaded from Supabase under control (no publication of the equine draft without the owner) | 13 reduced |
| V1-3 | Bilans persisted, linked to an animal, history | 14 (+ 11 skeleton if a quota applies) |
| V1-4 | Stored PDF artifacts and authorised sharing | 15 reduced, sharing part of 12 |
| V1-5 | Cross-cutting mobile and accessibility validation | design README, `TEST_STRATEGY.md` |
| Next | Verification 9, cabinets 10, entitlements 11, then 16 to 27 | per step |
Accessibility and security apply at every step, not only at V1-5. The release
readiness track (TODO RR-1 to RR-10) stays separate: no V1 step authorises a
release or a public exposure, and passing development tests is not a
production authorisation. The step texts below keep their numbering; each V1
item reuses the step it reduces. For a done step, the block is the original
specification: its "as built" note, the code and `CLAUDE.md` are
authoritative where they differ (the TypeScript packages `domain`, `anatomy`
and `pdf` named in Steps 4 to 6 were replaced by `crates/core` and deleted at
R4.8 and R5.7).
## 1. How to read the plan
- Steps follow the real dependency order, not the commercial sprint order of
@@ -32,12 +65,14 @@ must become. Where the two disagree, `OPEN_QUESTIONS.md` records it.
## 2. Guiding principles for every step
1. `pnpm typecheck && pnpm test:run && pnpm lint` green before any commit; for
DB steps also `supabase db reset && supabase test db` (architecture §36).
DB steps also `pnpm db:reset && pnpm db:test` (the CLI runs only through
`scripts/supabase.sh`); after a Rust change `pnpm rust:check`; before a
merge `pnpm check:all`.
2. A step that adds a table adds its RLS policies, indexes, pgTAP tests and
regenerated types in the same branch.
3. The UI is never the security boundary; every rule listed in
`BACKEND_ARCHITECTURE.md` §10 is implemented in PostgreSQL or a server
function.
`BACKEND_ARCHITECTURE.md` §10 is implemented in PostgreSQL or in a Rust
server process (`crates/worker` or a Rust HTTP service, D-R9).
4. No deletion of user data. Soft delete, revisions, archive.
5. Legacy modules are deleted at the step named in
`REPOSITORY_MIGRATION_MAP.md`, in the same branch that makes them dead.
@@ -200,7 +235,8 @@ Risks: snapshot size growth with future sheets (mitigate: snapshot subset = only
Milestone A (after Step 6): release 0.2.0 "canonical sheet + PDF v3", still a
local tool. Everything above has no backend and can ship to faunosteo.com
as-is.
as-is. Status 2026-10-25: `release/0.2.0` cut on 2026-10-11, not finished; its
fate (ship, supersede, rebase) is TODO RR-9.
```text
Step 7
@@ -220,7 +256,7 @@ Step 7 implementation note (2026-10-11): shipped as `docs/development/IDENTITY.m
Deviations: no TanStack Query (a zustand store covers the profile read/update of this
step; the query layer comes with the first list screens); `platform_invitations` and the
MFA helper not written (no admin screen to protect yet, gap documented in IDENTITY.md §4);
professional fields added to `profiles` as declared free text (verification = Step 11);
professional fields added to `profiles` as declared free text (verification = Step 9);
Google/Apple wired in config.toml behind env ids, buttons behind `APP_AUTH_PROVIDERS`.
```text
@@ -244,7 +280,8 @@ Step 8 as built (2026-10-13, `STEP8_FILES_ANALYSIS.md` D1–D9 + Rust R1,
family); there is no `issue_signed_url` RPC (the Storage API signs after the
SELECT policy; the owner-only avatar is downloaded under RLS, no signed URL);
the SVG sanitiser and the user SVG upload path move to Step 13 with their
producer (the allowlist sanitiser already exists in `packages/pdf`); the
producer (the allowlist sanitiser then lived in `packages/pdf`; since R3 it
is the Rust core's one SVG reader, `anatomy::svg::read_svg`); the
avatar pointer is derived from the single clean `assets` row (no
`profiles.avatar_asset_id`); the sheet bucket keeps its name
`anatomical-sheet-assets`.
@@ -288,7 +325,7 @@ Changes expected:
Tests: pgTAP matrix: free user, verified free user, invited grant with expiry, admin role; expired grant yields nothing.
Manual validation: grant an invited entitlement to a user via admin RPC and watch capabilities change.
Definition of Done: no is_paid boolean anywhere; every later feature reads capabilities.
Risks: capability list drift (keep it as one SQL enum + one TS const checked by a test).
Risks: capability list drift (keep it as one SQL enum + one Rust const in the core, exported to TypeScript through ts-rs, checked by a test).
```
```text
@@ -305,20 +342,37 @@ Definition of Done: architecture Sprint 3; rule 1 (animal ≠ sheet) visible in
Risks: the global-client design (C4) if confirmed as plain shared rows; GDPR consent texts not final (version column from day one).
```
Step 12 note (2026-10-25): roadmap item V1-1 proposes a reduced Step 12 under
the owner's orientation C4 (records attached to a workspace, one personal
workspace per practitioner, cabinets later, no global client record shared
between practitioners), without consents, grants, sharing, files or candidate
matching: `V1-1_OWNERS_ANIMALS.md`. The text above stands until the owner
ratifies the contract's orientations (§9.1) and answers its sub-choices
(§9.2).
```text
Step 13 (∥ Steps 9–12)
Name: Anatomical sheets in the database and official equine seed
Objective: Sheet and version tables with immutability, SVG assets in Storage, seed of the official equine sheet v1, SheetProvider over Supabase, read-only sheet library in the app.
Objective: Sheet and version tables with immutability, SVG assets in Storage, seed of the official equine sheet as a draft, SheetProvider over Supabase, read-only sheet library in the app.
Dependencies: Step 3, Step 4, Step 8
Changes expected:
- supabase: anatomical_sheets, anatomical_sheet_versions (content_jsonb + schema CHECK), immutability trigger on published rows, version numbering RPC, deprecate RPC, GC function with the four preconditions (no report, no fork, no grant, no pending process) returning candidates only (deletion job at Step 18), helpers can_use_sheet/can_fork_sheet (creator-only for now), seed script uploading the two SVG assets and inserting v1 published.
- supabase: anatomical_sheets, anatomical_sheet_versions (content_jsonb + schema CHECK), immutability trigger on published rows, version numbering RPC, deprecate RPC, GC function with the four preconditions (no report, no fork, no grant, no pending process) returning candidates only (deletion job at Step 18), helpers can_use_sheet/can_fork_sheet (creator-only for now), operator upload of the drawings (`pnpm assets:upload`) and the generated draft seed. Publication of the official equine sheet is an explicit act of a platform admin after the business review of REVIEW-REPORT.md (BDR-034, BDR-037); no step publishes it automatically.
- packages/supabase: typed accessors; apps/app: SheetProvider.supabase replaces the bundled seed in production builds (bundled kept for tests), /app/anatomy read-only list and preview.
Tests: pgTAP: UPDATE on published content raises; v2 numbering; GC preconditions each individually; non-creator cannot read a private sheet; integration: seed is idempotent and byte-faithful (checksums).
Manual validation: open /app/anatomy, see "Faunosteo / Cheval / officielle v1", preview both views, click zones (no report yet).
Definition of Done: rules 4–7 enforced in SQL; public/species/* no longer fetched by apps/app (nginx /species/ rule removed); SvgEditorRoute loads assets through signed URLs.
Risks: seed drift vs the committed document.json (CI compares); storage policy for public sheets to be widened at Step 18 only.
Manual validation: open /app/anatomy, see "Faunosteo / Cheval / officielle" with its draft or published status, preview both views, click zones (no report yet).
Definition of Done: rules 4–7 enforced in SQL; the app loads the sheet document and its drawings from Supabase, every drawing through the core's SVG reader; the bundled sheet stays for tests and the local tool.
Risks: seed drift vs the generated folders (`pnpm import:equine --check` and the curation tests compare; no CI runs, BDR-047); storage policy for public sheets to be widened at Step 18 only.
```
Step 13 status (2026-10-25): the tables, immutability triggers, RPCs, the
`anatomical-sheet-assets` bucket and the generated equine DRAFT seed exist
since Steps 4, 4b and 4c (migrations `20261008110000`, `20261009100000`,
`20261010100000`); `public/species/` and the SVG editor were deleted at
Step 5. Remaining: the provider over Supabase, the library screen, the GC
candidates. Roadmap item V1-2 reduces the step to a controlled loading of the
sheets; whether a signed-in practitioner may load the unpublished draft is an
owner decision taken at V1-2.
```text
Step 14
Name: Cloud reports
@@ -339,12 +393,12 @@ Name: PDF artifacts and cloud import
Objective: Store generated PDFs as report artifacts; import PDFs into the account through a server-validated path; render historical reports even if the sheet is gone.
Dependencies: Step 6, Step 14. Gate: confirmation before touching import/attachment code again.
Changes expected:
- supabase: report_pdf_artifacts (asset, locale, revision no, sha256), RPC import_report(attachment json, target animal) doing: version check, Zod validation server-side (plpgsql cannot run Zod → validate in an Edge Function or accept the attachment into a staging row and validate in the app with a server re-check of the invariants that matter: sheet version exists or snapshot-only version created, quota, ownership), snapshot-only version creation (read-only, status deprecated, flagged snapshot_only) when the referenced version no longer exists.
- supabase: report_pdf_artifacts (asset, locale, revision no, sha256), RPC import_report(attachment json, target animal) doing: version check, server-side validation of the archive (plpgsql cannot run the core's readers → run the Rust core's archive reader in a Rust service, D-R9, or accept the attachment into a staging row, read it with the core in the browser and re-check on the server the invariants that matter: sheet version exists or snapshot-only version created, quota, ownership), snapshot-only version creation (read-only, status deprecated, flagged snapshot_only) when the referenced version no longer exists. Opening import to external users stays gated by PDF_IMPORT_HARDENING.md §5 (BDR-040).
- apps/app: download/open artifact list on a report; import flow from the dashboard with quota preflight message and pricing redirect.
Tests: pgTAP: import beyond quota denied before any insert; snapshot-only version is never selectable for new reports; integration: export → delete sheet version (as admin) → import → PDF re-renders.
Manual validation: export, import into a second account (denied: wrong animal/owner), import into own account, check artifact list.
Definition of Done: rule 8 (historical restorable) demonstrated by test; PDF v2 import decision (Q1) applied.
Risks: Zod validation location (server vs client) must be decided per Q2; duplicate imports (idempotency by report id + sha256).
Risks: validation location (Rust service vs browser core with server re-check) decided at the step; duplicate imports (idempotency by report id + sha256).
```
```text
@@ -367,15 +421,15 @@ with the practitioner client. Steps 17–18 can start before B.
```text
Step 17 (∥ Steps 14–16)
Name: Anatomical sheet editor (merge of SVG editor and findings editor)
Objective: One structured editor on the canonical document: views, points/zones, categories, laterality, vertebral config, detail view creation, finding tree, annotation ↔ zone mapping, draft/publish/deprecate; personal sheets and official sheet maintenance; old tools deleted.
Dependencies: Step 13 (tables), Step 5 (document), decisions Q4/Q5/C8
Objective: One structured editor on the canonical document: views, points/zones, categories, laterality, vertebral config, detail view creation, finding tree, annotation ↔ zone mapping, draft/publish/deprecate; personal sheets and official sheet maintenance.
Dependencies: Step 13 (tables), Step 5 (document). Q4, Q5 and C8 are settled (OPEN_QUESTIONS statuses).
Changes expected:
- apps/app: /app/anatomy (library: official, own), /app/anatomy/new, /app/anatomy/:sheetId/editor with SheetEditorStore (document + selection + mode + undo), canvas tools (select/point/polygon, drag, vertex edit), properties panel, categories panel, views panel (create detail view from zone: bbox + margin → view_box, child view), vertebral config panel, findings panel (tree edit from pathology-editor behaviour + validation), mapping panel (annotation → finding zone, suggestions from zoneMatch allowed here as a helper), publish flow (new immutable version), deprecate.
- Deleted in the same branch: SvgEditorRoute.tsx, svg-editor.css, svg_editor.* keys, EditorsRoute, public/pathology-editor.html, public/species/equine/pathologies.json, scripts/scaffold-species.mjs.
- supabase: draft uniqueness (one draft per sheet), publish RPC validating the document (mapping targets exist, no dangling views) and uploading assets, personal-sheet creation RPC.
- apps/app: /app/anatomy (library: official, own), /app/anatomy/new, /app/anatomy/:sheetId/editor with SheetEditorStore (document + selection + mode + undo), canvas tools (select/point/polygon, drag, vertex edit), properties panel, categories panel, views panel (create detail view from zone: bbox + margin → view_box, child view), vertebral config panel, findings panel (tree edit + validation by the core), mapping panel (annotation → finding zone), publish flow (new immutable version), deprecate. Document rules, validation and drawing go through `crates/core` (BDR-043).
- The legacy tools (SvgEditorRoute, EditorsRoute, public/pathology-editor.html, public/species, scripts/scaffold-species.mjs) were already deleted at Step 5 (BDR-038); until this step, sheet content changes only through `curation/changes.json` and the Rust pipeline, reviewed, tested and versioned, and no graphic editor changes or publishes it (owner confirmed 2026-10-25). Annotating a bilan never changes the anatomical reference.
- supabase: draft uniqueness (one draft per sheet, exists since Step 4), publish RPC validating the document (mapping targets exist, no dangling views) and uploading assets, personal-sheet creation RPC.
Tests: one test per legacy operation (audit 03 §2, 05 §3.5) on the new model; detail-view geometry; publish creates v+1 and v1 reports still render (regression from Step 15 fixtures); pgTAP for draft uniqueness and publish validation.
Manual validation: fork-free scenario: create a personal sheet from scratch for a second species (dog, 3 points, 1 spine zone, 1 detail), publish, create a report on it, PDF; then edit the official sheet as admin, publish v2, open an old report (still v1).
Definition of Done: architecture Sprint 6 (except "promote manual point", added once Q6 is answered); REPOSITORY_MIGRATION_MAP REPLACE items for the editors closed.
Definition of Done: architecture Sprint 6 (except "promote manual point", added once Q6 is answered); every legacy editor operation of audit 03 §2 and 05 §3.5 covered on the new model.
Risks: largest UI step; split into sub-branches (canvas tools / panels / publish) each merged green behind a "beta" flag; feature parity gaps with the vanilla tool found late (mitigate with the reference tests first).
```
@@ -396,16 +450,15 @@ Risks: discovery performance (indexes §32); GC race with an in-flight report cr
```text
Step 19
Name: Notifications foundation and worker
Objective: Email provider abstraction, PostgreSQL job queue, apps/worker, transactional templates FR/EN, secure links.
Objective: Email provider abstraction, PostgreSQL job queue, notification jobs in the Rust worker, transactional templates FR/EN, secure links.
Dependencies: Step 7, Step 12 (document delivery to clients), decision Q7 (provider)
Changes expected:
- apps/worker: Node service, service-role client, job loop on private.jobs (SKIP LOCKED), EmailProvider interface + one implementation, retry/backoff, no clinical data in logs.
- supabase: private.jobs, email delivery log, secure_links (token hash, purpose, expiry).
- packages/i18n split (dictionaries without React) for templates.
- Docker: worker service in compose.
Tests: unit: queue semantics, template rendering; integration: enqueue → worker sends to Inbucket; secure link single-use and expiry.
- crates/worker (Rust, exists since Step 8 / R1 with the avatar job family and its compose service): a notification job family on the PostgreSQL queue (SKIP LOCKED or the lease-token pattern of BDR-048), EmailProvider trait + one implementation, retry/backoff, no clinical data in logs; least privilege per process (D-R9).
- supabase: job table, email delivery log, secure_links (token hash, purpose, expiry).
- Template dictionaries readable by the worker (FR/EN), kept in step with the app dictionaries.
Tests: unit: queue semantics, template rendering; integration: enqueue → worker sends to Mailpit; secure link single-use and expiry.
Manual validation: trigger "send report to owner" and receive the secure link locally.
Definition of Done: first job that is not SQL runs in the worker; architecture §22.3–22.4.
Definition of Done: notification jobs run in the worker; architecture §22.3–22.4 with D-R9 applied.
Risks: provider deliverability (SPF/DKIM at DNS); worker single instance (acceptable at launch).
```
@@ -417,7 +470,7 @@ Dependencies: Step 12, Step 19, Step 11 (booking.manage)
Changes expected:
- supabase: service_types, locations, availability_rules, availability_exceptions, appointments, intake_forms/questions/answers, RPCs request_booking (row lock on practitioner-day, one pending per client), confirm/reject/cancel/reschedule, expiry function (48h / 24h if <72h / 1h if <25h) run by pg_cron, availability RPC (server-side evaluation; travel buffers as fixed minutes until Step 21).
- apps/app: /app/calendar (week view), services/locations settings, manual appointment, intake form builder (default templates per species).
Tests: pgTAP: double request on the same slot (one wins), second pending request by the same client denied, expiry rules at each boundary, status transitions; unit: expiry rule mirror in TS; integration: full booking lifecycle.
Tests: pgTAP: double request on the same slot (one wins), second pending request by the same client denied, expiry rules at each boundary, status transitions; unit: expiry rule mirror in the Rust core (BDR-043); integration: full booking lifecycle.
Manual validation: book as a client via a test page (public UI comes at Step 22), confirm as practitioner, reminder enqueued (Step 19).
Definition of Done: architecture Sprint 8; principle 13 (race-safe) tested.
Risks: timezone handling (store timestamptz, practitioner tz on profile); calendar UI effort (consider a maintained library, declared at the step).
@@ -430,8 +483,8 @@ Objective: RoutingProvider abstraction with cache, travel before/after, return-t
Dependencies: Step 20, Step 19 (worker, alerts)
Changes expected:
- supabase: travel_profiles, travel_pricing_rules, route_cache, external_calendar_connections (encrypted credentials, server only), external_calendar_events, availability RPC extended with travel.
- apps/worker: routing provider adapter (one provider chosen after evaluation; interface first), calendar sync jobs, conflict detection.
- Edge Function or worker endpoint for Google OAuth callback.
- crates/worker: routing provider adapter (one provider chosen after evaluation; interface first), calendar sync jobs, conflict detection.
- Google OAuth callback served by a Rust HTTP service behind the reverse proxy (same image, `serve` subcommand, its own secrets; D-R9). Edge Functions are not used.
Tests: unit: engine with a mocked provider (previous location → travel → appointment → travel → next); pgTAP: external events block slots, titles never exposed; integration: ICS feed import.
Manual validation: two appointments 30 km apart; the availability RPC refuses the gap; connect a Google test calendar and see the block.
Definition of Done: architecture Sprint 9; no provider name in business logic.
@@ -442,7 +495,7 @@ Risks: provider cost/quota; refresh token storage (pgsodium or app-level encrypt
Step 22
Name: Public web and booking widget
Objective: apps/public-web with landing, practitioner public profile, search, SEO; booking widget (iframe + token).
Dependencies: Step 7, Step 9, Step 20, decision Q8 (framework)
Dependencies: Step 7, Step 9, Step 20. Framework: Astro (D-R8, validated with BDR-045; re-checked at the step's brainstorm per the global rule)
Changes expected:
- supabase: public_practitioner_profiles, public views/RPCs (approved columns only), booking_widget_tokens, public booking RPCs rate-limited.
- apps/public-web: SSR pages /, /osteopathe/<slug>, /osteopathes-animaliers/<region|city|species>, sitemap, metadata; booking UI used both on the profile and inside the widget iframe (postMessage height/theme).
@@ -450,7 +503,7 @@ Changes expected:
Tests: pgTAP: anon sees only published profiles and approved columns, never clients/animals/reports; e2e: book from the public page; widget on a static test site.
Manual validation: publish a profile, open it logged out, book; embed the widget script in a local HTML page; revoke the token.
Definition of Done: architecture Sprint 10; SEO checks (/seo, /web-validate) pass on the public pages.
Risks: SEO data leak via views (allow-list columns, tested); framework choice (Q8).
Risks: SEO data leak via views (allow-list columns, tested).
```
```text
@@ -460,7 +513,7 @@ Objective: Stripe customers/subscriptions for individual monthly/yearly, entitle
Dependencies: Step 11, Step 10, Step 7 (verified email + phone for referral), Step 19 (emails)
Changes expected:
- supabase: subscriptions filled by webhook, subscription_seats, referrals, webhook idempotency table, invoice links; get_effective_entitlements covers active subscriptions and referral months.
- Edge Function stripe-webhook (signature check, idempotent); checkout session creation RPC/Edge.
- Stripe webhook endpoint in a Rust HTTP service behind the reverse proxy (signature check, idempotent, its own secret; D-R9); checkout session creation by the same service.
- apps/app: /app/billing (plan, invoices, cancel at period end), pricing page redirect from quota blocks, referral code and status.
Tests: pgTAP: entitlement with active/cancelled/past-due subscription; referral cap 5/year; reward only after referred becomes paying; unit: webhook handler idempotency; integration with Stripe test clocks.
Manual validation: subscribe in test mode, see capability change, cancel, hit period end with a test clock.
@@ -475,7 +528,7 @@ Objective: Staging model, adapters (generic CSV/XLSX/JSON/ZIP, Faunosteo PDF v2/
Dependencies: Step 15 (PDF import), Step 12, Step 11, Step 19 (long imports in worker)
Changes expected:
- supabase: import_jobs, import_files, import_raw_records, import_mappings, import_errors, import_unmapped_data; commit RPC in one transaction; quota preflight.
- apps/worker: ImportAdapter interface (detect/inspect/map/validate/transform/commit), generic adapters; vendor adapters behind feature flags until samples are obtained.
- crates/worker: ImportAdapter trait (detect/inspect/map/validate/transform/commit), generic adapters; vendor adapters behind feature flags until samples are obtained.
- apps/app: /app/settings/import wizard (upload → preview → duplicates → confirm), "Données importées" panel on client/animal.
Tests: adapters on fixture files; pgTAP: commit is atomic (20 reports on a free account roll back entirely); duplicates never auto-merged; traceability of every transformed field.
Manual validation: import a CSV with a duplicate client; confirm the review; check unmapped data is visible.
@@ -503,7 +556,7 @@ Name: Data lifecycle: export, deletion, archive
Objective: Account data export, deletion workflow with hot retention, archive package to S3-compatible storage, sheet-version GC in production mode, restoration from archive.
Dependencies: Step 19 (worker), Step 23 (subscription states), Step 15 (artifacts)
Changes expected:
- apps/worker: export job (JSON + files manifest + checksums), archive job (lifecycle rules, no Object Lock), restore job; supabase: account_lifecycle states (active, restricted, archived, deleted), minimal archive pointer.
- crates/worker: export job (JSON + files manifest + checksums), archive job (lifecycle rules, no Object Lock), restore job; supabase: account_lifecycle states (active, restricted, archived, deleted), minimal archive pointer.
- apps/app: data export request, account deletion request.
Tests: unit: manifest/checksum; integration: export → delete → restore on staging; GC and archive never delete a version referenced by an archived report before its legal retention.
Manual validation: run the full cycle on a test account with artifacts.
@@ -659,7 +712,7 @@ only on explicit human signal.
| PDF: attachment format change, import of user data, browser-only rasteriser | CRITICAL | Steps 6, 15 | v3 format documented, v2 adapter, confirmation gate, Rasterizer interface |
| RLS mistakes | CRITICAL | every DB step | helper + pgTAP per table, full matrix at Step 27, no `USING (true)` for authenticated on core tables |
| Multi-tenant leakage via organization context | CRITICAL | Steps 10, 14 | context passed explicitly to services; org-scoped tests |
| Storage: direct uploads bypass metadata; signed URL leakage | IMPORTANT | Step 8 | insert policy requires assets row; short-lived signed URLs |
| Storage: direct uploads bypass metadata; signed URL leakage | IMPORTANT | Step 8 | insert policy requires assets row; owner-only files downloaded under RLS with no signed URL (BDR-048); short-lived signed URLs only for shared kinds |
| Offline conflicts overwriting server data | IMPORTANT | Step 16 | stale base rejection, conflict revisions, user choice |
| Agenda race conditions and expiry errors | IMPORTANT | Step 20 | row locks, single SQL expiry function, boundary tests |
| Route/travel provider lock-in or cost | IMPORTANT | Step 21 | `RoutingProvider` interface, cache, provider chosen after evaluation |
@@ -670,7 +723,7 @@ only on explicit human signal.
| Phone/email providers undecided | IMPORTANT | Steps 7, 19 | interfaces first; email-only verification until Q7 |
| Vocabulary collision (Observation) in new UI strings | LOW | all UI steps | fixed in C7 |
| Workspace move regressions | LOW | Step 2 | manual script + CI |
| Public site framework choice | LOW | Step 22 | Q8, isolated app |
| Public site framework choice | LOW | Step 22 | Astro (D-R8), isolated app |
## 9. Deliverable checklist per step (applies to every step)
+6
View File
@@ -3,6 +3,12 @@
Status: Step 0 deliverable, 2026-10-08. Describes *how* the existing code
evolves without a big-bang rewrite. The step-by-step schedule is in
`IMPLEMENTATION_PLAN.md`; this document explains the mechanics behind it.
Snapshot notice (2026-10-25, P0): the migrations described here for the sheet,
the report, the PDF and the editors were carried out at Steps 4 to 6 and by
the Rust phases R2 to R5, with different final shapes (inline
`finding_zone_id`, stable slug ids, PDF envelope v1, Rust core in place of the
TypeScript packages, legacy editors deleted at Step 5). Current sources:
`ANATOMICAL_SHEET_MODEL.md`, `docs/PDF-FORMAT.md`, `RUST.md`.
## 1. Principles
+60
View File
@@ -6,6 +6,66 @@ ambiguities or technically risky points found when confronting
questions for the developer that change architecture or development order.
Items that are merely interesting are left out.
## Status (revised 2026-10-25, P0)
The analysis below is the 2026-10-08 text, kept as written; this table says
what has been settled since and by which record (BDR = `.claude/memory/decisions.md`,
D-R = `RUST_ARCHITECTURE_REVIEW.md` Annex A). Paths it cites under
`public/species/` and `public/pathology-editor.html` no longer exist (deleted at
Step 5).
| Item | Status | Settled by / where it stands |
|---|---|---|
| C1 vertebral formula | settled | ordered `vertebral_config.regions`, free codes (BDR-031) |
| C2 report-only points | open | `localAnnotations` reserved empty in Report v3 (BDR-038); promotion semantics undecided (Q6a); defining it later is a report version bump |
| C3 worker on day one | settled | Rust worker built at Step 8 / R1 (BDR-044, BDR-048) |
| C4 global client record | owner orientation, awaiting ratification | records belong to a workspace (one personal workspace per practitioner in V1-1, cabinets later); no global directory shared between practitioners (owner, 2026-10-25); contract `V1-1_OWNERS_ANIMALS.md` §3, D2 |
| C5 animal update rights | owner orientation, awaiting ratification | writes reserved to workspace members with a write right, in V1-1 the practitioner in their personal workspace; no retroactive silent change of a finished bilan (owner, 2026-10-25); V1-1 contract §5.1, §5.3 |
| C6 unverified accounts | owner orientation, awaiting ratification | email confirmation ≠ professional verification; private use for confirmed-email accounts, verification (Step 9) required for public features presenting a verified professional; statuses are not platform roles (BDR-026) (owner, 2026-10-25); V1-1 contract §5.2. Replaces the 2026-10-08 assumption below (no clients or reports before verification) once ratified |
| C7 « Observation » vocabulary | settled | finding category kind `observation` renamed `consultation_reason` (BDR-033 point 5); *Observation* stays the report block |
| C8 drafts per sheet | settled | one draft per sheet, partial unique index (BDR-032) |
| C9 detail view asset | settled | nullable `svg_asset_id`, crop by `view_box`; the equine head is a crop of one cleaned drawing (BDR-031, BDR-036, BDR-037) |
| C10 Edge Functions on a small VPS | Edge part settled, hosting open | Edge Functions retired, Rust services instead (D-R9, BDR-045); VPS sizing and hosting = Q2 |
| C11 restore after the free window | open | Step 11 / 14 with the quota decision |
| C12 SVG sanitisation vs direct upload | settled (mechanism) | quarantine key, status column, closed policies, sandboxed Rust decoder (BDR-048, `STORAGE.md`); user SVG upload arrives with Step 13 through the core's SVG reader |
| C13 CLAUDE.md rules broken | settled | references registry replaces "≥ 1 source" (BDR-036); contracts are Rust (R2) |
| C14 locale of stored PDFs | open | artifact column at Step 15; the archive envelope already records the locale (`PDF-FORMAT.md`) |
| Q1 v2 PDFs in use | partly settled | v2 import is production code (BDR-038, BDR-039); whether real v2 files exist is unanswered |
| Q2 hosting | open | blocks any production backend (TODO RR-5); BDR-049 fixes only the DEV / STAGING / PROD split |
| Q3 non-mammal layouts | settled | free region codes (BDR-031) |
| Q4 external use of the pathology editor | moot | the tool was deleted at Step 5 (BDR-038); content changes go through `curation/changes.json` until the Step 17 editor (owner confirmed 2026-10-25) |
| Q5 one or two equine assets | settled | one cleaned drawing, head as crop (BDR-036, BDR-037) |
| Q6 manual points, shared client records | open (a); (b) reframed by C4 | (a) as C2; (b) no shared record if C4 is confirmed, so the edit-rights question moves inside a data space (V1-1 contract §5) |
| Q7 phone and email providers | open | Step 7 shipped email only; needed before production SMTP and phone verification |
| Q8 public site framework | settled | Astro (D-R8, validated with BDR-045), Rust exception recorded |
| Q9 catalog anomalies | settled, against the 2026-10-08 recommendation | no medical correction at import, anomalies reported, degraded slugs normalised (BDR-034); later corrections through curation changes (BDR-036, BDR-037) |
### Conflicts raised by P0 and their resolution (2026-10-25)
1. Step 17 keeps the plan's merged-editor scope, but the legacy editors were
deleted at Step 5 (BDR-038): until Step 17, no screen edits sheet content.
Resolved (owner, 2026-10-25): no graphic editor that changes or publishes
anatomical content until Step 17; reference changes go through the curation
sources and the Rust pipeline, reviewed, tested and versioned. Annotating a
bilan is distinct from changing the anatomical reference and never touches
`curation/changes.json`.
2. Publication of the official equine sheet: the plan's Step 13 used to expect
"v1 published"; BDR-034 and BDR-037 keep it a draft until a platform admin
publishes after business review. Confirmed (owner, 2026-10-25): the equine
sheet stays a draft until business validation, and nothing publishes it
automatically. Still open for V1-2: who triggers the review, and whether
V1-2 may serve the unpublished draft to signed-in practitioners.
3. Recorded decision BDR-041 calls professional verification "Step 11"; the
plan numbers it Step 9. Resolved: the plan's numbering is kept and the
correction is the new entry BDR-072 (the registry is append-only, BDR-041
is not edited).
4. README, DEPLOY and CHANGELOG mixed the live 0.1.0 (local tool, no backend)
with the unreleased `develop` (Supabase, worker, Rust core). Resolved in P0:
README separates the public 0.1.0, `develop`, DEV-only features and planned
work; CHANGELOG keeps every unreleased change under `Unreleased`; DEPLOY
marks its historical, unverified and unsafe parts, and the CSP example as
not production-ready. The fixes themselves stay with TODO RR-5.
## A. Contradictions, ambiguities, risky decisions
### C1. Vertebral formula shape (architecture §7.2 vs §23.2)
+3 -3
View File
@@ -84,7 +84,7 @@ Known trade-off: a stamped PDF saved before this change (object streams)
hides its `/Keywords`, so a stripped attachment on such a file reads as
`no_attachment` instead of `attachment_stripped`.
## 5. Prerequisites before external users (Step 7+ sync, Step 14 worker)
## 5. Prerequisites before external users (Step 7+ sync; cloud import at Step 15, through the Rust worker or a Rust service)
- Option A merged and the CLI on the scanner; no `PDFDocument.load` on any
untrusted input in the browser.
@@ -108,7 +108,7 @@ hides its `/Keywords`, so a stripped attachment on such a file reads as
`endstream` search over candidates sorted by data offset and bounded to
the cap, and no JSON parse for a candidate not opening on `{` or nesting
brackets deeper than 64 levels (linear byte pre-scan, strings skipped).
- Option C or a server-side import (Step 14) with a hard memory and time
- Option C or a server-side import (Step 15) with a hard memory and time
budget per file, for any path that still parses PDF objects.
- Dependency decision on pdf-lib (unmaintained since 2021): closed at R4.8
(2026-10-19): pdf-lib left the repository with the TypeScript engine; the
@@ -155,7 +155,7 @@ only; a refused import leaves the tab's texts in place: app suites
| 12 | Report collection caps on read (observations, zones, findings per observation) | §5 item "collection caps" | before public exposure | out of R4 (plan A11); today bounded by `MAX_JSON_VALUES` (400,000 values, 10 × the CAP envelope of 500 observations: a report of about 5,000 observations at the CAP density at most) and by the export's caps (500 × 8 views, closed kind); a dense hostile report slows the editor but cannot exhaust it |
| 13 | `<use>` nesting and reference budget on the PDF path | §5 "remaining low findings" | fixed with proof | every SVG the export composes went through the core's one reader (R3: cycles refused, expansion > 50,000 elements refused, prescan caps); `ExportInput` runs `read_svg` per asset (R4.4); cargo `svg_sanitiser`, `pdf_layout` |
| 14 | PNG logo decoder envelope (4096² cap, four logos) | §5 "remaining low findings" | fixed with proof | the application exports the bundled logos only (`src/assets/brand`, never the archive's branding: `export_from_envelope` is cargo-only); the gate refuses above 8192 px a side, 4096² pixels or 16 MiB of raw scanlines before any allocation (`PNG_MAX_*`, cargo `pdf_png` 108 cases + budget cases); the session frees the planes at `add_raster` |
| 15 | Option C or a server-side import for any path that still parses PDF objects | §5 item 4 | before public exposure | no such path exists today; applies to Step 14 if a server-side reader is introduced |
| 15 | Option C or a server-side import for any path that still parses PDF objects | §5 item 4 | before public exposure | no such path exists today; applies to Step 15 if a server-side reader is introduced |
| 16 | pdf-lib (unmaintained since 2021) | §5 item 5 | fixed with proof | left the repository at R4.8; `r4.census` |
| 17 | Stamped PDFs saved with object streams (before Step 6) read a stripped attachment as `no_attachment` | §4 trade-off | accepted temporarily | pre-Step-6 files only, same outcome as a foreign PDF, no data at stake; documented in PDF-FORMAT |
| 18 | Imports offered to external users | §5 gate | before public exposure | the gate stays closed: the import is a local-tool feature; opening it needs items 3, 9 and 12 closed and a fresh audit of the worker path |
@@ -1,6 +1,11 @@
# Repository migration map
Status: Step 0 deliverable, 2026-10-08. Branch `develop` at `2ae1e48`.
Snapshot notice (2026-10-25, P0): every REMOVE / REPLACE verdict below has been
executed except `practitionerCache.ts` (still used by the local tool); the file
paths, counts and the `anatomical-sheets` bucket name are those of 2026-10-08
(the bucket is `anatomical-sheet-assets`). Kept as the record of the starting
point; `CLAUDE.md` holds the current map.
Sources: `faunosteo-business-architecture.md` (target), `docs/faunosteo-audit/`
(current behaviour, audited at `83e40af`), direct reading of `src/`, `public/`,
`docker/`, `tests/`, `scripts/`.
+9
View File
@@ -3,6 +3,15 @@
Status: Step 0 deliverable, 2026-10-08. Current state: 32 files under
`tests/unit/`, 180 `it(` cases, vitest 3 + happy-dom, no browser, no e2e
(audit 13). All green per TODO as of 2026-07-12; not re-run in Step 0.
Revised 2026-10-25 (P0): counts on `develop` (2026-10-25 inventory): vitest
app 446, core-wasm 60, supabase 40; cargo core 383, worker 33 native + 16
Docker sandbox; 11 pgTAP files under the flat `supabase/tests/`. The locations
`apps/app/tests/components`, `apps/app/tests/integration`, `apps/app/e2e`,
`supabase/tests/{db,rls}` and `supabase/seed/test/` in §1 and §3 are planned,
not created; the real-stack e2e lives in `packages/supabase/tests/e2e`. No
real-browser suite exists yet (TODO RR-8; V1-1 contract §8.4 proposes the
first one). No CI has ever run (BDR-047): "CI" in the tables means the
prepared workflow.
## 1. Layers
+496
View File
@@ -0,0 +1,496 @@
# V1-1 Clients and animals: functional contract
Status: proposal, 2026-10-25, revised the same day with the owner's
orientations (brief « P0 : arbitrages documentaires et finalisation du contrat
V1-1 »). Nothing is implemented and nothing is authorised: no migration,
table, RPC, RLS policy, component or route exists or may be created for this
step until the owner ratifies the orientations of §9.1 and answers §9.2. The
orientations are recorded as proposed, not ratified. Roadmap position:
`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also
lays the permission frame of Step 10. The file name keeps "OWNERS" so the
documents that cite it keep working.
Part 1 states the facts. Parts 2 to 7 are the proposed contract. Part 8 lists
the tests and the Definition of Done. Part 9 lists the orientations, the
sub-choices they leave, and the decisions still open.
---
## 1. Facts the contract rests on
| Area | State on `develop` (0c54e4b) |
|---|---|
| Client and animal data | Text inside a bilan only: report v3 `owner = { name }`, `animal = { speciesId, name, breed?, age? }` (`crates/core/src/domain/report/identity.rs`). No table. |
| Species | `public.species` (`id` slug, `name_fr`, `name_en`, `sort_order`, `active`), one row `equine` / Cheval / Horse; SELECT for `authenticated` on active rows; no API write path. |
| Anatomical sheets | Only the equine DRAFT exists, unpublished until business review (BDR-034, BDR-037). Its content changes only through `curation/changes.json` and the Rust pipeline until plan Step 17 (owner, 2026-10-25). |
| Accounts | Email/password sign-up, `enable_confirmations = true` (no session before the email is confirmed), `profiles.active` switched by staff only, `private.require_actor()` refuses a missing or deactivated actor. |
| Roles | `platform_role` = owner, admin, moderator, support (BDR-026). No professional status and no cabinet table exist. |
| Audit | `audit.audit_logs` append-only, written by `private.log_event()`, action format `domain.verb`. |
| Files | `client-files` and `animal-files` buckets exist, closed (row only, no policy). |
| UI | `/app` shell (sidebar, drawer, top bar), `Dashboard`, `Account`. The validated mockup (`docs/design/`) shows Clients and Animaux sidebar entries and a mobile tab bar Accueil / Bilans / Agenda / Profil. The shared `Dialog` has no focus trap or focus restore (RR-7). |
| Form validation | D-R7: form constraints stay TypeScript (Zod schemas returning i18n keys); a constants module is checked against `pg_constraint` by a PGlite test. The SQL CHECK is the server boundary. The 2026-10-25 inventory put V1-1 validation in `crates/core`: that contradicted D-R7 and is withdrawn here (EVAL-034). |
| Tests | pgTAP on PGlite and on the real stack; real-stack e2e pattern in `packages/supabase/tests/e2e`; no real-browser test runner in the repository (RR-8). |
---
## 2. Scope
In V1-1, a signed-in practitioner with a confirmed email:
1. creates, edits, lists, searches, archives and restores clients, persons
and organisations;
2. creates, edits, lists, searches, archives and restores animals, each
linked to zero, one or several clients with a role per link;
3. sees a client's animals and an animal's clients, current and former;
4. does all of it on a phone (375 px wide) and on a computer, in French and
English, with the keyboard alone and with a screen reader.
Out of scope, each named so nobody builds it early: cabinet creation and
membership management, sharing between practitioners, client portal and
client accounts, any directory or matching across practitioners, consent
records, photos, weight and files, imports (CSV, PDF), notifications, any
link with bilans (V1-3), account closure, deletion, anonymisation and export
(D9), quotas and billing, the professional verification process (plan Step
9), any staff access to the records (D16), any editing of the anatomical
reference. The local tool and the bilan format do not change; annotating a
bilan never changes `curation/changes.json`.
---
## 3. Workspaces and the future cabinets (D2, C4)
Orientation D2 / C4: records belong to a workspace. In V1-1 each practitioner
has one personal workspace. There is no global directory of clients shared
between practitioners. Multi-practitioner cabinets come later and are not
built in V1-1.
| Table | V1-1 content | Later |
|---|---|---|
| `workspaces` | `id`, `kind` (`personal` only), `created_at`; one personal workspace per profile, created with the profile (trigger + backfill of existing profiles) | `kind = cabinet`, name, logo: the plan's Step 10 builds cabinets as workspaces instead of a separate `organizations` table |
| `workspace_members` | `workspace_id`, `user_id`, `role` (`owner` only) | roles `manager`, `practitioner`, `secretary` added with the cabinet step |
One helper answers every access question: the caller's role in a workspace,
null when the caller is not a member or the profile is inactive. Policies and
RPCs never test `user_id = auth.uid()` on the record itself, so the cabinet step
adds members, not new policies on every table.
Why not a plain `owner_user_id` column: it is simpler today, but every policy
and helper of clients, animals and later bilans would need a second branch for
cabinets, and moving a practitioner's records into a cabinet would rewrite
ownership columns. The workspace costs two small tables now.
Record placement is explicit: the browser sends the target workspace on
create and the server checks the caller's role in it. In V1-1 the app always
sends the personal workspace.
---
## 4. Entities and fields
Vocabulary (orientation D1): the interface says « Clients » (English
"Clients") and the code entity is `clients`. A client is the person or the
structure the practitioner deals with. Its relation to an animal carries a
role: `owner` (Propriétaire), `keeper` (Détenteur, for example the stable that
boards the horse) or `contact` (Contact). The entity and the role are never
merged: the same client can own one horse and keep another.
### 4.1 Client
| Field | Rule | Required |
|---|---|---|
| `kind` | `person` (personne physique) or `organisation` (structure: écurie, haras, association, entreprise or another legal entity); defaults to `person` | column always set, nothing to type (D3) |
| `display_name` | person: the name as the practitioner writes it (« Marie Dupont »); organisation: its name (« Écurie du Lac »); 1 to 120 characters | yes, the only required input (D4) |
| `email` | practical address format, at most 254 characters, stored lower-case | no |
| `phone` | E.164 like `profiles.phone`; French national input (`06 12 34 56 78`) normalised to `+33…` on submit | no |
| `address_line1`, `address_line2`, `postal_code`, `city` | at most 120 / 120 / 16 / 80 characters, no postal format check (Belgium, Switzerland) | no |
| `country` | ISO 3166-1 alpha-2; no SQL default, the form proposes France | no |
| `notes` | private to the workspace, at most 4 000 characters | no |
| `archived_at`, `archived_by` | set by the archive RPC only | n/a |
Every text field is trimmed, refuses control characters and is never empty
when present. No uniqueness on email or phone: two clients may share a
household address or phone. Contact details are optional at creation (D4):
what a booking, an invoice or a regulated document requires is set by the
step that introduces it, never by a NOT NULL here.
### 4.2 Animal
| Field | Rule | Required |
|---|---|---|
| `species_id` | an active row of `species` (§4.4) | yes (D5) |
| `species_detail` | free text, 1 to 80 characters, required with `other` and refused with any other species | if `other` (D5) |
| `name` | 1 to 80 characters | yes (D6) |
| `sex` | `male`, `female`, `unknown`; defaults to `unknown` | column always set, nothing to type (D6) |
| `breed` | free text, at most 80 characters (no breed list in V1-1) | no |
| `birth_year` | four-digit year, not in the future | no |
| `birth_date` | the full date, only when it is known; not in the future; when present, `birth_year` equals its year (CHECK) | no |
| `neutered` | `yes`, `no`, `unknown`; together with `sex` it gives stallion, gelding, mare in the equine UI | no, proposal (D6a) |
| `identification` | microchip, UELN, tattoo: at most 64 characters, letters, digits, spaces and hyphens, stored upper-case; no per-species format check | no, proposal (D6a) |
| `colour` | at most 80 characters | no, proposal (D6a) |
| `notes` | private to the workspace, at most 4 000 characters | no, proposal (D6a) |
| `deceased_on` | date not in the future; a deceased animal stays readable and is never archived implicitly | no, proposal (D6a) |
| `archived_at`, `archived_by` | archive RPC only | n/a |
A year alone never becomes a date: an animal born « in 2015 » has
`birth_year = 2015` and no `birth_date`, never a stored 1 January (D6, D6b).
Deferred to a later step (D6): weight (it belongs to a visit, not to the
animal) and photo (it needs the `animal-files` rules and a worker job). The
fields marked « proposal » go beyond the owner's list of 2026-10-25; the
owner keeps or drops each before the migration (D6a).
### 4.3 Client and animal relation
Table `animal_clients` (orientation D7): `animal_id`, `client_id`, `role`
(`owner`, `keeper`, `contact`), `created_at`, `ended_at`. Rules:
- many-to-many: an animal links to several clients and a client to several
animals, each link with its role; co-ownership is several `owner` links,
and owner and keeper are distinct links;
- client and animal belong to the same workspace (composite foreign keys on
`(workspace_id, id)`);
- one current row per (animal, client, role) (partial unique index on rows
with no `ended_at`);
- no owner is required: an animal may have no current `owner` link, because
the owner is unknown or not entered yet. No SQL constraint and no RPC
refuses it, and the app never creates a placeholder client; it shows
« Propriétaire non renseigné ». Whether a business operation (bilan,
invoice, sharing) later requires an owner is decided by the step that
introduces the operation;
- ending a relation (horse sold, keeper changed) sets `ended_at`; the row
stays as history and the former owner or keeper is shown as such (D7a,
historical relations kept under D8).
### 4.4 Species
The species list is reference data written by migration (orientation D5):
the nine species of this contract's first version, horse (the existing row
`equine`), donkey, dog, cat, cattle, goat, sheep, pig and rabbit, plus
« Autre » (`other`) with its required `species_detail`. No other species is
added. The slugs of the new rows follow the format of the `equine` row and are
fixed with the migration.
A species carries no anatomical sheet by itself: an animal of any listed
species can be recorded while no usable sheet exists for it (today only the
equine draft exists), and nothing links a species to a sheet automatically.
V1-1 shows no sheet information; V1-3 decides what a bilan does for an animal
whose species has no sheet.
---
## 5. Permissions
### 5.1 Matrix
| Actor | Read | Create | Edit | Archive / restore | Delete |
|---|---|---|---|---|---|
| Workspace member with role `owner` (V1-1: the practitioner in their personal workspace) | yes | yes | yes, active records only | yes | no (§6) |
| Future cabinet roles `manager`, `practitioner`, `secretary` | per the cabinet step | per the cabinet step | per the cabinet step | per the cabinet step | no |
| Another signed-in account | no | no | no | no | no |
| Platform owner, admin, moderator, support | no | no | no | no | no |
| Deactivated profile | no | no | no | no | no |
| Anonymous | no | no | no | no | no |
Orientation C5: writes belong to the members who hold a write right in the
workspace concerned. In V1-1 that is only the practitioner who owns the
personal workspace. Future cabinets may add permissions (business
architecture §2.2: a secretary manages customers and animals); the helper's
shape allows them, and they are built with the cabinet step.
Orientation D16: Faunosteo staff have no ordinary business access to private
records. No platform role (owner, admin, moderator, support) reads or writes
clients, animals or bilans through a policy or an RPC, and no admin screen
lists or opens them. That rule is distinct from exceptional privileged
technical operations (database maintenance, backup restore, incident response
through the service key or a database superuser): those exist by construction
of the hosting, and before any publication a separate contract frames,
justifies and audits them. V1-1 creates no exceptional access mechanism (no
impersonation, no break-glass RPC), and no worker job reads these tables.
### 5.2 Verification (C6)
Orientation C6: email confirmation and professional verification are two
distinct things. An account with a confirmed email has private use of the
application, within the permissions and features available: V1-1 is open to
any active account with a session (GoTrue gives no session before
confirmation). Professional verification (plan Step 9; BDR-041 said Step 11,
corrected by BDR-072) is required for the public features that present a
practitioner as a verified professional (public profile, community
publication, booking); it is not built in V1-1 and does not gate it.
Professional statuses (practitioner, student, professor) come from
verification and are never platform roles (BDR-026).
### 5.3 Edits and finished bilans (C5)
V1-1 holds no bilan. The rule binds V1-3: a bilan keeps its own identity
snapshot (already true of the report v3 format); editing an animal or a client
never rewrites a finished bilan, retroactively or silently. Any refresh of a
draft bilan from the animal record is an explicit user action.
### 5.4 Server rules
- Reads: SELECT policies on `clients`, `animals`, `animal_clients`,
`workspaces`, `workspace_members` through the workspace helper, explicit
column lists in the app (no `select=*`).
- Writes: security-definer RPCs only (create, update, archive, restore, link,
end a link). No INSERT, UPDATE or DELETE grant on these tables for API roles.
Each RPC calls `private.require_actor()`, checks the role in the target
workspace, answers the same 42501 for an unknown id and a forbidden id, and
writes one `log_event` row with ids and changed field names, never names,
contacts or notes.
- Concurrency: update RPCs take the `updated_at` the form loaded and refuse a
stale write with a closed `conflict` kind, so two tabs never overwrite each
other silently.
- Archived records are read-only until restored.
- Helpers in `private` follow the project rule: security definer,
`set search_path = ''`, EXECUTE revoked from public, granted only where
evaluated; census tests updated.
---
## 6. Archive, deletion and privacy
### 6.1 Archive (D8)
Archiving is a functional state, read-only and reversible. It hides a record
from default lists and search, keeps it readable from its page and from the
« archived » filter, and refuses edits until the record is restored. Restore
is always possible. Relations are kept: an archived client stays on its
animals' pages, marked archived. Archiving a client never archives its animals;
the confirmation lists the active animals for which it is the only current
owner.
Archiving erases nothing. It is not the deletion or anonymisation of personal
data (§6.2), and no retention duration is attached to it.
### 6.2 Account deletion and the data lifecycle (D9)
V1-1 implements no account closure, deletion, anonymisation or export, and
sets no retention duration. Orientation D9: no rule may block the deletion of
an account for good because it holds data. A later lifecycle contract (plan
Step 26, BDR-033 point 7) will distinguish closing the account, deleting or
anonymising personal data, keeping some data where a justification exists,
the records of a workspace shared by a cabinet, and the legal obligations
that apply. The owner sets the retention durations and the erasure policy;
nothing here presumes them.
What V1-1 does so that contract stays possible:
- records belong to a workspace, never to a user column, so a cabinet's
records survive a member leaving, and a personal workspace can be exported,
anonymised or erased as one unit;
- authorship columns (`archived_by`, audit rows) hold ids only, never names,
so anonymising a profile rewrites no record;
- a client's personal data sits in the identified columns of one table, with
no copy in audit rows, logs or URLs, so erasure or anonymisation is a
bounded update.
The one technical choice before the migration is how the database behaves
when an auth user whose personal workspace holds records is deleted in DEV
(D9a, §9.2).
### 6.3 Privacy, legal basis, information
To frame with legal counsel before any public exposure (business
architecture §28); nothing here decides it:
- likely roles: the practitioner or cabinet is the controller of client and
animal records, Faunosteo its processor, which needs processor terms in the
conditions of use;
- the legal basis is not presumed to be consent. The likely basis for client
identity and contact data is the care contract between practitioner and
client and the practitioner's legal obligations (invoicing). Consent would
apply to optional purposes only (marketing, sharing with another
practitioner), none of which V1-1 implements;
- clients must be informed (GDPR articles 13 and 14): the information text,
and whether the app records that it was given, is decision D10. V1-1 shows
nothing to clients;
- retention durations belong to the lifecycle contract (§6.2);
- minimisation: the field list of §4 is closed; the notes fields carry a hint
to record only what the care needs;
- no personal data in URLs (ids are uuids; the search term is never put in the
query string), in audit rows or in application logs; search goes through a
POST RPC so the term stays out of access logs.
---
## 7. Screens and journeys
Routes (English, like the existing `/app/dashboard` and `/app/account`):
| Route | Content |
|---|---|
| `/app/clients` | list (name, kind, city, phone, animal count), search, archived filter, « new client » |
| `/app/clients/new` | form; optional « add a first animal » section in the same flow |
| `/app/clients/:clientId` | identity and contact, animals with their role (current and former), edit, archive or restore, add an animal |
| `/app/animals` | list (name, species, breed, sex, owners or « Propriétaire non renseigné »), search, species and archived filters, « new animal » |
| `/app/animals/new` | form with optional client selection or inline client creation; prefilled when opened from a client |
| `/app/animals/:animalId` | identity, owners, keepers and contacts (current and former), edit, archive or restore |
An unknown id and a forbidden id show the same « not found » screen.
Journeys:
1. New client calling about a horse: Clients → new client → type the name,
add the first animal in the same form → save → client page with the animal.
2. Find an animal from a phone in a stable: Animaux → type part of the name or
the identification → open the animal → see owners and keeper with the phone
as a `tel:` link.
3. Horse sold: animal page → add the new owner → end the old owner's relation
→ the old client stays, with its other animals, and appears as former owner
on the horse's page.
4. Owner unknown: a rider brings a horse without its owner's details → the
animal is created with no client → its page and the list show
« Propriétaire non renseigné », no placeholder client exists → the owner
is added later.
5. Client archived: the confirmation lists the animals for which it is the
only current owner → archived → hidden from lists, visible under the
archived filter, still shown on its animals' pages, restorable.
6. Animal deceased, if `deceased_on` is kept (D6a): mark deceased with a date
→ the animal stays in lists with a « deceased » badge.
Desktop: the sidebar entries Clients and Animaux of the validated mockup become
active; list and detail use the existing `Card`, `FormField` and `Button`
components; no new visual direction. Mobile: single column, rows as cards with
44 px targets, forms as full pages (no modal form), save bar reachable with
the keyboard open. The tab bar question is decision D11; dashboard tiles are
decision D12.
Accessibility applied in V1-1, not deferred to V1-5: every field labelled,
errors linked with `aria-describedby` and announced, focus moved to the first
error on submit and to the page heading on navigation, visible focus, no
action reachable only by pointer, confirmation dialogs with focus trap and
focus restore (decision D13), an axe check per screen in the browser tests.
Unsaved form changes ask before leaving. Failure kinds are closed and phrased
by i18n (FR and EN), like the auth and asset failures.
---
## 8. Tests and Definition of Done
### 8.1 SQL (pgTAP, PGlite and real stack)
- RLS enabled, no API write grant, explicit column grants; census tests
(`001`, schema↔types) updated.
- Allowed and denied per actor of §5.1: member reads and writes; second
account, anonymous, deactivated account and each platform role read
nothing and every RPC refuses with 42501; unknown id and forbidden id give
the same error.
- Every CHECK of §4 accepted at its bound and refused one step past it; a
client with only a display name accepted; `species_detail` required with
`other` and refused otherwise; a `birth_date` whose year differs from
`birth_year` refused, a `birth_year` alone accepted.
- Same-workspace link rule; an animal with no owner link accepted; a second
current (animal, client, role) row refused; an ended relation kept and
readable; archived records refuse edits; archiving a client leaves its
animals and links unchanged; stale `updated_at` refused.
- Audit rows written for each RPC, with no name, contact or note in them.
- Personal workspace created for a new profile and backfilled for existing
ones; the D9a behaviour as decided.
### 8.2 Cross-account on the real stack
An e2e file beside `avatar-flow.e2e.ts`: two users created through the admin
API on the local stack; A creates a client and an animal; B lists (empty),
reads by id (nothing), updates, archives, links (42501); the anon key reads
nothing; A deactivated by SQL loses access. Run by `pnpm` script on the DEV
origin.
### 8.3 Application
- Unit and component tests: form schemas (each rule, i18n keys), list and
search states (empty, results, error), archive and restore flow, conflict
message, « Propriétaire non renseigné » state, route guard, i18n key parity.
- Constraint parity test (D-R7): the TypeScript constants equal the SQL CHECK
bounds read from `pg_constraint` on PGlite.
### 8.4 Real browsers
A Playwright suite under `apps/app/e2e` (decision D14: `@playwright/test`
and `@axe-core/playwright` as dev dependencies), run against `pnpm dev` and
the local stack on the DEV origin:
- desktop Chromium, Firefox and WebKit; phone viewports 375 × 667 and
412 × 915;
- journeys 1 to 6 of §7;
- the creation journey with the keyboard only;
- two browser contexts: B opens A's client URL and gets « not found »;
- no client or animal name in any URL;
- an axe scan on each screen, zero serious or critical violation.
Then the owner's manual check on a real phone and a computer over the LAN.
### 8.5 Definition of Done
All tests above green; `pnpm check:all`; `pnpm db:reset && pnpm db:test`;
regenerated `database.types.ts`; fresh verifier and security gates; docs
(a domain document for clients and animals, CLAUDE.md folder map and
architecture, `docs/design/README.md` owners table); report format, PDF,
sheets and local tool unchanged; nothing deployed, Supabase DEV untouched
outside `db:reset` of the local stack.
---
## 9. Orientations and decisions
### 9.1 Owner orientations of 2026-10-25 (proposed, awaiting ratification)
All are needed before the first migration. « SQL » marks an orientation that
fixes a table shape or a constraint, « permissions » one that fixes a policy
or an RPC check.
| Id | Orientation | Impact |
|---|---|---|
| D1 | Interface term « Clients »; Propriétaire, Détenteur and Contact are roles of the relation to an animal; the client entity is never confused with its role | SQL: table `clients`, link roles `owner` / `keeper` / `contact` |
| D2 / C4 | `workspaces` and `workspace_members`; one personal workspace per practitioner in V1-1; records attached to a workspace; no global client directory; cabinets later, not built in V1-1 | SQL and permissions: every policy and RPC goes through the workspace helper |
| D3 | Persons and structures (écuries, haras, associations, entreprises, other legal entities), with an explicit distinction in the model | SQL: `kind` column and CHECK |
| D4 | The display name or company name is the only required field; contact details optional at creation; later steps set their own requirements | SQL: one required column; no NOT NULL on contact columns |
| D5 | The nine species of this contract plus « Autre » with a detail; no new species; no automatic sheet per species; a species may exist with no usable sheet | SQL: reference rows by migration; `species_detail` CHECK |
| D6 | Name and species required; sex with `unknown`; breed optional; birth year optional; a full date when known, never invented from a year; weight and photo deferred | SQL: `sex` CHECK and default; `birth_year` / `birth_date` coherence CHECK |
| D7 | Many-to-many relation with an explicit role per link; co-ownership; owner unknown or not entered allowed with no fake client; no SQL rule forcing an owner while that is undecided | SQL: link table with no minimum-owner constraint |
| D8 | Archive read-only and reversible; historical relations kept; no cascade from a client to its animals; no retention duration; archive is not erasure | SQL and permissions: `archived_at` columns, RPCs refuse edits on archived rows |
| D9 | No rule blocking an account's deletion for good; a later lifecycle contract (closure, deletion or anonymisation, justified retention, cabinet records, legal obligations); nothing implemented in V1-1, nothing in the model preventing it | SQL: delete behaviour of the keys to the profile (D9a) |
| D16 | No ordinary staff access to private records; no admin screen on clients, animals or bilans; exceptional technical operations framed, justified and audited before publication; no exceptional access mechanism in V1-1 | permissions: no platform-role branch in any policy or RPC |
| C5 | Writes reserved to workspace members with a write right; in V1-1 only the practitioner in their personal workspace; finished bilans never changed retroactively or silently | permissions |
| C6 | Email confirmation distinct from professional verification; a confirmed email gives private use; verification required for public professional features; statuses are not platform roles; verification process not built now | permissions: the V1-1 gate is an active session |
### 9.2 Sub-choices the orientations leave open (SQL, before the migration)
| Id | Question | Recommendation | Alternative |
|---|---|---|---|
| D4a | Structured first and last name for persons | not in V1-1: one `display_name`; nullable columns can be added later without touching existing rows | a required `last_name` for persons (a second required field, against D4) |
| D6a | Fields beyond the owner's list: `neutered`, `identification`, `colour`, `notes`, `deceased_on` | keep all five, optional | drop any of them; adding one later is an additive column |
| D6b | Birth date model | `birth_year` plus an optional `birth_date`, with the coherence CHECK | one `date` with a precision flag: stores an invented day for a year-only birth, which D6 refuses |
| D7a | Ending a relation | `ended_at` on the link, the row kept as history | delete the row; the history then survives only as ids in the audit log |
| D9a | Deleting, in DEV, an auth user whose personal workspace holds records | a temporary guard refuses it, replaced by the lifecycle contract; an account with no record is deleted as today | cascade (erases the records with the account, deciding the policy early) or keep an orphaned workspace (records nobody can read) |
### 9.3 Decisions still open
Not arbitrated by the owner; status open, recommendation and impact given.
Before the RPCs are written (they change server behaviour):
| Id | Decision | Recommendation | Impact |
|---|---|---|---|
| D15 | Abuse guard | per-workspace caps (20 000 clients, 50 000 animals) refused by the create RPCs | RPC behaviour, no table change |
Before or during the interface work (no table impact):
| Id | Decision | Recommendation | Impact |
|---|---|---|---|
| D10 | Client information notice: text, and whether the app records that it was given | decide with the legal texts; nothing recorded in V1-1 | none in V1-1; recording it later adds a column; required before public exposure |
| D11 | Mobile navigation | drawer only in V1-1; the tab bar of the mockup arrives with Bilans (V1-3), since two of its four entries would lead nowhere today | UI |
| D12 | Dashboard tiles | show the two real tiles (clients, animals) now; bilans and appointments when their tables exist | UI |
| D13 | Shared `Dialog` focus trap and restore | fix it in V1-1 (it also improves the editor dialogs; partial RR-7) | UI, shared component |
| D14 | Real-browser test tooling | add `@playwright/test` and `@axe-core/playwright` as dev dependencies | manifest and lockfile change at implementation |
| D17 | Bridge to the local tool (« start a bilan for this animal », prefill only) | no: V1-3 links bilans to animals properly; a prefill now would be a second path to delete later | none |
### 9.4 Never assumed, framed before any public exposure
The legal basis of the processing (consent is not presumed to be required),
the information given to clients, the retention durations, the deletion and
anonymisation rules, the legal qualification of each party. None of them
blocks a DEV implementation once §9.1 is ratified; each blocks any public
exposure.
Ratifying §9.1, answering §9.2 and settling D15 unlock the first migration,
on a `feature/` branch off `develop`.