Files
faunosteo/docs/development/IMPLEMENTATION_PLAN.md
bchanot bc6a7ddb6f docs(docs): V1-1.4 animals and relations as built, DEV procedure to M3
Contract §8.3 (differences, relation states, caps, lock order across M2 and
M3, concurrency results, migration states, mutations, residuals), helpers
and derived values; SUPABASE.md §3.3 procedure from DEV's current state to
M3 (not run) and §3.5; TEST_STRATEGY, plan note, backend table, CLAUDE.md.
2026-10-26 01:06:24 +01:00

752 lines
62 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Faunosteo SaaS: implementation plan
Status: Step 0 deliverable, 2026-10-08. Main document of `docs/development/`.
Companion documents: `REPOSITORY_MIGRATION_MAP.md` (what happens to each
current file), `DOMAIN_MAP.md` (future domains), `FRONTEND_ARCHITECTURE.md`,
`BACKEND_ARCHITECTURE.md`, `MIGRATION_STRATEGY.md` (how modules evolve),
`TEST_STRATEGY.md`, `OPEN_QUESTIONS.md` (contradictions and questions).
Reference product/architecture: `faunosteo-business-architecture.md`
(2026-10-07). Reference of current behaviour: `docs/faunosteo-audit/`
(frozen at `83e40af`). The code is the source of truth for what the app
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
the architecture document (§35). The mapping to those sprints is given in
§6.
- Every step is a testable deliverable: it ends in a known state with
automated tests, a manual validation script and a Definition of Done. No
step is "half of a feature".
- Steps marked `∥` can run in parallel with the step named.
- Each step is one gitflow branch (`feature/<nn>-<slug>` off `develop`,
merged on explicit human signal); long steps may be split into
sub-branches that each leave `develop` green. Branch names are in §7.
- The invariants of the brief (§18 rules 1–8, §19 security) are restated at
the step where they become enforceable.
- Effort is not estimated in hours here; the "size" column in §5 gives a
relative order of magnitude.
## 2. Guiding principles for every step
1. `pnpm typecheck && pnpm test:run && pnpm lint` green before any commit; for
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 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.
## 3. Steps
```text
Step 0
Name: Preparation and technical plan
Objective: Confront target architecture, audit and code; produce docs/development/.
Dependencies: none
Changes expected: docs/development/* only (this set). No application file.
Tests: none
Manual validation: documents reviewed by the developer; open questions answered or deferred explicitly.
Definition of Done: the 8 documents exist; Step 1 can start without further analysis.
Risks: plan built on an audit frozen at 83e40af; two later commits (audit merge, hooks) do not touch src/.
Status: DONE 2026-10-08.
```
```text
Step 1
Name: Characterisation tests on the current application
Objective: Pin the behaviour that the migration must preserve, on real data, without changing application code.
Dependencies: Step 0
Changes expected:
- tests/unit/*: click chain (onZoneClick branches), spine sync on real Horse.svg,
SVG ↔ catalog strict mapping table (27 annotations → 26 zones), opens-detail ↔
manifest coherence, matcher parity app vs pathology-editor.html, catalog copies
byte parity, catalog invariants (incl. the sphenoid/ssb-dysfunctions anomaly
asserted as known), full PDF roundtrip with every zone kind + text assertions,
traverseForJsonAttachment fallback, orphan findings behaviour, registry/AnimalForm.
- tests/fixtures/report-v2.full.json, report-v2.minimal.json (golden).
- README test count corrected (174 → actual).
- No file under src/ or public/ changes.
Tests: the new tests themselves; existing 180 untouched and green.
Manual validation: pnpm test:run shows the new count; open one golden fixture and check it describes a realistic report.
Definition of Done: ≈230–250 green cases; TEST_STRATEGY.md §2 table fully checked; CI (if present) green.
Risks: happy-dom limits on canvas/Image for the roundtrip (mitigation: deterministic rasterizer stub + a separate Playwright check later); tests that encode a bug as expected behaviour must be labelled "known" in their name.
```
```text
Step 2
Name: Monorepo workspace
Objective: Move the app to apps/app under a pnpm workspace with zero behaviour change; add CI.
Dependencies: Step 1
Changes expected:
- apps/app/{src,public,tests,scripts,index.html,vite.config.ts,vitest.config.ts,tsconfig*.json,eslint.config.js,package.json}
- root: pnpm-workspace.yaml (apps/*, packages/*), package.json scripts delegating
(pnpm -r typecheck/test:run/lint/build), engines + packageManager, Node 24 pins.
- Dockerfile build context and paths updated; docker/nginx.conf and entrypoint.sh unchanged.
- CI pipeline (.gitea/workflows/ci.yml): install, typecheck, test, lint, build (+ docker job).
- packages/ holds only a README (no empty package).
Tests: full suite green from the root; dist contains the static editor and species assets.
Manual validation: docs/development/WORKSPACE.md §6.
Definition of Done: identical behaviour, same test count, CI file present, docs synced (WORKSPACE.md, CLAUDE.md, README, DEPLOY.md, CHANGELOG).
Risks: path regressions (caught by the suite + dist listing); Docker build not verifiable on a host without a Docker daemon.
Status: DONE 2026-10-08 (branch feature/step-02-monorepo-workspace, uncommitted, awaiting validation).
Facts: 144 files moved with git mv; 271/271 tests, typecheck, lint, build green from the root;
Node 24 LTS adopted (Node 20 EOL 2026-04-30); pnpm 10.13.1 pinned (packageManager + root devDependency);
lockfile rewritten by pnpm 10.13.1 (libc fields left by an earlier pnpm 11 dropped).
Side note: the gitflow finish of Step 1 purged docs/superpowers/{specs,plans} (lib rule BDR-065,
commit 8f217d8 on develop); restored under docs/history/superpowers/ (same path would be purged again).
```
```text
Step 3
Name: Supabase foundation
Objective: Local Supabase stack, migration system, test harness, generated types, first protected table, audit log skeleton.
Dependencies: Step 2. Deployment target depends on OPEN_QUESTIONS Q2 (local work is unaffected).
Changes expected:
- supabase/config.toml, supabase/migrations/0001_foundation.sql: schemas private/audit,
updated_at trigger, private.log_event(), audit.audit_logs (append-only), profiles table
+ auth.users trigger + RLS (own row), private.is_platform_owner/admin/moderator/support
reading profile_roles (table created here, writes only via RPC stub).
- supabase/tests/: pgTAP harness, tests for profiles RLS and role helpers.
- packages/supabase: browser client factory, generated database.types.ts, CI diff check.
- packages/config: runtime config keys supabaseUrl/anonKey (env.js + entrypoint.sh extended).
- CI: supabase start, db reset, test db, gen types diff.
- .env.example: placeholders only.
Tests: pgTAP green; a vitest integration test signs in a seeded user and reads only their profile.
Manual validation: supabase start; create two users in Studio; verify each sees one profile row via the REST API with their JWT; anon sees none.
Definition of Done: "authenticated request can hit a protected table safely" (architecture Sprint 0 exit criteria); docs/development/BACKEND_ARCHITECTURE.md conventions applied.
Risks: self-hosted vs managed decision (Q2) changes the deploy runbook, not the code; pgTAP learning curve; Supabase CLI version pinned in package.json devDependencies.
```
```text
Step 4 (∥ Step 3)
Name: Canonical anatomical sheet model and legacy importer
Objective: Define the AnatomicalSheetDocument (pure Zod) and build the deterministic importer that turns the two equine SVGs + catalog into a seed document with stable ids and explicit mappings.
Dependencies: Step 1 (mapping table and special-case tests), Step 2 (workspace)
Changes expected:
- packages/domain: sheet document schema (schema_version, species_id, vertebral_config as ordered region list, views, annotations, categories, finding_tree reusing findings.ts, annotation_finding_map, scope_disclaimer, legacy_id_map), species schema.
- packages/anatomy: svgConvention.ts and labels.ts moved; legacy/ importer (uses zoneMatch and regionFromLabel once); renderer helper that emits data-anno-* from a document; spineZones generalised to region codes (old label-based function kept in legacy/).
- supabase/seed/anatomical-sheets/equine/v1/{document.json, legacy-id-map.json, assets/, IMPORT-REPORT.md} generated by a script (pnpm seed:equine), checksums of source SVGs recorded.
- Decisions on OPEN_QUESTIONS Q5 and Q9 applied in the importer (defaults: two assets; ssb-dysfunctions under sphenoid renamed with a logged note).
- apps/app untouched (still uses the registry).
Tests: importer reproduces the Step 1 mapping table exactly; every audit 07 special case has a test; document Zod rejects duplicate annotation ids, dangling view parents, mapping to unknown zones, published schema mismatches; idempotency (running twice yields byte-identical output).
Manual validation: open IMPORT-REPORT.md: 27 annotations, 26 mapped, 1 detail trigger, 5 spine zones with region codes C/T/L/S/Cd, 9 bilateral, 2 views; diff document.json against docs/faunosteo-audit/anatomical-sheet-example.json for sanity.
Definition of Done: seed document committed; packages/domain and packages/anatomy have no DOM import outside anatomy/dom/*; no runtime code imports zoneMatch outside legacy/.
Risks: subtle divergences between parser and importer on the detail trigger (no name, category kept); Horse_head.svg id space overlaps if a future file reuses ids (mitigated by per-view id scoping in the importer).
Adjustment 2026-10-08 (user brief for Step 4): the step is split. Step 4 = model, validation,
persistence foundations and tests (packages/domain, migration 20261008110000_anatomical_sheets,
pgTAP 005, docs/development/ANATOMICAL_SHEET_MODEL.md). Step 4b = legacy importer producing the
official equine sheet as a DRAFT with an import report, published only after business review.
packages/anatomy is created at Step 4b. Labels use `{ fr, en }` objects, annotation→findings is
`finding_zone_id`, finding categories carry a `kind`; see the spec for the final field names.
Step 4b done 2026-10-09: packages/anatomy importer + `pnpm import:equine`, seed
supabase/seed/anatomical-sheets/equine/v1 (draft, not published), Storage bucket + policy
(migration 20261009100000), pgTAP 006/007. Business decisions of 2026-10-09 recorded in
ANATOMICAL_SHEET_MODEL.md §5 (follow-gated use → community step; verified publication →
identity step; erasure path → retention step).
Step 4c done and validated by the user 2026-10-10 (branch feature/step-04c-equine-curation, finished into develop):
document schema v2 (references registry, review_status, vertebral count_range; migration
20261010100000, pgTAP 008), curation pipeline in packages/anatomy (changeset → draft with
CHANGELOG, REVIEW-REPORT, before/after review drawings), seed layout legacy-import/ + curation/ +
draft/ (the `v1/` folder is gone), research-backed audit of the equine sheet (44 changes, 48
references, levels A/B/C, nothing published), Docker naming convention (BDR-035).
Step 5 preparation 2026-10-10: docs/development/STEP5_MIGRATION_ANALYSIS.md (Report v3 shape,
v2→v3 adapter fed by a generated report-migration-map, bundled SheetProvider, annotation layer
renderer reproducing the legacy markers, interaction service + store split, PDF shim with
attachment v3, replace-or-refactor table, risks, tests, 8 decisions D1–D8). Awaiting validation;
the orientations below supersede "annotation_finding_map" (inline finding_zone_id, BDR-031) and
"locale of last export" (locale stays out of the report, BDR-014).
Step 5 done 2026-10-10 (branch feature/step-05-app-on-canonical-sheet, awaiting user validation):
Report v3 + v2 migration (packages/domain/report), report-migration-map + sheet-ref + app review
drawings from the pipeline, annotation layer renderer (@faunosteo/anatomy/render), bundled
SheetProvider (SHEET_BUNDLE), zoneInteraction service, store on v3 with persistence adapter, PDF v3
with v2 archive import, legacy registry / matchers / editors / public species assets removed
(legacy sources moved under the seed). Visible changes limited to the validated 4c content and D6/D7.
```
```text
Step 5
Name: Application on the canonical sheet (local, no backend)
Objective: Make apps/app run on the seed document instead of the manifest/registry, with report document v3 and the zone-interaction service extracted. Still single-user, still sessionStorage.
Dependencies: Step 4
Changes expected:
- packages/domain: report document v3 (zones by annotationId+viewId, region codes, anatomicalSheetVersionId, identity snapshots, localAnnotations, locale of last export); v2ToV3 adapter using legacy-id-map; v2 schema retained as input.
- apps/app: SheetProvider interface with a bundled implementation over the seed; AnatomyCanvas/DetailModal on views; ObservationCard uses annotation_finding_map (matcher import removed); VertebraPicker tabs from vertebral_config; services/zoneInteraction.ts extracted from EditorRoute and unit-tested; reportStore split (pure actions + sessionStoragePersistence adapter) and holding v3; draft migration on load; registry.ts and species/equine/* deleted (SvgEditorRoute and AnimalForm read SheetProvider).
- PDF still works through a thin shim (labels from the document) until Step 6; no public/species fetch remains except the SVG asset bytes served from public/ until Step 13.
Tests: Step 1 characterisation tests pass unchanged or are migrated one-to-one with the replacing test named; v2ToV3 on golden fixtures; zoneInteraction service tests (all branches); no-import-of-zoneMatch lint test.
Manual validation: full manual flow (new report → zones of each kind → findings → PDF export → import) in FR and EN; refresh keeps the draft; a v2 draft left in sessionStorage is migrated.
Definition of Done: identical user-visible behaviour; registry gone; EditorRoute under 300 lines; CLAUDE.md folder map updated.
Risks: largest refactor of the app core; mitigated by Step 1 tests and by keeping the shim for PDF; v2 drafts in the wild (none expected).
```
```text
Step 6
Name: PDF pipeline v3 (snapshot-based export, attachment v3, import)
Objective: Export from (document, sheet snapshot, branding, locale) with no fetch; attachment carries sheet reference and snapshot; import v3 and v2.
Dependencies: Step 5. Gate: explicit confirmation before editing pdf/import.ts and pdf/attachment.ts (CLAUDE.md).
Changes expected:
- packages/pdf: export/import/attachment/render moved; new signature; Branding object replaces hard-coded logos/URLs; Rasterizer interface with the browser implementation; attachment v3 format documented in docs/PDF-FORMAT.md (written for real).
- apps/app: export passes the snapshot from SheetProvider; import detects v2 vs v3 and routes v2 through v2ToV3.
Tests: golden text extraction for the full fixture (FR/EN); attachment v3 roundtrip; render with a snapshot only (no provider) proves rule 8 feasibility; v2 PDF from Step 1 fixture imports and re-exports as v3; vet marker still WinAnsi-safe.
Manual validation: export the demo report, open in two viewers, check pages, open the attachment list and confirm osteo-report*.json; import the file on a fresh tab; import a v2 PDF produced before Step 5.
Definition of Done: no fetch in packages/pdf; docs/PDF-FORMAT.md complete; size of attachment < 250 KB for the equine demo.
Risks: snapshot size growth with future sheets (mitigate: snapshot subset = only views and annotations referenced + finding zones referenced); viewers that strip attachments (visible PDF remains the archive).
```
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. 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
Name: Identity: Auth, profiles, roles, app shell
Objective: Login, email verification, profile, roles; the private app gains the /app shell and a query layer.
Dependencies: Step 3, Step 2
Changes expected:
- supabase: migrations for profile_roles RPCs (grant/revoke by owner/admin only), platform_invitations, MFA enforcement helper for admin roles; GoTrue config: email/password, OTP, Google, Apple (provider ids from env), phone (per OPEN_QUESTIONS Q7, may ship later).
- apps/app: /login, /app/* guarded routes, /app/dashboard (empty), /app/profile/edit; TanStack Query added (dependency declared); session handling; locale synced to profiles.locale; legacy routes still reachable and unauthenticated (local tool mode) until Step 14.
Tests: pgTAP for roles RPC (self-grant denied, admin grant audited); integration: sign-up → verify → login → profile update; component tests for forms.
Manual validation: create account, verify email (Inbucket locally), log in with Google (test credentials), edit profile, log out; confirm an unauthenticated user cannot read profiles via REST.
Definition of Done: architecture Sprint 1 identity part; audit_logs receives role changes.
Risks: Apple sign-in setup cost; phone provider pending (Q7).
```
Step 7 implementation note (2026-10-11): shipped as `docs/development/IDENTITY.md`.
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 9);
Google/Apple wired in config.toml behind env ids, buttons behind `APP_AUTH_PROVIDERS`.
```text
Step 8
Name: Files foundation (Storage)
Objective: Asset metadata table, private buckets, object key convention, signed URL RPC, storage.objects policies, SVG quarantine/sanitizer.
Dependencies: Step 7
Changes expected:
- supabase: assets table (+ sanitization_status), buckets created by migration, storage policies calling private helpers, RPC issue_signed_url(asset_id), Edge Function or SQL-only sanitizer for SVG (decision at the step: SQL cannot parse XML safely; prefer an Edge Function or the worker if Q2 rules out edge-runtime).
- packages/supabase: upload helper (client → bucket path from assets row).
- apps/app: avatar upload on the profile page as the first consumer.
Tests: pgTAP: a user cannot read another user's object; quarantined SVG unreadable by others; signed URL denied without access; unit tests for the sanitizer on hostile SVG fixtures (script, foreignObject, on*, javascript:, external use/href, CSS url()).
Manual validation: upload avatar; copy the object URL and open it logged out (denied); upload a hostile SVG as a sheet asset and verify it is rewritten.
Definition of Done: all eight buckets exist and are private; architecture §15.1–15.3 implemented.
Risks: direct-to-bucket uploads bypassing the assets row (mitigate: insert policy on storage.objects requires a matching assets row).
```
Step 8 as built (2026-10-13, `STEP8_FILES_ANALYSIS.md` D1–D9 + Rust R1,
`STORAGE.md`): the server-side processing is the Rust worker `crates/worker`
(the plan's `apps/worker` of Step 19 arrives early, in Rust, with one job
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 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`.
```text
Step 9 (∥ Step 10)
Name: Professional verification
Objective: Verification workflow with documents, admin review, expiry.
Dependencies: Step 7, Step 8
Changes expected:
- supabase: professional_verifications, professional_documents, status RPCs (submit, review), expiry job (pg_cron or SQL function called by the future worker), audit events.
- apps/app: /app/profile/verification (submit SIRET, identifiers, upload RC Pro/C2V), /app/admin/verifications (review list, approve/reject with reason).
Tests: pgTAP for transitions (only admins review; user cannot set verified), document expiry moves status to expired; integration for the full flow.
Manual validation: submit as practitioner, review as admin, see the badge; backdate a document expiry and run the job.
Definition of Done: unverified accounts blocked from the capabilities decided in OPEN_QUESTIONS C6.
Risks: legal acceptance criteria not final (documents list may change: keep document_type open text + CHECK).
```
```text
Step 10 (∥ Step 9)
Name: Organizations (cabinets)
Objective: Organization creation, membership roles, personal vs organization context in the app.
Dependencies: Step 7
Changes expected:
- supabase: organizations, organization_members, RPCs add_member/remove_member/set_role, helpers is_org_member/manager/practitioner, seat exclusivity constraint (one cabinet-paid seat per user, enforced at Step 11 with billing_source).
- apps/app: /app/settings/organization, member management, context switcher (personal / cabinet) stored in session.
Tests: pgTAP: secretary cannot self-promote; non-member sees nothing; manager manages; integration: create cabinet, invite by email, accept.
Manual validation: two accounts, one cabinet, switch context, verify visibility of the other member's profile only.
Definition of Done: architecture Sprint 2 minus seats billing.
Risks: context leakage into later queries (every report/client query must take the context explicitly; enforce by a service-layer signature, not a global).
```
Step 10 note (2026-10-25): with C4 ratified (BDR-073), cabinets are built as
workspaces of kind `cabinet` on the `workspaces` / `workspace_members` tables
that V1-1 creates, not as separate `organizations` / `organization_members`
tables; cabinet roles extend `workspace_member_role` and plug into the V1-1
workspace helpers (`V1-1_OWNERS_ANIMALS.md` §3, §4, §9.1). The rest of the
step (member management, context switcher, seats) is unchanged.
```text
Step 11
Name: Entitlement engine skeleton (no Stripe)
Objective: plans, entitlement_grants, get_effective_entitlements(user), capability names; free launch plan by default; admin/invited/promo grants.
Dependencies: Step 7, Step 9, Step 10
Changes expected:
- supabase: plans (seeded: free_launch, individual_monthly, individual_yearly, cabinet_base placeholder), subscriptions and subscription_seats tables created empty (Stripe fills them at Step 23), entitlement_grants, function get_effective_entitlements, helper has_active_entitlement(uid, capability), capability catalogue documented (reports.write, reports.complete, reports.edit_after_free_window, community.publish_sheet, booking.manage, profile.public, sheet.private_visibility).
- apps/app: capabilities hook; UI hides what the user lacks (not a boundary).
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 Rust const in the core, exported to TypeScript through ts-rs, checked by a test).
```
```text
Step 12
Name: Clients and animals
Objective: Global client records, contacts, consents, access grants; animals with deceased status and files; species list.
Dependencies: Step 7, Step 8, Step 10, decisions on OPEN_QUESTIONS C4/C5/Q6
Changes expected:
- supabase: species, clients, client_contacts (normalized), client_consents, client_access_grants, client_relationships (practitioner/org ↔ client, with per-relationship notes), animals, animal_access_grants; helpers can_view_client/animal; candidate-match RPC returning only "a record may exist" without identifying the other relationship; consent recording with legal_text_version.
- apps/app: /app/clients list/detail, new client + contacts + consent capture, /app/animals/:animalId with photo and files, deceased flow, sharing request flow (secure email link; delivery stubbed until Step 19).
Tests: pgTAP: cross-practitioner isolation, grant expiry/revocation, org member access, candidate match leaks nothing; integration: create client/animal, share, revoke.
Manual validation: two practitioners; the second cannot see the first's client until a grant exists; revoke and verify.
Definition of Done: architecture Sprint 3; rule 1 (animal ≠ sheet) visible in the model (animals.species_id only).
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 is a reduced Step 12 under C4,
ratified by the owner on 2026-10-25 (BDR-073): records attached to a
workspace, one personal workspace per practitioner, cabinets later, no global
client record shared between practitioners, no consents, grants, sharing,
files or candidate matching. Contract and technical design:
`V1-1_OWNERS_ANIMALS.md` (business decisions approved; architecture and N1-N9
validated 2026-10-25, BDR-074; the workspaces, clients and animals and
relations migrations (V1-1.1, V1-1.2, V1-1.4) written and tested in
isolation, not applied to DEV). Where the
text above differs (global clients, consents, grants, photo, files, deceased
flow), the contract governs V1-1.
```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 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), 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" 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
Objective: Reports persisted in PostgreSQL with autosave, revisions, numbering, completion, quota and free edit window; the local-only flow retired.
Dependencies: Step 5, Step 11, Step 12, Step 13
Changes expected:
- supabase: reports, report_revisions, practitioner_report_counters, RPCs create_report(animal, sheet_version, context), autosave_report(id, document, base_revision) returning revision no, checkpoint_revision(reason), complete_report (quota: 5 lifetime completed incl. deleted and imported; sets free_edit_until = +5 days for free plan), restore_revision, copy_previous_report, soft delete; helpers can_view_report/can_edit_report; RLS; indexes of architecture §32.
- apps/app: /app/dashboard (recent reports), /app/animals/:id → "new report" (choose sheet: official, own, followed later), /app/reports/:reportId editor on supabasePersistence, sync indicator, revision history + restore, completion dialog; routes /, /new, /editor removed; HomeRoute/NewReportRoute/practitionerCache deleted; PDF export uses profile/org branding.
Tests: pgTAP: numbering under two concurrent sessions, 6th completion denied on free, deleted completed still counts, edit after window denied, revisions created on checkpoints only, org-owned report visibility; integration: create → autosave → complete → reopen; unit: persistence contract shared with sessionStorage adapter.
Manual validation: full consultation flow with two accounts (personal and cabinet context); kill the network mid-edit and confirm the UI reports unsaved (offline handling itself is Step 16).
Definition of Done: architecture Sprint 4 except IndexedDB fallback; rules 3–4 visible (reports.anatomical_sheet_version_id NOT NULL FK).
Risks: autosave write volume (throttle 2 s + diff check); report document size with localAnnotations; migration of the sessionStorage draft of existing users (one-time import prompt).
```
```text
Step 15
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, 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: validation location (Rust service vs browser core with server re-check) decided at the step; duplicate imports (idempotency by report id + sha256).
```
```text
Step 16
Name: Offline safety for the report editor
Objective: IndexedDB outbox, visible sync state, retry, conflict revisions.
Dependencies: Step 14
Changes expected:
- apps/app: outboxPersistence wrapping supabasePersistence; sync state machine (synced / pending / offline / conflict); conflict → server keeps both as revisions (reason conflict) and the user picks.
- supabase: autosave_report rejects stale base_revision with a typed error; RPC resolve_conflict.
Tests: unit: outbox replay order, dedupe, stale base handling; Playwright: go offline, edit, go online, verify revision; two tabs editing the same report.
Manual validation: airplane mode scenario on a phone-sized viewport; reload during offline keeps edits.
Definition of Done: architecture §26 MVP target; no claim of "saved" before ack.
Risks: IndexedDB quota and private-mode browsers (fallback to memory with a warning).
```
Milestone B (after Step 16): release 0.5.0 "cloud reports", internal beta
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.
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 + 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); 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).
```
```text
Step 18
Name: Community
Objective: Follow, public sheet discovery, use permission by follow, private sheet grants (use/fork), fork with provenance, reporting/moderation, sheet-version garbage collection.
Dependencies: Step 17, Step 10, Step 11 (community.publish_sheet, sheet.private_visibility)
Changes expected:
- supabase: practitioner_follows, sheet_usage_grants, community_reports, fork RPC (copies current version content into a new sheet, records based_on_*), helpers can_use_sheet/can_fork_sheet extended (public + follow, private + grant), public sheet discovery view, counters, GC job (pg_cron) deleting deprecated versions that pass the four preconditions and logging it.
- apps/app: /app/community (discover, follow), sheet library shows followed creators' sheets, grant management on private sheets, report/moderate UI (moderator role only).
Tests: pgTAP: unfollow revokes use for new reports but existing reports keep their version; private sheet invisible without grant; fork never mutates source; GC never deletes a referenced version; support role cannot moderate.
Manual validation: three accounts: creator publishes, follower uses, third cannot; creator makes it private, grants use to follower only; fork; deprecate v1 unused → GC removes it; deprecate a used version → kept.
Definition of Done: architecture Sprint 11; principle 10 (forks never mutate source) tested.
Risks: discovery performance (indexes §32); GC race with an in-flight report creation (take a row lock on the version during create_report).
```
```text
Step 19
Name: Notifications foundation and worker
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:
- 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: 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).
```
```text
Step 20
Name: Agenda core
Objective: Services, locations, availability rules/exceptions, appointments with status machine, server-authoritative booking with expiry and one-pending-per-client, manual creation, cancellation/reschedule, intake forms.
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 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).
```
```text
Step 21
Name: Travel engine and external calendars
Objective: RoutingProvider abstraction with cache, travel before/after, return-to-base, per-appointment override, Google two-way sync, Apple ICS, conflict alerts.
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.
- 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.
Risks: provider cost/quota; refresh token storage (pgsodium or app-level encryption, decided at the step).
```
```text
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. 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).
- Docker: public-web service; nginx/proxy routes.
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).
```
```text
Step 23
Name: Billing (Stripe) and referral
Objective: Stripe customers/subscriptions for individual monthly/yearly, entitlement engine fed by webhooks, billing history, cabinet seat groundwork, referral rewards with anti-fraud prerequisites.
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.
- 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.
Definition of Done: architecture Sprint 12; principle 12 (limits server-side) complete.
Risks: Stripe tax/TTC handling (Stripe Tax decision); seat pricing not fixed (groundwork only).
```
```text
Step 24
Name: Import framework
Objective: Staging model, adapters (generic CSV/XLSX/JSON/ZIP, Faunosteo PDF v2/v3, Animalib/Kiwi when samples exist), read-only preflight, mapping review, duplicate candidates, quota check, atomic commit, "Données importées".
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.
- 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.
Definition of Done: architecture Sprint 13 minus vendor adapters pending samples.
Risks: vendor formats unknown (do not guess; adapters wait for samples).
```
```text
Step 25
Name: Administration, audit and legal documents
Objective: Admin console (verification review already exists), audit log viewer, impersonation with banner and expiry, moderation queue UI, legal document versions and acceptance, admin MFA mandatory.
Dependencies: Step 7, Step 9, Step 18, Step 23
Changes expected:
- supabase: impersonation_sessions RPC (short-lived, audited), legal_documents + acceptances, MFA requirement helper enforced on admin tables.
- apps/app: /app/admin/* (users, roles, verifications, moderation, audit, entitlement overrides).
Tests: pgTAP: impersonation expires and is logged; admin without MFA denied; acceptance versioning; moderation role matrix.
Manual validation: impersonate a test user, see the banner, act, check the audit entry.
Definition of Done: architecture §17.5, §29 complete.
Risks: scope creep of the admin UI (minimum needed by support).
```
```text
Step 26
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:
- 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.
Definition of Done: architecture §16; rule 8 at account level.
Risks: legal retention durations not final (parameters, not code).
```
```text
Step 27
Name: Production hardening and first-cohort release
Objective: Full RLS and storage audit, cross-tenant scenarios, security headers/CSP, rate limiting, backup/restore rehearsal, monitoring, dependency audit, performance checks with realistic seed, legal validation checklist.
Dependencies: all previous steps
Changes expected:
- supabase/tests: full RLS matrix generated from the table list; cross-tenant scenarios of architecture Prompt 10 as e2e; EXPLAIN ANALYZE on §32 indexes with a 10k-report seed.
- nginx/proxy: CSP, HSTS, frame-ancestors for the widget origin list; rate limits on public RPCs.
- ops: backup verification job, monitoring/alerting, runbooks (deploy, restore, rotate keys).
- DEPLOY.md rewritten for the full stack.
Tests: everything green; audit findings each with severity, scenario, fix and regression test (no blind fixes).
Manual validation: restore the production backup on staging; penetration checklist walked by a second person.
Definition of Done: architecture §38 Definition of Done satisfied except items that are legal (tracked separately); release 1.0.0.
Risks: findings reopening earlier steps (budget time for one iteration).
```
## 4. Dependency graph
```text
Step 0 ─▶ Step 1 ─▶ Step 2 ─┬─▶ Step 3 (Supabase foundation) ─┬─▶ Step 7 (Identity) ─┬─▶ Step 8 (Files) ─┬─▶ Step 9 (Verification) ─┐
│ │ ├─▶ Step 10 (Orgs) ─┼──────────────────────────┼─▶ Step 11 (Entitlements)
│ │ │ │ │
└─▶ Step 4 (Sheet model, ∥ 3) ─▶ Step 5 (App on sheet) ─▶ Step 6 (PDF v3) └─▶ Step 12 (Clients/Animals) ◀┘
│ │
└────────── Step 13 (Sheets in DB, needs 3+4+8) ──────┤
▼
Step 14 (Cloud reports: 5+11+12+13) ─▶ Step 15 (PDF artifacts: 6+14) ─▶ Step 16 (Offline)
│
Step 17 (Editor merge: 13+5, ∥ 14–16) ─▶ Step 18 (Community: 17+10+11) │
│
Step 19 (Notifications/worker: 7+12) ─▶ Step 20 (Agenda: 12+19+11) ─▶ Step 21 (Travel/calendars) ─▶ Step 22 (Public web + widget: 7+9+20)
│
Step 23 (Billing: 11+10+19) ─▶ Step 24 (Imports: 15+12+11+19) ─▶ Step 25 (Admin: 7+9+18+23) ─▶ Step 26 (Lifecycle: 19+23+15) ─▶ Step 27 (Hardening)
```
Per-step table (depends on / unblocks / main risk):
| Step | Depends on | Unblocks | Main risk |
|---|---|---|---|
| 1 Characterisation tests | 0 | 2, 4, 5 | encoding bugs as expected behaviour |
| 2 Workspace | 1 | 3, 4 | path regressions (DONE) |
| 3 Supabase foundation | 2 | 7, 13 | hosting decision (Q2) |
| 4 Sheet model + importer | 1, 2 | 5, 13 | special cases missed (audit 07) |
| 5 App on sheet, document v3 | 4 | 6, 14, 17 | core refactor size |
| 6 PDF v3 | 5 | 15 | attachment size, import gate |
| 7 Identity | 3 | 8, 9, 10, 11, 12, 19, 22 | OAuth/phone providers |
| 8 Files | 7 | 9, 12, 13 | bypassing assets row |
| 9 Verification | 7, 8 | 11, 22, 25 | legal criteria |
| 10 Organizations | 7 | 11, 12, 18, 23 | context leakage |
| 11 Entitlements | 7, 9, 10 | 14, 18, 20, 23, 24 | capability drift |
| 12 Clients/Animals | 7, 8, 10 | 14, 19, 20, 24 | global client design (C4) |
| 13 Sheets in DB | 3, 4, 8 | 14, 17 | seed drift |
| 14 Cloud reports | 5, 11, 12, 13 | 15, 16, 24 | autosave volume, quota correctness |
| 15 PDF artifacts + import | 6, 14 | 24, 26 | server validation location |
| 16 Offline | 14 | B milestone | IndexedDB edge cases |
| 17 Editor merge | 13, 5 | 18 | parity with vanilla tools |
| 18 Community | 17, 10, 11 | 22 (counts), 25 | GC race |
| 19 Notifications/worker | 7, 12 | 20, 21, 23, 24, 26 | deliverability |
| 20 Agenda | 12, 19, 11 | 21, 22 | timezones, race |
| 21 Travel/calendars | 20, 19 | 22 | provider cost |
| 22 Public web + widget | 7, 9, 20 | 27 | SEO data leak |
| 23 Billing | 11, 10, 7, 19 | 24, 25, 26 | tax, idempotency |
| 24 Imports | 15, 12, 11, 19 | 27 | unknown vendor formats |
| 25 Admin | 7, 9, 18, 23 | 27 | scope |
| 26 Lifecycle | 19, 23, 15 | 27 | legal durations |
| 27 Hardening | all | 1.0.0 | reopening earlier steps |
Parallel tracks a single developer can interleave: (A) 3 → 7 → 8 → 9/10 → 11
→ 12; (B) 4 → 5 → 6; (C) 13 → 17 → 18 once A reaches 8. Track B has no
backend and can ship to the live site at any time (Milestone A).
## 5. Migration difficulty ranking (brief §8)
| Class | Migration | Why |
|---|---|---|
| CRITICAL | Anatomical sheet model + legacy importer (Steps 4, 13) | Replaces the implicit sheet (four sources, no id, no version, fuzzy link) with the object every report references; a mistake here is baked into immutable v1 and into every report's annotation ids. |
| CRITICAL | Report document v3 + persistence split (Steps 5, 14) | Changes the identity space of zones (`boneId` → `annotationId`), the region model, and the store; this is the clinical core and had zero tests on its click chain. |
| CRITICAL | RLS and helpers (Steps 3, 7–14) | The only security boundary of a multi-tenant clinical database; a wrong policy is a data breach, not a bug. |
| CRITICAL | Client/animal permissions (Step 12) | Global client records across practitioners plus consent and sharing; the design itself is flagged (C4). |
| CRITICAL | PDF portability (Steps 6, 15) | The PDF is the long-term archive and the import path handles user data; rule 8 depends on it. |
| IMPORTANT | Editor merge (Step 17) | Large UI with two untested legacy references, but no data risk: the document model and tables already exist. |
| IMPORTANT | Agenda + travel + calendars (Steps 20–21) | Server-authoritative engine with concurrency rules; new domain, no legacy. |
| IMPORTANT | Community (Step 18) | Permission model on sheets and garbage collection with four preconditions. |
| IMPORTANT | Billing + entitlements (Steps 11, 23) | Server-side limits; the skeleton must exist early or quota logic gets re-implemented. |
| IMPORTANT | Offline (Step 16) | Conflict semantics; limited scope by design. |
| IMPORTANT | Imports (Step 24) | Atomicity and quota; vendor formats unknown. |
| LOW | Workspace move (Step 2), i18n package, UI package, public site (Step 22), notifications (Step 19), admin UI (Step 25) | Mechanical or greenfield with clear contracts. |
## 6. Mapping to the architecture's sprints (§35)
| Architecture sprint | Plan steps |
|---|---|
| 0 Foundation | 2, 3 (+ 1 as prerequisite) |
| 1 Auth/profile/verification | 7, 9 |
| 2 Organizations | 10 (+ seats in 23) |
| 3 Clients/animals | 12 (+ files 8) |
| 4 Cloud reports | 14, 16 (+ entitlements 11) |
| 5 Sheet data model | 4, 13 |
| 6 Editor merge | 17 |
| 7 PDF + portability | 6, 15 |
| 8 Agenda core | 20 |
| 9 Travel + calendars | 21 |
| 10 Public profile + widget | 22 |
| 11 Community | 18 |
| 12 Billing + referral | 23 (+ 11) |
| 13 Migration engine | 24 |
| 14 Hardening | 25, 26, 27 |
The plan pulls the sheet model (sprint 5) and PDF (sprint 7) *before* cloud
reports because a cloud report must reference a sheet version from its first
row, and pulls entitlements before reports because the quota is part of
completion.
## 7. Branches (gitflow, no branch created in Step 0)
| Step | Branch | Notes |
|---|---|---|
| 0 | `chore/step-00-implementation-plan` | docs only (`.claude/**` exempt rule does not cover `docs/`, so a chore branch) |
| 1 | `feature/step-01-characterisation-tests` | |
| 2 | `feature/step-02-monorepo-workspace` | one `git mv` commit, one config commit |
| 3 | `feature/step-03-supabase-foundation` | |
| 4 | `feature/step-04-sheet-model-importer` | |
| 5 | `feature/step-05-app-on-sheet-v3` | may split: `-a-zone-service`, `-b-document-v3`, `-c-sheet-provider` |
| 6 | `feature/step-06-pdf-v3` | confirmation gate on import/attachment |
| 7–13 | `feature/step-07-identity` … `feature/step-13-sheets-db-seed` | |
| 14 | `feature/step-14-cloud-reports` | sub-branches: `-a-tables-rpc`, `-b-editor-persistence`, `-c-retire-local-flow` |
| 15–16 | `feature/step-15-pdf-artifacts-import`, `feature/step-16-offline-outbox` | |
| 17 | `feature/step-17-sheet-editor` | sub-branches `-a-canvas`, `-b-panels`, `-c-publish-delete-legacy` |
| 18–26 | `feature/step-18-community` … `feature/step-26-data-lifecycle` | |
| 27 | `release/1.0.0` after `feature/step-27-hardening` | |
| Milestones | `release/0.2.0` after Step 6, `release/0.5.0` after Step 16 | cut via `/release-candidate` |
| Fixes | `bugfix/*` off develop; `hotfix/*` only for the live site | |
Every branch is pushed at `start` and on every commit (gitflow hooks); `finish`
only on explicit human signal.
## 8. Risk register (brief §11)
| Risk | Class | Where | Mitigation |
|---|---|---|---|
| Data loss during persistence switch (sessionStorage → Supabase) | CRITICAL | Step 14 | one-time draft import prompt; drafts never deleted client-side until server ack; revisions from day one |
| Identifier model change (`data-anno-id` → stable annotation ids; `boneId` → `annotationId`) | CRITICAL | Steps 4, 5 | deterministic importer + committed legacy id map + Step 1 mapping table as oracle; v2 adapter tested on golden fixtures |
| SVG assets: duplicated head file, opaque ids, degraded slugs, trigger without category, client-only sanitizer | CRITICAL | Steps 4, 8, 13, 17 | importer runs only on committed files; slugs preserved verbatim; server sanitizer + quarantine; per-view id scoping |
| Finding mappings: fuzzy match at runtime, duplicate node ids across zones, `ssb-dysfunctions` anomaly | CRITICAL | Steps 4, 5 | explicit `annotation_finding_map` validated on publish; paths anchored at zone; anomaly fixed before v1 (Q9) |
| Historical reports unreadable after sheet changes | CRITICAL | Steps 13, 15 | immutable versions, FK from report, snapshot in PDF, snapshot-only version on import, GC preconditions tested |
| 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; 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 |
| Community: GC deleting a referenced version; private sheet exposure | IMPORTANT | Step 18 | preconditions in one function with tests; grants evaluated in helpers |
| Billing: webhook replay, entitlement drift | IMPORTANT | Steps 11, 23 | idempotency table, single `get_effective_entitlements` |
| Imports: partial commits on free accounts, silent merges | IMPORTANT | Step 24 | one transaction, duplicate review mandatory |
| Hosting under-provisioned for self-hosted Supabase | IMPORTANT | Step 3 deploy | Q2 before deploying; local work unaffected |
| 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 | Astro (D-R8), isolated app |
## 9. Deliverable checklist per step (applies to every step)
1. Plan line in `.claude/tasks/TODO.md` with sub-tasks checked as they land.
2. Branch per §7; commits in Conventional Commits with the allowed scopes
(`schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`,
`config`, `species`, `i18n`, `docker`, `docs`, `tests`, `chore`; new scopes
`supabase`, `app`, `worker`, `public-web`, `domain` to be added to
CLAUDE.md at Step 2).
3. Tests listed in the step green; `TEST_STRATEGY.md` §3 row satisfied.
4. Manual validation script executed and its result written in the PR / TODO note.
5. Docs touched: CLAUDE.md folder map, `docs/development/*` if the plan changed, domain docs.
6. Registries: decisions (BDR) for each visible design choice, learnings, blockers.
7. Definition of Done met; otherwise the step is not merged.