docs(docs): V1-1 owner decisions N1-N9 and M1 as built

Contract: N4 voiding instead of deletion, N5 date constraints, N6 write budget per workspace under a lock, N7 effective-privilege wording and residual admin paths, N9 audit metadata limited to ids; M1 as-built notes and isolated-stack results (§8.1). SUPABASE.md §3.3 with the owner procedure to apply M1 on DEV without reset; backend architecture, test strategy, plan and CLAUDE.md lines.
This commit is contained in:
bchanot committed 2026-10-25 20:00:06 +01:00
1 parent 7bf4fb6079
commit 0f8c9833cc
6 files changed
+237 -59

No files matched your search

+4 -3
View File
@@ -49,8 +49,9 @@ 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`:
business decisions ratified 2026-10-25, BDR-073; SQL/RLS/RPC design awaiting owner validation on
`feature/v1-1-clients-animals`; nothing built).
business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on
`feature/v1-1-clients-animals` only V1-1.1 is built: migration `20261025100000_workspaces.sql`, tested on PGlite and an
isolated stack, not applied to Supabase DEV).
---
@@ -274,7 +275,7 @@ faunosteo/
│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test
├─ supabase/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs)
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs), workspaces (V1-1.1: personal workspace per account, access helpers)
│ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
+14 -1
View File
@@ -83,12 +83,25 @@ private.has_active_entitlement(uid, capability text)
Each helper ships with pgTAP tests in the same migration step: positive case,
negative case, expired grant, revoked grant, wrong organization.
As built from V1-1 (contract `V1-1_OWNERS_ANIMALS.md` §9, BDR-073/074): the
perimeter is a workspace, not an organization. `private.caller_workspace_ids()`
(member, active profile, confirmed email; no parameter, `auth.uid()` only;
EXECUTE for `authenticated`) and `private.writable_workspace_ids()` (the same,
restricted to a write role; EXECUTE for nobody, called inside definer RPCs)
replace `is_org_*` and `can_view_client/animal` for V1-1 records. They avoid
RLS recursion by running as the table owner (`security definer`, owner
`postgres`, `search_path = ''`) rather than with `row_security = off`. No
helper or policy has a platform-role branch (D16). Every V1-1 table revokes
all privileges from `anon` and `service_role` (N7); `postgres` keeps
`BYPASSRLS` on the Supabase image and the service key stays a GoTrue admin
credential, residual paths named in the contract §6.3.
### 4.2 Policy rules per domain (summary of §17.3)
| Table family | SELECT | INSERT/UPDATE/DELETE |
|---|---|---|
| `profiles` | own row; admins via view | own row; roles only through RPC |
| `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place |
| `workspaces`, `workspace_members` (V1-1; cabinets extend them instead of `organizations`) | members, through `caller_workspace_ids()` | none through the API: personal workspace created by trigger; cabinet membership RPCs come with Step 10 |
| `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
| `animals` | `can_view_animal` | practitioner with an active relationship or grant |
| `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC |
+3 -2
View File
@@ -354,8 +354,9 @@ 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; the SQL, RLS and RPC
design awaits the owner's validation before the first migration). Where the
`V1-1_OWNERS_ANIMALS.md` (business decisions approved; architecture and N1-N9
validated 2026-10-25, BDR-074; V1-1.1 workspaces migration 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.
+36 -2
View File
@@ -18,7 +18,8 @@ supabase/
│ ├─ 20261009100000_sheet_asset_storage.sql bucket anatomical-sheet-assets + read policy through the sheet
│ ├─ 20261010100000_sheet_document_schema_v2.sql document schema 2: references, review_status, count_range checks
│ ├─ 20261011100000_profiles_professional.sql practice_name, professional_title, siret
│ └─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md)
│ ├─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md)
│ └─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3)
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
├─ seed/anatomical-sheets/equine/ official equine sheet as a DRAFT, generated by `pnpm import:equine`
│ ├─ legacy-sources/ the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input)
@@ -181,11 +182,44 @@ Seed accounts (local only, password `LocalDev-only-password-1`):
| `alice@faunosteo.local` | plain user |
| `bob@faunosteo.local` | plain user |
### 3.3 Workspaces (V1-1.1, migration M1)
Contract: `docs/development/V1-1_OWNERS_ANIMALS.md` §4, §8.1, §9. Every
account has exactly one personal workspace, created by the trigger
`profiles_create_personal_workspace` in the sign-up transaction (GoTrue →
`handle_new_auth_user` → profile → workspace + `holder` membership), through
the single write path `private.ensure_personal_workspace(uuid)` (one
statement, idempotent, race-safe). A deferred constraint trigger refuses at
commit a personal workspace without its holder or with any other member.
Reads: RLS through `private.caller_workspace_ids()` (member, active profile,
confirmed email, `auth.uid()` only). No API role writes either table; `anon`
and `service_role` hold no privilege on them. From M2 on, record tables use
the same helpers; the app passes its workspace id explicitly.
M1 is written and tested on PGlite and on an isolated stack, not applied to
the DEV stack. Applying it there is an owner action, without a reset:
```bash
pnpm supabase db dump --local -f ~/faunosteo-dev-schema-before-m1.sql # optional safety copy: schema
pnpm supabase db dump --local --data-only -f ~/faunosteo-dev-data-before-m1.sql # and data (DEV accounts are fictitious)
pnpm supabase migration list --local # 20261025100000 listed as local only
pnpm supabase migration up --local # applies the pending migration; its backfill creates the missing workspaces
pnpm db:test # the 12 pgTAP files on the DEV database (each rolled back)
pnpm db:types:check # no diff with the committed types
```
Afterwards every existing account has its workspace: in Studio's SQL editor,
`select count(*) from public.profiles p where not exists (select 1 from
public.workspaces w where w.personal_user_id = p.id)` returns 0. The migration is forward-only: undoing it means restoring
the dumps or writing a new migration. `pnpm db:reset` also applies it, but
replays the whole database from zero and loses the DEV accounts and data.
## 4. Writing a migration
1. `pnpm supabase migration new <name>` creates `supabase/migrations/<timestamp>_<name>.sql`.
2. A migration that adds a table adds, in the same file: RLS enable, explicit
`revoke all ... from public, anon, authenticated` then the exact grants,
`revoke all ... from public, anon, authenticated` (and `service_role` for
V1-1 record tables, contract N7) then the exact grants,
separate SELECT / INSERT / UPDATE / DELETE policies, indexes, comments.
3. Add or extend a pgTAP file under `supabase/tests/`: the allowed path and
every denied path (other user, anon, direct write bypassing an RPC). Scope
+4
View File
@@ -12,6 +12,10 @@ not created; the real-stack e2e lives in `packages/supabase/tests/e2e`. No
real-browser suite exists yet (TODO RR-8; V1-1 contract §12.5 proposes the
first one, decision D14). No CI has ever run (BDR-047): "CI" in the tables means the
prepared workflow.
V1-1.1 (2026-10-25): supabase vitest 44 (config test added), 12 pgTAP files
(`012_workspaces.sql`, 85 checks; 531 checks in all), also run on an isolated
real stack because the DEV stack stays untouched until the owner applies M1
(`V1-1_OWNERS_ANIMALS.md` §8.1).
## 1. Layers
+176 -51
View File
@@ -2,10 +2,13 @@
Status: business decisions approved by the owner on 2026-10-25 (brief « V1-1 :
ratification des décisions métier et préparation de l'implémentation »,
BDR-073). The technical design of Parts 8 to 10 and the choices of §13.2 and
§13.3 are proposals awaiting the owner's validation at the V1-1 preparation
checkpoint. Until that validation nothing is implemented: no migration, table,
RPC, policy, component, route or dependency, and Supabase DEV is untouched.
BDR-073). The architecture of Parts 4 to 9 and the technical choices N1 to N9
were validated by the owner the same day (brief « Validation du contrat V1-1
et autorisation de V1-1.1 Workspaces », BDR-074, §13.2), with the precisions
written into §5.3, §9 and §10. The interface choices of §13.3 stay proposals
until their UI steps. Only step V1-1.1 is authorised: migration M1 is written
and tested on an isolated database (§8.1); it is not applied to Supabase DEV,
and nothing of V1-1.2 to V1-1.6 exists.
Branch: `feature/v1-1-clients-animals`. 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
@@ -106,10 +109,25 @@ clients shared between practitioners, no data visible from one practitioner to
another, and no sharing between practitioners of a cabinet. Invitations and
cabinet permissions are not built.
- Creation: a trigger after insert on `profiles` creates the personal workspace
and its `holder` membership; the migration backfills existing profiles.
- Creation: a controlled server initialisation, never a client call. A
trigger after insert on `profiles` creates the personal workspace and its
`holder` membership in the transaction that creates the account (GoTrue
inserts `auth.users`, `private.handle_new_auth_user` inserts the profile,
the trigger creates the workspace): a failure anywhere rolls back the whole
sign-up, so no account exists without its workspace and no workspace
without its account. The workspace exists before the email is confirmed and
stays unreadable until then (§9.1). The migration backfills existing
profiles through the same write path.
- Uniqueness: `personal_user_id` is unique, so an account never has two
personal workspaces.
personal workspaces. The single write path inserts with `on conflict do
nothing` on that key: a retry, a replay or two concurrent calls create one
workspace and one membership, never two (§8.1).
- Consistency: a personal workspace has exactly one member, its account, as
`holder`. A deferred constraint trigger checks it at commit, whatever role
writes, so neither row survives alone and no other account can be added.
- Deletion: no archive state for a workspace. A personal workspace follows its
account: deleting an empty account deletes it; from M2 on, records refuse
the deletion (D9a, §7.2).
- Context: every read and write names its workspace (RPC parameter or filter).
The app reads its personal workspace once after sign-in and passes its id
explicitly to the access layer; nothing reads a global "current workspace"
@@ -222,9 +240,10 @@ Table `animal_client_relations`:
|---|---|
| `animal_id`, `client_id` | same workspace, enforced by composite foreign keys |
| `relation_role` | `owner`, `keeper` or `contact` |
| `started_on` | date the relation began, when known; null when unknown |
| `ended_at` | null while the relation is current; set when the end is recorded (§13.2 N5) |
| `started_on` | date the relation began, when known; null when unknown; never filled by default |
| `ended_at` | null while the relation is current; set to the recording time when the end is recorded (§13.2 N5); a technical time, never shown as the end date |
| `ended_on` | date the relation ended, when known; only on an ended relation; not before `started_on` |
| `voided_at` | null for a relation that existed; set when a relation entered by mistake is voided (§13.2 N4) |
| `revision`, `created_at`, `updated_at` | server-maintained |
Rules:
@@ -252,15 +271,48 @@ Rules:
keeps their other animals and appears as « ancien propriétaire » on the
animal's page. Between the two actions the animal has two current owners or
none, two valid states, so no atomic transfer operation is needed;
- ending is not deleting: an ended relation stays readable. Removing a
relation entered by mistake is §13.2 N4; a relation ended by mistake is
corrected the same way: removed, then created again as current.
- ending is not deleting: an ended relation stays readable as a former
relation, with its dates;
- voiding is not ending (N4): a relation that never existed (wrong client,
wrong animal, wrong role) is voided, never ended, so it never appears as a
former owner or keeper and no end date is invented for a period that never
was. The row keeps every value as entered, gains `voided_at`, and becomes
frozen (no end, no date change, no un-voiding); the audit log records who
voided it and when (§9.3). Voided relations are left out of every list, of
the current-relation index, of the derived values (§9.3) and of the current
cap; they count in the 200 total per animal, so a create-and-void loop
cannot grow a table without bound. No V1-1 screen shows them; the row stays
for the lifecycle contract (export, erasure) and incident work;
- an end recorded on the wrong relation is voided like any wrong relation,
then the right one is created. An end recorded with a wrong date is
corrected by `update_animal_client_relation`. Re-opening a relation whose
end never happened (clearing `ended_at`) is not offered in V1-1: the
relation is voided and created again as current, with the same start date;
the owner may ask for an explicit reopening at V1-1.4.
Date rules (N5), all enforced by SQL CHECK except « not in the future »,
which needs the clock and is checked by the RPCs (tomorrow's UTC date, §9.3):
| Constraint | SQL |
|---|---|
| dates optional, no default | `started_on date`, `ended_on date`, both nullable, no `default` |
| plausible lower bound | `started_on >= '1900-01-01'`, `ended_on >= '1900-01-01'` |
| an end date only on an ended relation | `ended_on is null or ended_at is not null` |
| order when both are known | `started_on is null or ended_on is null or started_on <= ended_on` |
| a voided relation keeps its state | `voided_at` set only by the void RPC; every other write RPC refuses a voided row (`invalid_input`) |
| one current relation per triple | unique index on `(animal_id, client_id, relation_role) where ended_at is null and voided_at is null` |
### 5.4 Species (D5, approved)
Reference data written by migration: the nine species of the contract (the
existing `equine` row plus eight) and « Autre ». No other species is added.
Slugs, names and order are proposal §13.2 N1:
Slugs, names and order approved by the owner (§13.2 N1). Compatibility,
checked on 2026-10-25: species are rows of `public.species` (text `id`,
CHECK `^[a-z0-9][a-z0-9_-]{0,63}$`, which every slug below satisfies), never a
SQL enum, so M3 adds rows and freezes no new enumeration; the Rust core
carries `species_id` / `speciesId` as a free string (report identity, sheet
document, snapshot, sheet index) with no species list, and the only existing
id, `equine`, is kept unchanged:
| `id` | `name_fr` | `name_en` | `sort_order` |
|---|---|---|---|
@@ -291,7 +343,7 @@ adds the refusal if it opens sheet creation.
| Actor | Read | Create | Edit | Archive / restore | Delete |
|---|---|---|---|---|---|
| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no, except a relation entered by mistake if §13.2 N4 is approved |
| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no; a relation entered by mistake is voided, never deleted (§13.2 N4) |
| Future cabinet roles | defined by the cabinet step | | | | |
| The same account with an unconfirmed email | no | no | no | no | no |
| Another signed-in account | no | no | no | no | no |
@@ -334,16 +386,26 @@ Residual technical paths, named so nobody believes them closed:
credentials, bounded only by their custody; the exceptional-access contract
covers them, with two follow-ups in §14 (a narrower worker credential,
monitoring of GoTrue admin actions in `auth.audit_log_entries`);
- the table owner (`postgres`, not a superuser on Supabase) and any database
- the table owner (`postgres`, not a superuser on Supabase, but holding
`BYPASSRLS` on the Supabase image, checked on 17.11.0.004) and any database
superuser read past RLS: maintenance, backup restore and incident response
are exceptional privileged operations that the separate contract frames,
justifies and audits before any publication.
Both paths were exercised on the isolated stack of V1-1.1 (§8.1): the service
key reads nothing through PostgREST (`permission denied`), yet it obtains a
session for any account through GoTrue's admin link generation and then reads
that account's workspace like its practitioner. Removing table privileges
narrows the direct path only; the residual risk stays on the security track
before production (RR-4), as the owner required (N7).
The existing audit policy lets platform owners and admins read audit rows. The
V1-1 rows carry the actor, resource ids, the action and the workspace id. Read
with the staff policy on profiles, that reveals per-practitioner volumes,
working hours and events such as « relation ended »: activity metadata, never
names or contacts. §13.2 N9 decides whether that stays visible.
V1-1 rows carry the actor, the resource id, the action, the time and the
workspace id. Read with the staff policy on profiles, that would reveal
per-practitioner volumes, working hours and events such as « relation ended »:
activity metadata, never names or contacts. N9 (§13.2): platform staff get no
general view of the private records, so M2 removes the `client.*`, `animal.*`
and `animal_client_relation.*` actions from `audit_logs_select_admin`.
### 6.4 Edits and finished bilans (C5, approved)
@@ -454,23 +516,24 @@ term travels in a POST body), audit rows, application logs or error messages
---
## 8. SQL schema (proposed, not a migration)
## 8. SQL schema (M1 written, M2 and M3 proposed)
Three forward-only migrations, one per data step, each with its pgTAP files,
the regenerated `database.types.ts` and the census updates in the same branch
(plan principle 2). Timestamps are set when written.
(plan principle 2). Timestamps are set when written. M1 as built, with its
differences from the sketch below: §8.1.
| Migration | Step | Content |
|---|---|---|
| M1 `<ts>_workspaces.sql` | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS |
| M1 `20261025100000_workspaces.sql` (written, V1-1.1) | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS |
| M2 `<ts>_clients.sql` | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS |
| M3 `<ts>_animals_relations.sql` | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS |
Why the correlation header in M1: `private.log_event` copies that request
header verbatim today (foundation migration), the app never sends it, and
PostgREST exposes every header, so a caller chooses the size of each
append-only audit row. V1-1 raises the audited write rate from 10 to 1 000 an
hour per account, which turns that into a storage risk. The change keeps the
append-only audit row. V1-1 raises the audited write rate to 1 000 an hour
per workspace (§10), which turns that into a storage risk. The change keeps the
function's signature and callers.
Sketch of the tables. `<clean>(c)` abbreviates the text rule of §5:
@@ -580,6 +643,7 @@ create table public.animal_client_relations (
started_on date, -- >= 1900-01-01 (CHECK); not in the future (RPC)
ended_on date, -- idem
ended_at timestamptz,
voided_at timestamptz, -- set once by the void RPC (N4)
create_request_id uuid not null,
revision integer not null default 1,
created_at timestamptz not null default now(),
@@ -592,12 +656,14 @@ create table public.animal_client_relations (
check (ended_on is null or ended_at is not null),
constraint animal_client_relations_dates_order
check (started_on is null or ended_on is null or started_on <= ended_on),
constraint animal_client_relations_started_on_range check (started_on >= '1900-01-01'),
constraint animal_client_relations_ended_on_range check (ended_on >= '1900-01-01'),
constraint animal_client_relations_create_request_unique
unique (workspace_id, create_request_id)
);
create unique index animal_client_relations_current_unique
on public.animal_client_relations (animal_id, client_id, relation_role)
where ended_at is null;
where ended_at is null and voided_at is null;
create index animal_client_relations_animal_idx
on public.animal_client_relations (workspace_id, animal_id);
create index animal_client_relations_client_idx
@@ -644,6 +710,51 @@ follows French alphabetical order closely enough for a list. If the dictionary
of `unaccent` ever changed, stored keys would differ from new ones until their
rows are rewritten: recorded, low risk.
### 8.1 M1 as built (V1-1.1, 2026-10-25)
`supabase/migrations/20261025100000_workspaces.sql`, tested by
`supabase/tests/012_workspaces.sql` (85 checks) and the census of
`001_schema.sql`. Differences from the sketch and from the plan, each
deliberate:
| Point | Sketch or plan | As built | Why |
|---|---|---|---|
| Uniqueness of the personal workspace | inline `unique` | named constraint `workspaces_personal_user_unique` | the single write path targets it with `on conflict`, tests name it |
| Write path | trigger and backfill | both call `private.ensure_personal_workspace(uuid)`: workspace and holder membership inserted by one statement, `on conflict (personal_user_id) do nothing`, returns whether it created | one place for atomicity and idempotence; a concurrent call waits for the first commit, then writes nothing |
| Consistency workspace ↔ holder | not in the sketch | deferred constraint triggers `workspaces_personal_holder` and `workspace_members_personal_holder` on `private.check_personal_workspace()`: at commit, a personal workspace has exactly its account as `holder` | the owner asked for a coherence constraint between the workspace's account and its member; it holds for any writer, the table owner included; cabinets are not constrained |
| Trigger name | not named | `profiles_create_personal_workspace` | |
| `private.writable_workspace_ids()` | M1 | created in M1, unused until M2's write RPCs | the helper set of §9.1 ships and is tested once |
| Access layer `packages/supabase/src/workspaces.ts` | planned in V1-1.1 | deferred to V1-1.2 | no consumer before the clients access layer; the brief authorised M1 and its tests |
| `pnpm db:reset && pnpm db:test` | planned gate | not run: the owner kept the DEV stack untouched | replaced by an isolated real stack (below) |
Not changed by M1: the privileges of existing tables. `service_role` keeps the
Supabase default privileges it holds today on `profiles`, `profile_roles` and
`assets` (only the new tables and `private.object_purge_queue` revoke it);
narrowing them is outside V1-1.1 and needs the owner's decision (N7).
Isolated real-stack verification. A throwaway stack built from the DEV stack's
images (PostgreSQL 17.11.0.004, GoTrue v2.197.0, Storage v1.79.36, PostgREST
v16.4, Mailpit v1.31.3) on its own Docker network, ports on the loopback
only, no Docker volume, DEV containers untouched. Two runs: from zero (all
migrations then the seeds, as `supabase db reset`), and the DEV path (the
migrations before M1, the seeds and two accounts created through GoTrue, then
M1, whose backfill created the five missing workspaces). In both: the twelve
pgTAP files green (531 checks); real concurrent sessions (two creations of one
account's workspace: the second waited for the first commit and wrote
nothing; two racing backfills created 40 workspaces between them, no
duplicate; commits of a workspace without its holder or with a foreign member
refused at COMMIT; a rolled-back creation left nothing and the retry created
one); ten parallel GoTrue sign-ups each with one workspace; 33 HTTP checks
through GoTrue and PostgREST (sign-up without session, confirmation by the
mailed link, reads limited to the own workspace, `count=exact` of one,
refusals with `permission denied` for writes, for the anon key and for the
service key, `private` functions unreachable, deactivation effective on the
next request with the same token, the correlation header capped through a
real request, an empty account deleted by the GoTrue admin API taking its
workspace along, and the residual admin path of §6.3). The types were
generated from that database: the diff with the committed file is exactly the
M1 additions.
---
## 9. Policies, helpers and RPCs
@@ -654,10 +765,12 @@ rows are rewritten: recorded, low risk.
|---|---|---|---|
| `private.caller_workspace_ids()` | `setof uuid` | the single source of the access rule: workspaces where `auth.uid()` is a member, with an active profile and a confirmed email | `authenticated` (policies evaluate it) |
| `private.writable_workspace_ids()` | `setof uuid` | `caller_workspace_ids()` restricted to a write role (V1-1: `holder`) | none (called inside RPCs) |
| `private.require_write_budget(p_actor uuid)` | `void` | raises P0001 `rate_limited` when the actor has 1 000 audit rows within the past hour or 5 000 within the past day (every audit row of the actor counts, on the existing `audit_logs_actor_idx`) | none |
| `private.require_write_budget(p_workspace_id uuid)` | `void` | raises P0001 `rate_limited` when the workspace has 1 000 audited writes within the past hour or 5 000 within the past day (N6: per workspace); the count and the write are serialised per workspace, never a bare count followed by an unprotected insert; the counter (rows counted by workspace, or a counter row per workspace and window) and its lock are fixed and documented with M2 | none |
| `private.fold_text(p_value text)` | `text` | lower case without accents (`unaccent` with an explicit dictionary), declared immutable for the generated columns | `authenticated` (the invoker search folds the term) |
| `private.create_personal_workspace()` | trigger | after insert on `profiles`: workspace + `holder` membership | none |
| `private.ensure_personal_workspace(p_user_id uuid)` | `boolean` | the single write path: workspace and `holder` membership in one statement, `on conflict do nothing` on `personal_user_id`; true when it created (M1, §8.1) | none |
| `private.create_personal_workspace()` | trigger | after insert on `profiles`: calls `ensure_personal_workspace(new.id)` | none |
| `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none |
| `private.check_personal_workspace()` | constraint trigger | deferred to commit: a personal workspace has exactly its account as `holder` (M1, §8.1) | none |
All are `security definer` (except `fold_text`, a pure SQL function),
`set search_path = ''`, `revoke all ... from public, anon, authenticated,
@@ -711,7 +824,12 @@ Locks: create RPCs of clients and animals lock the workspace row (cap and
insert serialised per workspace); every relation RPC locks the animal row
`for update` then the client row `for share`, in that order; the archive RPCs
lock their row `for update`. So caps, « both active » and « animal active »
cannot be passed by a concurrent call.
cannot be passed by a concurrent call. The write budget and the 100 000
relations per workspace count rows that writes on different animals or
clients can add at the same time: they are counted under a lock that
serialises those writes per workspace (owner, N6: never a bare count followed
by an unprotected insert). M2 fixes that lock and the global lock order
(candidate: workspace row, then animal, then client) and documents it here.
Parameters: dates, years and enum values arrive as `text` and are parsed inside
the body, so a malformed value (« 2015-02-30 ») is answered `invalid_input`
@@ -729,9 +847,9 @@ update that changes nothing writes nothing and returns the current revision.
| `update_animal` | `animal_id`, `expected_revision`, the seven fields | `{revision}` | species active or unchanged; birth not in the future | `animal.updated` |
| `set_animal_archived` | `animal_id`, `archived` | `{revision}` | same state: no write | `animal.archived` / `animal.restored` |
| `create_animal_client_relation` | `animal_id`, `client_id`, `create_request_id`, `relation_role`, optional `started_on` | `{id, revision}` | both in one writable workspace (else 42501); both active; no current duplicate; at most 20 current and 200 total relations per animal and 100 000 per workspace (`limit_reached`); `started_on` not in the future | `animal_client_relation.created` |
| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` |
| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` |
| `delete_animal_client_relation` | `relation_id`, `expected_revision` | `void` | only if §13.2 N4 is approved; animal active; explicit confirmation in the UI | `animal_client_relation.deleted` |
| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; not voided; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` |
| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; not voided; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` |
| `void_animal_client_relation` | `relation_id`, `expected_revision` | `{revision}` | N4: a relation entered by mistake, current or ended; animal active; not already voided; sets `voided_at = now()`, changes no other column; explicit confirmation in the UI; no deletion | `animal_client_relation.voided` |
The combined journeys use the atomic `create_animal` with its optional
relation. « New client with a first animal » is two calls (`create_client`,
@@ -741,9 +859,12 @@ after a failure resumes at the missing call and never creates a second client.
"Not in the future" allows up to the UTC date of tomorrow (and its year for
`birth_year`), so a date that is today in any time zone is accepted; the form
checks against the device's local date. Audit metadata is `{workspace_id}`,
plus `{relation_role}` on relation actions: no changed-field list, no name,
contact, date or search term.
checks against the device's local date. Audit rows (N9) hold the technical
ids (actor, resource, workspace in `metadata` as `{workspace_id}`), the
action and its time: no relation role, no changed-field list, no name,
contact, date or search term. A row exists only for a committed write, so its
presence is the result; refusals write nothing, which keeps a caller from
growing the log by failing on purpose.
Read RPCs: `language plpgsql`, `security invoker` (RLS applies), stable,
`set search_path = ''`, `#variable_conflict use_column`, parameters referenced
@@ -840,8 +961,8 @@ migration.
| Search term | 0 to 100 characters after trimming | a name or a phone fits; longer is noise | RPC |
| Records per workspace | 20 000 clients, 20 000 animals, 100 000 relations | a full-time practitioner sees roughly 1 000 to 2 000 visits a year, so 20 000 animals is more than a decade of distinct animals for one person | RPC, under the workspace or animal row lock |
| Relations per animal | 20 current, 200 in total | co-owners, keeper and contacts fit in 20; 200 covers decades of sales; the animal page reads them in one select | RPC |
| Write rate | 1 000 audited writes per actor per rolling hour and 5 000 per rolling day, every audit row of the actor counted on the existing `audit_logs_actor_idx` | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) |
| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to ids and the relation role | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) |
| Write rate | 1 000 audited writes per workspace per rolling hour and 5 000 per rolling day (owner, N6), counted under a per-workspace lock (§9.3); the counter is fixed with M2 | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) |
| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to the workspace id (N9) | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) |
| Concurrent writes | optimistic `revision` on every update; locks of §9.3 (workspace row for creates, animal then client row for relations, the row itself for archive); idempotent creates through `create_request_id` | no silent overwrite between two tabs or devices, no cap overshoot, no duplicate on retry | SQL and RPC |
| Enumeration | random uuid ids; one 42501 `not_found` for an unknown and a forbidden id in every RPC, with no lock taken outside the caller's workspaces; reads filtered by RLS return empty, never an error that says "exists"; searches limited to one workspace of the caller; closed codes, never values, in errors | | RLS, RPC |
| Login, sign-up, email sending | existing GoTrue limits (`[auth.rate_limit]` in `config.toml`); per-IP limits on `/rest/v1` at the production reverse proxy | | GoTrue; infrastructure (deploy notes) |
@@ -879,7 +1000,7 @@ only, never a name or a search term.
| `/app/clients/:clientId/edit` | client form |
| `/app/animals` | list (name, species, breed, sex, current owners or « Propriétaire non renseigné »), search, species filter, « archivés » filter, « Nouvel animal » |
| `/app/animals/new` | animal form with optional client selection or inline client creation; prefilled when opened from a client |
| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct (and remove per N4) a relation; edit, archive or restore |
| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct the dates of, or void (N4) a relation; edit, archive or restore |
| `/app/animals/:animalId/edit` | animal form |
An unknown id and a forbidden id show the same « introuvable » screen.
@@ -1083,19 +1204,22 @@ without the owner's go.
| D15 | Principle of technical caps protecting the service, distinct from commercial quotas; thresholds proposed in §10 for validation before the RPCs |
| Naming | Explicit nomenclature (§3); no generic `owner_id` |
### 13.2 Technical choices to validate before the first migration
### 13.2 Technical choices, decided by the owner on 2026-10-25 (BDR-074)
| Id | Question | Recommendation | Alternative |
The owner validated N1 to N9 with the precisions of the last column; they
prevail over the recommendation where they differ (N4, N6, N9).
| Id | Question | Recommendation (preparation) | Owner decision, 2026-10-25 |
|---|---|---|---|
| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | English nouns (`donkey`, `dog`…), which mixes two schemes since `equine` cannot be renamed (sheets and reports cite it) |
| N2 | First and last names for persons (D4a) | not in V1-1: no V1-1 screen reads them, search and sort use the display name, and adding two nullable columns later touches no row | add `given_name` and `family_name` now with the priority rule of §5.1 |
| N3 | Client notes (not in the ratified list; animal notes deferred) | defer, like animal notes: minimisation, and free text is where sensitive data slips in | keep `notes` (at most 2 000 characters, with a hint to record only what the care needs) |
| N4 | Removing a relation entered by mistake | allow an explicit, confirmed, audited deletion (`delete_animal_client_relation`): ending a wrong relation would record a false « ancien propriétaire », against the accuracy principle; this is an exception to plan principle 4 (no deletion of user data), limited to relations | a `voided_at` flag hidden from every read (keeps the wrong row, adds a filter everywhere), or no correction (end it) |
| N5 | Relation dates | `started_on` and `ended_on` as optional business dates, plus `ended_at` as the owner named it: null while current, the time the end was recorded, so an end with an unknown date never invents one | `ended_at` alone, which stores the recording time as the end date |
| N6 | Thresholds of §10 | as proposed | other values |
| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` (the precedent of the files migration): no direct read path. It does not close the GoTrue admin path (§6.3): the key stays a full-access credential, bounded by its custody | default Supabase privileges for `service_role` (bypasses RLS: one request reads every record) |
| N8 | Sex in the form | three explicit choices, none preselected: one tap more, but « inconnu » then means unknown, not skipped | « Inconnu » preselected |
| N9 | Audit rows read by platform owners and admins | exclude `client.*`, `animal.*` and `animal_client_relation.*` actions from `audit_logs_select_admin` now (a new policy condition in M2): what they reveal (§6.3) is activity of private records, which D16 keeps from staff; incident work reads them through the exceptional-access path | keep the existing policy until the exceptional-access contract |
| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | approved: exactly the nine species of the contract plus `other` with a required detail, no invented species, no historical anatomical id renamed; compatibility with the Rust model and Supabase checked before freezing anything (§5.4: rows, not an enum) |
| N2 | First and last names for persons (D4a) | not in V1-1 | approved: no separate names in V1-1; `display_name` is the required reference and the single source of truth |
| N3 | Client notes | defer, like animal notes (minimisation) | approved: deferred; no free-text field without an identified business need |
| N4 | Correcting a relation entered by mistake | an explicit, audited deletion | changed: a traceable logical voiding (`voided_at`, `void_animal_client_relation`), distinct from the normal end of a relation; a voided relation stops appearing as current or former without its history being falsified; `ended_on` never represents a period that never existed; minimised audit row (§5.3, §9.3); nothing built before V1-1.4 |
| N5 | Relation dates | optional `started_on` and `ended_on`, plus `ended_at` recording time | approved: both dates optional, never invented, ordered when both are known; an end date is not a deletion; SQL constraints written in §5.3 before V1-1.4 |
| N6 | Thresholds of §10 | as proposed, write budget per actor | approved as technical caps (not commercial quotas), with the write budget per workspace: 1 000 an hour, 5 000 a day; caps enforced consistently under concurrency, never a bare count then an unprotected insert; counters and locks documented when the RPCs are written; no quota system in V1-1.1 |
| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` | approved as minimisation, without claiming it removes every administrative path: effective grants examined, direct privileges removed, EXECUTE limited, definer owners checked, access tested for anon, authenticated and service_role; global Supabase privileges and existing tables unchanged without a specific decision; the GoTrue admin residual risk stays on the pre-production security track (§6.3) |
| N8 | Sex in the form | three explicit choices, none preselected | approved: nothing preselected, « Inconnu » chosen explicitly, a missing answer never turned into a value |
| N9 | Audit rows read by platform owners and admins | exclude the V1-1 actions from `audit_logs_select_admin` (M2) | approved: no general staff view of private client and animal data; audit rows limited to technical id, operation, time, result and bounded validated correlation ids; no name, contact, observation or business data; append-only kept; caller-controlled growth bounded (correlation cap in M1, §8.1) |
### 13.3 Interface decisions still open
@@ -1132,8 +1256,8 @@ validates after V1-1.1 and after the first UI step; nothing merges into
| Step | Content |
|---|---|
| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012` |
| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards, N9 audit policy, field limits and parity test, access layer, real-stack e2e |
| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), awaiting the owner's checkpoint; not applied to DEV |
| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, access layer (with the personal workspace read deferred from V1-1.1), real-stack e2e |
| V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13) |
| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof |
| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry |
@@ -1158,7 +1282,8 @@ Risks and dependencies:
- DEV holds fictitious data only until the legal framing (§7.3);
- `docs/design/README.md` places the mobile tab bar « with the first list
screens », which D11 contradicts until the owner decides;
- the RPC surface grows by fourteen functions (RR-4 review);
- the RPC surface grows by fourteen functions (RR-4 review); N4 replaces the
delete RPC by `void_animal_client_relation`, so the count is unchanged;
- the D-R7 chore for the existing forms reuses the V1-1 constants module;
- no CI runs on the forge: every gate is local;
- two old R5.6 rehearsal worktrees in an earlier session's scratchpad hold