From 6bf69787cb72d58e4340ca9081ab6bb4ed95ddeb Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:08:33 +0100 Subject: [PATCH] chore(memory): BDR-074, EVAL-036, V1-1.1 journal, TODO, gate contract --- .claude/memory/decisions.md | 8 +++ .claude/memory/evals.md | 7 +++ .claude/memory/journal.md | 5 ++ .claude/tasks/TODO.md | 16 +++-- .../contracts/2026-10-25-v1-1-1-workspaces.md | 58 +++++++++++++++++++ 5 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 0fcf2fa3..f2a17de9 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -542,3 +542,11 @@ Decision (owner brief « V1-1 : ratification des décisions métier et préparat Still open: D10-D14, D17 (UI); technical design (SQL/RLS/RPC, N1-N9, D15 thresholds, U1-U3) awaits owner validation at V1-1 preparation checkpoint; no migration before. Contract restructured: verification now §6.2 (BDR-072 cites old §5.2). Alt: keep proposals open; global client record (2026-10-08 plan Step 12); `owner_user_id` column instead of workspaces. Status: active. Branch `feature/v1-1-clients-animals` off develop 5502617. Contract `docs/development/V1-1_OWNERS_ANIMALS.md` §13.1. + +## BDR-074 | 2026-10-25 | V1-1 architecture + N1-N9 validated by owner; V1-1.1 M1 workspaces built in isolation + +Decision (owner brief « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces »): V1-1 model accepted as target (workspaces + members, one personal ws per practitioner, cabinets later as shared ws, no organizations table, isolation per ws, clients person|structure, animals per ws, N-N relations, composite FKs, D-R7 TS forms + SQL CHECK boundary, RLS at creation, RPC writes). 6-step split accepted; only V1-1.1 authorised. N1 9 species + other, rows not enum, ids unchanged (Rust species_id free string, SQL CHECK fits). N2 no first/last names. N3 client notes deferred. N4 CHANGED: logical voiding (`voided_at`, `void_animal_client_relation`) ≠ end; voided never shown current/former, no invented `ended_on`, minimised audit; delete RPC dropped. N5 dates optional, never invented, ordered; CHECKs written in contract §5.3. N6 caps approved, write budget PER WORKSPACE (1000/h, 5000/day), concurrency-safe (no bare count+insert), mechanism fixed with M2. N7 service_role minimisation w/o claiming admin paths closed; existing tables/global privileges untouched. N8 sex none preselected. N9 no staff general view; audit = technical ids, op, time, result, bounded correlation; metadata `{workspace_id}` only (relation_role dropped). D10-D14, D17, U1-U3 stay contract-level; tab-bar contradiction → V1-1.3. +M1 as built (`20261025100000_workspaces.sql`): creation = server init in sign-up tx (trigger on profiles → `private.ensure_personal_workspace` one-statement CTE, ON CONFLICT on named unique `workspaces_personal_user_unique`); deferred constraint triggers `workspaces_personal_holder`/`workspace_members_personal_holder` (personal ws = exactly its account as holder, any writer); backfill once; `caller_workspace_ids` (active + email confirmed, auth.uid only) EXECUTE authenticated; `writable_workspace_ids` EXECUTE none; revoke all incl. service_role on new tables/functions; log_event correlation cap + NOT VALID CHECK. +Deviations: `packages/supabase/src/workspaces.ts` → V1-1.2 (no consumer); `db:reset && db:test` on DEV replaced by isolated sandbox (owner kept DEV untouched). +Alt: workspace created at first authorised login (client-triggered, forgeable timing, partial-state risk); invariant only by grants (owner-role bugs undetected); per-actor budget (cabinet-blind). +Status: active. M1 not applied to DEV (owner action, SUPABASE.md §3.3). Contract §5.3, §8.1, §9, §10, §13.2. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 8fbfff28..9994d592 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -253,3 +253,10 @@ Action: V1-1 contract §1 + §8.3 follow D-R7. Check every proposal against Anne Method: plan-challenger ×3 (correctness, robustness, simplicity) on `V1-1_OWNERS_ANIMALS.md` before owner checkpoint; evidence read from migrations, harness, worker config, react-router dist. Anomaly: draft claimed (1) N7 service_role revoke → "D16 holds at key level" (false: service key = GoTrue admin key → magic link / set password → user session); (2) identical 42501 while reusing `require_actor()` (two messages); (3) audit growth bounded (false: `log_event` stores attacker-sized `x-correlation-id`). Also phone search vs E.164 broken, OR search unindexable, backfill untestable, multi-call create duplicates, relation RPCs race, useBlocker needs data router. Action: all integrated into contract §6.3, §8-§12, §14 + TODO. Claims about key/role reach need proof via the auth admin API too, not only PostgREST grants. + +## EVAL-036 | 2026-10-25 | V1-1.1 M1 workspaces: gates and isolated real stack + +Method: fresh verifier on contract `.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md` + fresh security auditor (semgrep 3 rulesets + hand SQL review), PGlite + sandbox runs, 5 mutations of M1 (email check, ON CONFLICT, correlation cap, foreign-member guard, service_role EXECUTE) all caught by 012. +Result: security PASS (2 MEDIUM scanner false positives: policy via helper, not raw auth.uid(); LOWs = table names in 42501, residual admin paths, NOT VALID CHECK, pre-existing bounded revoke reason). Verifier C1-C8 MET, C9 UNVERIFIABLE (forbidden to read DEV) → closed by `supabase migration list --local` (M1 remote empty). +Anomalies: first mutation run misread (sed indentation miss, crash not printed) → rerun with crash capture; concurrency script pipefail printed false "UNEXPECTED" after real ERROR → fixed. GoTrue 500 on same-email concurrent sign-up = GoTrue race on users_email_partial_key, not M1. +Action: contract for gates should name a read-only way to check DEV state (migration list) so C9-type clauses are verifiable. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index b0c1847d..6eb7069e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -400,3 +400,8 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp ## 2026-10-25 (V1-1 ratification + preparation, branch feature/v1-1-clients-animals) - Owner ratified V1-1 business decisions (BDR-073). Branch via gitflow lib off develop 5502617, pushed. Contract rewritten: approved §13.1, nomenclature §3, SQL M1-M3, RLS/helpers/RPCs §9, D15 thresholds §10, UI §11, tests §12, N1-N9 + D10-D14/D17/U1-U3 open, 6 steps in TODO. - 3 challengers: CONCERNS, findings integrated (EVAL-035). Stop at checkpoint: no migration, no dependency, no Supabase DEV change. + +## 2026-10-25 (V1-1.1 workspaces, branch feature/v1-1-clients-animals) +- Owner validated V1-1 architecture + N1-N9 (BDR-074; N4 voiding, N6 budget per workspace, N9 ids-only audit). Built M1 `20261025100000_workspaces.sql` + pgTAP 012 (85) + config test; commits 7bf4fb6 (code), 0f8c983 (docs). +- Isolated sandbox (DEV images, own net, loopback ports, no volume): fresh + upgrade paths, 531 pgTAP, concurrency, 33 HTTP checks; types generated there (sslmode=disable). DEV untouched (migration list: M1 local only). +- Gates: security PASS (0 HIGH), verifier ECARTS(1) = C9 unverifiable by it, closed by read-only migration list. rust:check + check:all green. STOP at checkpoint; M1 on DEV = owner action (SUPABASE.md §3.3). diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 0fe1dd6a..7bbc728d 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -382,8 +382,16 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - [x] owner ratification 2026-10-25 (brief « V1-1 : ratification des décisions métier et préparation de l'implémentation », BDR-073): D1-D9a, C4-C6, D16, D15 principle, naming - [ ] V1-1 clients and animals: branch `feature/v1-1-clients-animals` (gitflow start off develop 5502617, pushed); contract `docs/development/V1-1_OWNERS_ANIMALS.md` (§3 nomenclature, §8 SQL, §9 RLS/RPC, §10 D15, §11 UI, §12 tests, §13 decisions). Each step = commits on this branch; owner validates after V1-1.1 and after the first UI step; merge into develop only on the owner's go. Gates every step: `pnpm typecheck && pnpm test:run && pnpm lint`; SQL steps also `pnpm db:reset && pnpm db:test`, `pnpm db:types:check`; UI steps through the design toolchain (Build UI) following `docs/design/`. - [x] V1-1.0 preparation (docs only): branch checks (develop = origin/develop 5502617, tree clean, P0 merged dae74e0; two stale R5.6 rehearsal worktrees in an old session scratchpad hold edits, left untouched); contract statuses approved; nomenclature; SQL schema M1-M4; helpers, RLS, RPCs, failures, definer statement; D15 thresholds; journeys, forms, a11y; pgTAP/e2e/Playwright plan; decisions N1-N9, D10-D14, D17, U1-U3; BDR-073; OPEN_QUESTIONS C4/C5/C6/Q6; plan Step 10/12 notes; DOMAIN_MAP, CLAUDE.md, README, TEST_STRATEGY citations; 3 fresh plan challengers (correctness, robustness, simplicity: CONCERNS, findings integrated: search keys, phone search, GoTrue admin path, correlation header cap, idempotent creates, locks, identical errors, backfill function, behavioural parity, Chromium-only V1-1, beforeunload guard, derived values, 6 steps / 3 migrations) - - [ ] CHECKPOINT: owner validates the technical design (§8-§10) + N1-N9 + D10-D14, D17, U1-U3 → STOP until then (no migration, no dependency) - - [ ] V1-1.1 Workspaces foundation + - [x] CHECKPOINT: owner validated the contract architecture + N1-N9 2026-10-25 (brief « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces »); D10-D14, D17, U1-U3 stay contract-level until their UI steps; only V1-1.1 authorised + - [ ] V1-1.1 Workspaces foundation (owner brief 2026-10-25; isolated test DB only, DEV stack untouched, stop at checkpoint) + - [x] contract: N1-N9 as decided (N4 voiding instead of deletion, N6 budget per workspace + concurrency rule, N7 effective-privilege wording, N9 metadata list), M1 as-built notes + - [x] M1 `20261025100000_workspaces.sql`: enums, tables, deferred personal-holder invariant, `ensure_personal_workspace` + trigger + backfill, helpers, `log_event` correlation cap + NOT VALID CHECK, grants (service_role included), RLS + - [x] pgTAP `012_workspaces.sql` + `001_schema.sql` census; schema-types map; config test (`enable_confirmations`, schemas) + - [x] isolated real stack in the scratchpad (own network, loopback ports only): migrations from zero, pgTAP, GoTrue sign-up + confirmation, PostgREST role probes, concurrency + idempotence, seed accounts + - [x] types regenerated from the isolated DB; `pnpm typecheck && pnpm test:run && pnpm lint` + - [x] docs: SUPABASE.md §3.3 (+ DEV procedure), BACKEND_ARCHITECTURE §4.1/§4.2, TEST_STRATEGY counts, IMPLEMENTATION_PLAN note, CLAUDE.md; BDR-074, journal + - [ ] fresh verifier + security audit on M1; `pnpm rust:check`, `pnpm check:all`; commits pushed; checkpoint report + - Deviation from the line below: `packages/supabase/src/workspaces.ts` deferred to V1-1.2 (no consumer before the clients access layer; brief authorises M1 + tests) - Objective: every account has exactly one personal workspace, readable by itself only, with the helpers every later table uses; audit rows no longer sized by the caller - Depends: checkpoint - Files: `supabase/migrations/_workspaces.sql`; `supabase/tests/012_workspaces.sql`; `supabase/tests/001_schema.sql` (tables, RLS, privileges, helper census); `packages/supabase/src/database.types.ts` (regenerated); `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspace`) + `src/index.ts`; `packages/supabase/tests/db/schema-types.test.ts`; config test (`enable_confirmations = true`); `docs/development/SUPABASE.md` @@ -396,7 +404,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack - Depends: V1-1.1; N2, N3, N6, N9 decided - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated - - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget` (1 000/h, 5 000/day); enum `client_kind`; `clients` (`name_key`, `search_key`, `phone_digits`, `create_request_id`); `create_client`, `update_client`, `set_client_archived`, `search_clients`; N9 condition on `audit_logs_select_admin`; grants; RLS + - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget(p_workspace_id)` (N6: per workspace, 1 000/h, 5 000/day, counted under a per-workspace lock; document counter + lock order in contract §9.3); enum `client_kind`; `clients` (`name_key`, `search_key`, `phone_digits`, `create_request_id`); `create_client`, `update_client`, `set_client_archived`, `search_clients`; N9 condition on `audit_logs_select_admin`; grants; RLS - Tests: contract §12.1 rows for clients (whole-error identity, no lock outside the workspace, archived before conflict, replayed request id, caps, budgets, audit without values, search accents/case/backslash/phone formats/keyset); parity test; e2e cross-account + service key refused + GoTrue admin delete; search time on 20 000 clients recorded - Acceptance: gates green; e2e green on the local stack; measurement written in the contract - Security: constraint and parse errors caught inside RPCs; text parameters parsed in the body; search through POST; definer census @@ -414,7 +422,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - Objective: animals with the ten species rows and the D6b birth model, relations with history, never across workspaces - Depends: V1-1.2; N1, N4, N5, N8 decided - Files: `supabase/migrations/_animals_relations.sql`; `supabase/tests/014_animals_relations.sql`; `field-limits.ts` + parity test; `packages/supabase/src/{animals,relations}.ts`; e2e extended; types regenerated - - Migration M3: species rows (9 + `other`), table comment; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations` (composite FKs, partial unique index, request ids); `create_animal` (optional initial relation), `update_animal`, `set_animal_archived`, `search_animals`, relation create/end/update/(delete if N4); `list_client_animals`, `client_archive_preview`; grants; RLS + - Migration M3: species rows (9 + `other`), table comment; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations` (composite FKs, partial unique index, request ids); `create_animal` (optional initial relation), `update_animal`, `set_animal_archived`, `search_animals`, relation create/end/update/void (N4: `voided_at`, `void_animal_client_relation`, never delete); `list_client_animals`, `client_archive_preview`; grants; RLS - Tests: five birth states; `species_detail` iff `other`; inactive species; dates incl. 31 December UTC; cross-workspace refused by RPC (42501) and by FK; duplicates and the concurrent race; successive relations; archived interactions (§7.1) under locks; caps per animal and per workspace; derived values; D9a (account with records cannot be deleted, empty one is); report, sheet and editor species ids unaffected - Acceptance: gates green; e2e green; local tool and PDF unchanged - Security: same whole error for every foreign id; FK proof independent of the RPC; animal-then-client lock order diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md new file mode 100644 index 00000000..97fa6607 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md @@ -0,0 +1,58 @@ +# CONTRACT: V1-1.1 Workspaces (M1), owner brief 2026-10-25 « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces » + +- branch `feature/v1-1-clients-animals`, base 5d734be; code commit 7bf4fb6 +- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §3, §4, §8 (M1 sketch), §9.1, §9.2, §9.5, §10, §12.1 +- diff under review: `git diff 5d734be..HEAD -- supabase packages/supabase` +- isolated real-stack evidence: `/tmp/claude-1000/-home-bchanot-Documents-faunosteo/55c1fd3e-1c33-4c77-8509-9cd3ca683a18/scratchpad/sandbox/` + (`RESULTS.md`; scripts `up.sh`, `tap.sh`, `concurrency.sh`, `http.mjs`, `down.sh`; containers `faunosteo_m1sandbox_*` + running, same images as the DEV stack). `tap.sh` and `node http.mjs` may be re-run (rolled back / unique emails); + `concurrency.sh` inserts fixed ids and runs once per sandbox. The DEV stack (`supabase_*_faunosteo`) must not be touched. + +## Clauses + +C1. **Scope.** One migration only, `supabase/migrations/20261025100000_workspaces.sql` (M1). No M2/M3 object (no clients, +animals, relations, species rows, unaccent, fold_text, write budget, write RPC), no React screen, no Playwright, no cabinet +feature, no change to crates/, no change to an existing migration file, no change to existing tables' grants or policies +except the `private.log_event` redefinition and the NOT VALID CHECK on `audit.audit_logs.correlation_id`. + +C2. **Model.** Enums `workspace_kind` = {personal} and `workspace_member_role` = {holder} only (no unused cabinet role); +`workspaces(id, kind, personal_user_id unique → profiles on delete cascade, created_at)` with CHECK personal ⇔ +personal_user_id not null; `workspace_members(workspace_id → workspaces cascade, user_id → profiles cascade, member_role, +created_at, PK (workspace_id, user_id))`, index on user_id. No `owner_id`; names as in contract §3. No archive column: +a workspace follows its account (deletion cascades; M2's `on delete restrict` will block it when records exist, D9a). + +C3. **Creation.** Server-side only: trigger after insert on `profiles` → `private.ensure_personal_workspace(uuid)`, which +writes workspace and holder membership in one statement with ON CONFLICT on the unique key (atomic, idempotent, race-safe); +`private.backfill_personal_workspaces()` covers existing profiles, idempotent, called once by the migration after the +trigger exists. No API role can call either. Works with the existing sign-up chain (GoTrue → `handle_new_auth_user` → +profile → workspace, one transaction); the workspace exists before email confirmation and stays unreadable until then. + +C4. **Integrity.** A deferred constraint trigger refuses at commit, whatever role writes: a personal workspace without its +holder, a foreign member in a personal workspace, the removal of the holder alone, the transfer of a personal workspace to +another account. Cabinets are not constrained. Error messages carry no id or personal data. + +C5. **Access rule.** `private.caller_workspace_ids()`: no parameter, `auth.uid()` only, member + `profiles.active` + +`auth.users.email_confirmed_at is not null`; security definer, `search_path = ''`, owner postgres, EXECUTE for +`authenticated` only. `private.writable_workspace_ids()`: same restricted to holder, EXECUTE for nobody. No platform-role +branch anywhere (D16). The private schema stays out of PostgREST (`config.toml` schemas = public, pinned by a test). + +C6. **RLS and privileges.** RLS enabled on both tables; one SELECT policy each, for `authenticated`, through +`caller_workspace_ids()`, no `using (true)`; no write policy. `revoke all` from public, anon, authenticated, service_role, +then column SELECT grants to authenticated only. Every new function: `revoke all` from public, anon, authenticated, +service_role; security definer; `search_path = ''`; owner postgres. Effective privileges tested for anon, authenticated and +service_role (SQL refusal 42501 distinct from an empty RLS result). + +C7. **Audit (N9).** `private.log_event` keeps its signature, privileges and callers; `x-correlation-id` stored only when it +matches `^[A-Za-z0-9-]{1,64}$`, else null; `audit_logs_correlation_id_format` CHECK NOT VALID on new rows. Append-only kept. + +C8. **Tests.** pgTAP `supabase/tests/012_workspaces.sql` covers: creation with the account, holder membership, failed sign-up +leaves nothing, idempotence, uniqueness, FK/PK refusals, backfill (trigger disabled) and its idempotence, the commit +invariant, A/B isolation, refusal for unconfirmed (then access after confirmation), deactivated, platform staff, anon, +service_role, parameter usurpation (filters by other ids, inserts naming others), direct calls of private functions, the +privilege/definer/owner census, the empty account deletion, the correlation cap. `001_schema.sql` census updated; +`schema-types.test.ts` and `database.types.ts` (regenerated, only M1 additions); `config.test.ts` pins +`enable_confirmations = true`, anonymous sign-ins off, schemas = public. All green on PGlite (`pnpm test:run`) and on the +isolated real stack from zero and on the upgrade path (sandbox `RESULTS.md`), with real concurrency evidence. + +C9. **Limits.** Nothing applied to the DEV stack; no merge into develop; main and release/0.2.0 untouched; no deploy; +no real personal data in fixtures.