-- V1-2.1 M5 sheet_review_workflow. Contract: -- docs/development/V1-2_ANATOMICAL_SHEETS.md §6 (lifecycle, review, verdict, -- publication), §7 (species, new sheets), §9 (drawings), §12.2 (SQL authority), -- §12.3 (M5), §14.3 (working copy). Applied together with M4. -- -- M5 adds the reviewed authoring workflow that replaces the Step 4 lifecycle: -- * version provenance and review columns, a sheet working-copy column; -- * triggers: revision bump and author set on every content write, the -- draft freeze while a round runs, the extended publication/immutability -- guard; the historical sheet stays writable only for the seed; -- * review rounds, comments and acknowledgments; -- * the authoring RPCs: create an official sheet, open a draft, save, submit, -- withdraw, comment, acknowledge, approve or request changes, publish, -- deprecate, archive, restore, delete a draft; the equine working copy; -- * species RPCs (create inactive, edit inactive, activate, rename); -- * catalogue and version read RPCs; -- * uploads: register (historical sheet refused), confirm with a Storage -- existence and size check (F7), an INSERT policy for the pending key, the -- bucket limit lowered to 2 MiB, an operator read RPC; -- * the SQL business mirror removed, one declared status check kept (§12.2). -- The verdict itself is written by the worker RPCs of M6: until then a round -- never leaves `verifying` except a withdrawal, so nothing is published -- outside the pgTAP fixtures that stand in for the worker. -- =========================================================================== -- 1. Enums, version/sheet columns, review tables -- =========================================================================== create type public.sheet_round_status as enum ( 'verifying', 'open', 'approved', 'changes_requested', 'withdrawn', 'verification_failed' ); create type public.sheet_verification_outcome as enum ('failed', 'unavailable'); alter table public.anatomical_sheet_versions add column revision integer not null default 0 constraint anatomical_sheet_versions_revision_nonneg check (revision >= 0), add column authors uuid[] not null default '{}', add column source_version_id uuid references public.anatomical_sheet_versions (id) on delete set null, add column published_review_id uuid, add column document_fingerprint text constraint anatomical_sheet_versions_fingerprint_format check (document_fingerprint is null or document_fingerprint ~ '^[0-9a-f]{64}$'), -- A drawing is at most 2 MiB (archive cap, §9.1): new rows only. add constraint anatomical_sheet_versions_published_fingerprint check (status <> 'published' or document_fingerprint is not null); -- The document cap is the contract's measure (§12.2): the UTF-8 bytes of the -- document's JSON text, `octet_length(content::text)`. The base CHECK measured -- the binary jsonb (`pg_column_size`), larger than the text for a document of -- many small values, so a conforming draft could hit a raw constraint error. alter table public.anatomical_sheet_versions drop constraint anatomical_sheet_versions_content_size, add constraint anatomical_sheet_versions_content_size check (octet_length(content::text) <= 2097152); alter table public.anatomical_sheets add column working_copy_source_version_id uuid references public.anatomical_sheet_versions (id) on delete set null; comment on column public.anatomical_sheet_versions.authors is 'Author set (contract §5.5): the account that created the draft and every account that changed its content since. Maintained by the content trigger, frozen into the round at submission.'; comment on column public.anatomical_sheet_versions.source_version_id is 'The base of a derived draft: set only when the source is a version published through a V1-2 round (contract §6.2).'; create table public.anatomical_sheet_reviews ( id uuid primary key default gen_random_uuid(), version_id uuid not null references public.anatomical_sheet_versions (id) on delete restrict, round integer not null constraint anatomical_sheet_reviews_round_positive check (round > 0), revision integer not null, authors uuid[] not null, submitted_by uuid not null references public.profiles (id) on delete restrict, submitted_at timestamptz not null default now(), submission_note text constraint anatomical_sheet_reviews_submission_note_length check (char_length(submission_note) <= 1000), status public.sheet_round_status not null default 'verifying', attempts integer not null default 0, lease_token uuid, locked_at timestamptz, verdict jsonb constraint anatomical_sheet_reviews_verdict_object check (verdict is null or jsonb_typeof(verdict) = 'object'), verified_at timestamptz, verified_with text constraint anatomical_sheet_reviews_verified_with_length check (char_length(verified_with) <= 100), failure_outcome public.sheet_verification_outcome, failure_code text constraint anatomical_sheet_reviews_failure_code_format check (failure_code ~ '^[a-z][a-z0-9_.]{0,60}$'), decided_by uuid references public.profiles (id) on delete restrict, decided_at timestamptz, decision_note text constraint anatomical_sheet_reviews_decision_note_length check (char_length(decision_note) <= 4000), withdrawn_by uuid references public.profiles (id) on delete restrict, withdrawn_at timestamptz, withdrawal_note text constraint anatomical_sheet_reviews_withdrawal_note_length check (char_length(withdrawal_note) <= 1000), created_at timestamptz not null default now(), constraint anatomical_sheet_reviews_round_unique unique (version_id, round) ); comment on table public.anatomical_sheet_reviews is 'Review rounds of a draft version (contract §6.3). One row per round; one non-terminal round per version at a time; the verdict is written by the worker RPCs (M6).'; -- One non-terminal round per version (contract §6.1). create unique index anatomical_sheet_reviews_one_open on public.anatomical_sheet_reviews (version_id) where status in ('verifying', 'open', 'approved'); create index anatomical_sheet_reviews_verifying_idx on public.anatomical_sheet_reviews (submitted_at) where status = 'verifying'; alter table public.anatomical_sheet_versions add constraint anatomical_sheet_versions_published_review_fkey foreign key (published_review_id) references public.anatomical_sheet_reviews (id) on delete restrict; create table public.anatomical_sheet_review_comments ( id uuid primary key default gen_random_uuid(), review_id uuid not null references public.anatomical_sheet_reviews (id) on delete cascade, author uuid not null references public.profiles (id) on delete restrict, group_key text constraint anatomical_sheet_review_comments_group_key_format check (group_key ~ '^(general|view:|zone:)'), body text not null constraint anatomical_sheet_review_comments_body_length check (char_length(body) between 1 and 4000), created_at timestamptz not null default now() ); comment on table public.anatomical_sheet_review_comments is 'Append-only comments on a round (contract §6.3): author, body, optional group key.'; create index anatomical_sheet_review_comments_review_idx on public.anatomical_sheet_review_comments (review_id, created_at); create table public.anatomical_sheet_review_acknowledgments ( id uuid primary key default gen_random_uuid(), review_id uuid not null references public.anatomical_sheet_reviews (id) on delete cascade, group_key text not null constraint anatomical_sheet_review_acks_group_key_format check (group_key ~ '^(general|view:|zone:)'), group_digest text not null constraint anatomical_sheet_review_acks_digest_format check (group_digest ~ '^[0-9a-f]{64}$'), reviewer uuid not null references public.profiles (id) on delete restrict, created_at timestamptz not null default now(), constraint anatomical_sheet_review_acks_unique unique (review_id, group_key, reviewer) ); comment on table public.anatomical_sheet_review_acknowledgments is 'Append-only "groupe lu" records (contract §6.3): a reviewer outside the authors acknowledges a group against the verdict''s digest.'; create index anatomical_sheet_review_acks_reviewer_idx on public.anatomical_sheet_review_acknowledgments (reviewer); -- =========================================================================== -- 2. SQL authority: drop the business mirror, keep the structural guards, -- add the declared status check (contract §12.2) -- =========================================================================== drop function private.sheet_document_issues(jsonb); drop function private.sheet_document_view_issues(jsonb); drop function private.sheet_document_annotation_issues(jsonb); drop function private.sheet_document_duplicate_issues(jsonb); drop function private.sheet_document_reference_issues(jsonb); drop function private.append_issue(text[], text); -- Declared status mirror (contract §12.2): a structural walk refusing any -- element whose review_status is absent, to_confirm or inherited. Kept so a -- worker defect can never make unread content official; follows the schema's -- default (absent = inherited). Returns true when every element is reviewed. create or replace function private.sheet_all_reviewed(p_doc jsonb) returns boolean language sql immutable set search_path = '' as $$ select not exists ( -- annotations: review_status on each select 1 from jsonb_array_elements(coalesce(p_doc -> 'annotations', '[]'::jsonb)) a where coalesce(a ->> 'review_status', 'inherited') <> 'reviewed' ) and not exists ( -- finding categories: review_status on each category select 1 from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c where coalesce(c ->> 'review_status', 'inherited') <> 'reviewed' ) and not exists ( -- finding nodes at every depth (categories[*].children and below) select 1 from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c, jsonb_path_query(c, '$.children[*].**{0 to 64}') n where jsonb_typeof(n) = 'object' and n ? 'id' and coalesce(n ->> 'review_status', 'inherited') <> 'reviewed' ); $$; comment on function private.sheet_all_reviewed(jsonb) is 'Declared defensive status check (contract §12.2): true when every annotation, finding category and finding node is reviewed (an absent review_status counts as inherited, so it is refused).'; -- True when any element is explicitly `to_confirm` (contract §6.7 keeps -- `publish.to_confirm.open` apart from `publish.inherited.present`, which -- covers an inherited or omitted status). create or replace function private.sheet_has_to_confirm(p_doc jsonb) returns boolean language sql immutable set search_path = '' as $$ select exists ( select 1 from jsonb_array_elements(coalesce(p_doc -> 'annotations', '[]'::jsonb)) a where a ->> 'review_status' = 'to_confirm' ) or exists ( select 1 from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c where c ->> 'review_status' = 'to_confirm' ) or exists ( select 1 from jsonb_array_elements(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) z, jsonb_array_elements(coalesce(z -> 'categories', '[]'::jsonb)) c, jsonb_path_query(c, '$.children[*].**{0 to 64}') n where jsonb_typeof(n) = 'object' and n ? 'id' and n ->> 'review_status' = 'to_confirm' ); $$; -- True when the scope disclaimer is present and non-blank in FR and EN (O6). create or replace function private.sheet_disclaimer_ok(p_doc jsonb) returns boolean language sql immutable set search_path = '' as $$ select length(btrim(coalesce(p_doc -> 'scope_disclaimer' ->> 'fr', ''))) > 0 and length(btrim(coalesce(p_doc -> 'scope_disclaimer' ->> 'en', ''))) > 0; $$; -- =========================================================================== -- 3. Triggers: revision, author set, freeze, extended publication guard -- =========================================================================== -- A content write bumps the revision and adds the actor to the author set -- (contract §5.5, §6.2). A non-terminal round freezes the content. A content -- write with no authenticated actor is refused for every sheet except the -- historical one (its converging seed). create or replace function private.on_sheet_version_content() returns trigger language plpgsql security definer set search_path = '' as $$ declare v_actor uuid := auth.uid(); begin if tg_op = 'UPDATE' and new.content = old.content then return new; end if; if tg_op = 'UPDATE' and exists ( select 1 from public.anatomical_sheet_reviews r where r.version_id = new.id and r.status in ('verifying', 'open', 'approved') ) then raise exception 'draft.frozen' using errcode = '55000'; end if; if v_actor is null and new.sheet_id <> private.historical_sheet_id() then raise exception 'content write needs an authenticated actor' using errcode = '42501'; end if; if tg_op = 'UPDATE' then new.revision := old.revision + 1; end if; if v_actor is not null and not (new.authors @> array[v_actor]) then new.authors := new.authors || v_actor; end if; return new; end; $$; create trigger anatomical_sheet_versions_on_content before insert or update of content on public.anatomical_sheet_versions for each row execute function private.on_sheet_version_content(); -- Extended immutability guard (contract §6.8), replacing the base version. create or replace function private.guard_sheet_version_update() returns trigger language plpgsql set search_path = '' as $$ begin if new.id <> old.id or new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then raise exception 'id, sheet_id and version_number are immutable' using errcode = '42501'; end if; if old.status = 'deprecated' then raise exception 'deprecated version % is frozen', old.id using errcode = '42501'; end if; if old.status = 'published' then -- Only the deprecation transition, and it changes no V1-2 column. if new.status = 'deprecated' and new.content = old.content and new.document_schema_version = old.document_schema_version and new.change_note = old.change_note and new.created_by is not distinct from old.created_by and new.published_at = old.published_at and new.published_by is not distinct from old.published_by and new.created_at = old.created_at and new.revision = old.revision and new.authors = old.authors and new.source_version_id is not distinct from old.source_version_id and new.published_review_id is not distinct from old.published_review_id and new.document_fingerprint is not distinct from old.document_fingerprint then return new; end if; raise exception 'published version % is immutable', old.id using errcode = '42501'; end if; -- old.status = 'draft' if new.status = 'deprecated' then raise exception 'a draft cannot be deprecated; delete it' using errcode = '55000'; end if; if new.status = 'published' then -- A draft is published only through the gate: an approved round of this -- version and revision whose verdict passed, named by published_review_id. if new.published_review_id is null or not exists ( select 1 from public.anatomical_sheet_reviews r where r.id = new.published_review_id and r.version_id = old.id and r.revision = old.revision and r.status = 'approved' and r.verdict is not null ) then raise exception 'publish.review.missing' using errcode = '42501'; end if; end if; return new; end; $$; -- =========================================================================== -- 4. Authoring helpers and RPCs -- =========================================================================== -- The calling session: an active account with a confirmed email, at aal2 -- (contract §5.6, §6.7). Every catalogue RPC except the readers calls it -- before any lookup or capability check, so an aal1 session gets one answer -- (`rights.mfa`) whatever it asks for and whatever it holds. create or replace function private.require_catalog_actor() returns uuid language plpgsql stable security definer set search_path = '' as $$ declare v_actor uuid := private.require_actor(); begin if not private.has_mfa() then raise exception 'rights.mfa' using errcode = '42501'; end if; return v_actor; end; $$; -- The calling session holds one capability at aal2, returning the actor. create or replace function private.require_capability(p_kind public.catalog_grant_kind) returns uuid language plpgsql stable security definer set search_path = '' as $$ declare v_actor uuid := private.require_catalog_actor(); begin if not private.grant_active(v_actor, p_kind) then raise exception 'rights.capability' using errcode = '42501'; end if; return v_actor; end; $$; -- Require the sheet_editor capability at aal2 on an official, non-deleted -- sheet other than the historical one (writes), returning the actor. The -- capability is checked first, so only an editor learns a sheet is historical. create or replace function private.require_sheet_author(p_sheet_id uuid) returns uuid language plpgsql stable security definer set search_path = '' as $$ declare v_actor uuid := private.require_catalog_actor(); begin if not private.can_edit_sheet(v_actor, p_sheet_id) then raise exception 'rights.capability' using errcode = '42501'; end if; if p_sheet_id = private.historical_sheet_id() then raise exception 'sheet.historical_read_only' using errcode = '42501'; end if; return v_actor; end; $$; -- The sheet_publisher capability at aal2 on an official, non-deleted sheet. create or replace function private.require_sheet_publisher(p_sheet_id uuid) returns uuid language plpgsql stable security definer set search_path = '' as $$ declare v_actor uuid := private.require_catalog_actor(); begin if not (private.grant_active(v_actor, 'sheet_publisher') and exists ( select 1 from public.anatomical_sheets s where s.id = p_sheet_id and s.is_official and s.status <> 'deleted' )) then raise exception 'rights.capability' using errcode = '42501'; end if; return v_actor; end; $$; -- The structural guards a stored document passes at creation, save and -- working copy (contract §12.2): an object whose id-bearing collections are -- arrays, schema version 2, at most 2 MiB as the UTF-8 bytes of its JSON text -- (the table CHECK of section 1 uses the same measure; checked here first so -- the caller gets the closed code, never a raw constraint error). A number -- prints as plain digits (`1e131071` is 131 072 bytes of text), so the printed -- numbers are summed one at a time first: the whole text is built only once it -- stays within the input's size plus the cap, never a gigabyte from a small -- payload (an out-of-memory error instead of the closed code). create or replace function private.check_document_structure(p_doc jsonb) returns void language plpgsql immutable set search_path = '' as $$ declare v_number jsonb; v_number_bytes bigint := 0; begin if not private.sheet_document_has_shape(p_doc) then raise exception 'document.shape' using errcode = '23514'; end if; if (p_doc -> 'schema_version') is distinct from '2'::jsonb then raise exception 'document.schema_version' using errcode = '23514'; end if; -- One jsonb_path_query_array call, then its elements: linear in the number -- count (jsonb_path_query row by row is quadratic on PostgreSQL 17). for v_number in select jsonb_array_elements(jsonb_path_query_array(p_doc, 'strict $.** ? (@.type() == "number")')) loop v_number_bytes := v_number_bytes + octet_length(v_number::text); if v_number_bytes > 2097152 then raise exception 'document.too_large' using errcode = '23514'; end if; end loop; if octet_length(p_doc::text) > 2097152 then raise exception 'document.too_large' using errcode = '23514'; end if; end; $$; -- A new official sheet row (creation and working copy). A slug outside the -- table's format is invalid input; one already used by a non-deleted official -- sheet answers `sheet.slug_taken`, the race included (unique index). create or replace function private.insert_official_sheet( p_species text, p_name text, p_slug text, p_description text, p_source uuid ) returns uuid language plpgsql security definer set search_path = '' as $$ declare v_sheet uuid; begin if p_slug is null or p_slug !~ '^[a-z0-9][a-z0-9-]{1,79}$' then raise exception 'invalid_input' using errcode = 'P0001'; end if; begin insert into public.anatomical_sheets (species_id, name, slug, description, creator_user_id, is_official, visibility, working_copy_source_version_id) values (p_species, p_name, p_slug, p_description, null, true, 'private', p_source) returning id into v_sheet; exception when unique_violation then raise exception 'sheet.slug_taken' using errcode = 'P0001'; end; return v_sheet; end; $$; -- Create an official sheet and its draft v1 from a core-built document. create or replace function public.create_official_sheet( slug text, document jsonb ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_editor'); v_species text := document ->> 'species_id'; v_name text; v_description text; v_sheet uuid; begin perform private.check_document_structure(document); v_name := left(coalesce(nullif(btrim(document -> 'name' ->> 'fr'), ''), nullif(btrim(document -> 'name' ->> 'en'), ''), 'Sans nom'), 120); v_description := left(coalesce(document -> 'description' ->> 'fr', ''), 2000); -- An official sheet accepts an active or inactive species, never `other` (§7.2). if v_species is null or v_species = 'other' or not exists (select 1 from public.species s where s.id = v_species) then raise exception 'sheet.species_invalid' using errcode = 'P0001'; end if; v_sheet := private.insert_official_sheet(v_species, v_name, create_official_sheet.slug, v_description, null); -- The budget row last, after the rows the insert locks through its foreign -- keys (species), as every RPC takes it (M4). perform private.consume_catalog_write_budget(v_actor); perform private.log_event( v_actor, 'anatomical_sheet.created', 'anatomical_sheet', v_sheet, null, null, jsonb_build_object('species_id', v_species, 'official', true) ); perform private.insert_sheet_draft(v_actor, v_sheet, document, 'Brouillon initial'); return v_sheet; end; $$; -- Open the single draft of an official sheet, from a published version. create or replace function public.create_sheet_draft( sheet_id uuid, from_version_id uuid default null, change_note text default '' ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_sheet_author(sheet_id); v_source public.anatomical_sheet_versions%rowtype; v_base uuid; v_draft uuid; begin perform 1 from public.anatomical_sheets s where s.id = create_sheet_draft.sheet_id and s.status = 'active' for no key update; if not found then raise exception 'sheet.inactive' using errcode = '55000'; end if; select v.* into v_source from public.anatomical_sheet_versions v where v.id = coalesce(from_version_id, (select current_version_id from public.anatomical_sheets where id = create_sheet_draft.sheet_id)) and v.sheet_id = create_sheet_draft.sheet_id and v.status <> 'draft'; if v_source.id is null then raise exception 'sheet.no_source' using errcode = 'P0002'; end if; if exists (select 1 from public.anatomical_sheet_versions v where v.sheet_id = create_sheet_draft.sheet_id and v.status = 'draft') then raise exception 'draft.exists' using errcode = 'P0001'; end if; if char_length(create_sheet_draft.change_note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); -- Base only from a version still `published` that was published through a -- V1-2 round (§6.2): a deprecated source gives no base, so every group of -- the new draft is to cover again. v_base := case when v_source.status = 'published' and v_source.published_review_id is not null then v_source.id end; v_draft := private.insert_sheet_draft(v_actor, sheet_id, v_source.content, change_note); update public.anatomical_sheet_versions set source_version_id = v_base where id = v_draft; return v_draft; end; $$; -- Explicit save with a revision check (contract §6.2). create or replace function public.save_sheet_draft( version_id uuid, expected_revision integer, document jsonb, change_note text default '' ) returns jsonb language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_row public.anatomical_sheet_versions%rowtype; begin select v.sheet_id into v_row.sheet_id from public.anatomical_sheet_versions v where v.id = save_sheet_draft.version_id; if v_row.sheet_id is null then raise exception 'not_found' using errcode = '42501'; end if; perform private.require_sheet_author(v_row.sheet_id); -- Lock order sheet, then version (§6.1): an archive waits for this write or -- is seen by it, so nothing lands on a sheet archived in the meantime. perform 1 from public.anatomical_sheets s where s.id = v_row.sheet_id for share; select v.* into v_row from public.anatomical_sheet_versions v where v.id = save_sheet_draft.version_id for update; if v_row.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; -- A draft of an active official sheet only (§6.2): an archived sheet is frozen. if not exists (select 1 from public.anatomical_sheets s where s.id = v_row.sheet_id and s.status = 'active') then raise exception 'sheet.inactive' using errcode = '55000'; end if; if exists (select 1 from public.anatomical_sheet_reviews r where r.version_id = v_row.id and r.status in ('verifying', 'open', 'approved')) then raise exception 'draft.frozen' using errcode = '55000'; end if; if save_sheet_draft.expected_revision is distinct from v_row.revision then raise exception 'draft_conflict' using errcode = 'P0001'; end if; perform private.check_document_structure(document); if char_length(save_sheet_draft.change_note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; if (document ->> 'species_id') is distinct from (select species_id from public.anatomical_sheets where id = v_row.sheet_id) then raise exception 'document.species' using errcode = '23514'; end if; if document = v_row.content then raise exception 'draft.unchanged' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_versions set content = document, change_note = coalesce(save_sheet_draft.change_note, '') where id = v_row.id; perform private.log_event( v_actor, 'anatomical_sheet_version.saved', 'anatomical_sheet_version', v_row.id, null, null, jsonb_build_object('sheet_id', v_row.sheet_id, 'revision', v_row.revision + 1) ); return jsonb_build_object('revision', v_row.revision + 1); end; $$; -- =========================================================================== -- 5. Review rounds: submit, withdraw, comment, acknowledge, decide -- =========================================================================== create or replace function public.submit_sheet_review( version_id uuid, expected_revision integer, note text default null ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_row public.anatomical_sheet_versions%rowtype; v_round integer; v_id uuid; begin select v.sheet_id into v_row.sheet_id from public.anatomical_sheet_versions v where v.id = submit_sheet_review.version_id; if v_row.sheet_id is null then raise exception 'not_found' using errcode = '42501'; end if; perform private.require_sheet_author(v_row.sheet_id); -- Lock order sheet, then version (§6.1): an archive waits for this write or -- is seen by it, so nothing lands on a sheet archived in the meantime. perform 1 from public.anatomical_sheets s where s.id = v_row.sheet_id for share; select v.* into v_row from public.anatomical_sheet_versions v where v.id = submit_sheet_review.version_id for update; if v_row.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; if not exists (select 1 from public.anatomical_sheets s where s.id = v_row.sheet_id and s.status = 'active') then raise exception 'sheet.inactive' using errcode = '55000'; end if; if submit_sheet_review.expected_revision is distinct from v_row.revision then raise exception 'draft_conflict' using errcode = 'P0001'; end if; if exists (select 1 from public.anatomical_sheet_reviews r where r.version_id = v_row.id and r.status in ('verifying', 'open', 'approved')) then raise exception 'round.open' using errcode = '55000'; end if; if char_length(note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; -- Every drawing id of the document is registered for the sheet (§12.2, -- kept at submission and publication). if cardinality(private.sheet_document_unknown_assets(v_row.sheet_id, v_row.content)) > 0 then raise exception 'view.asset.unknown' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); select coalesce(max(round), 0) + 1 into v_round from public.anatomical_sheet_reviews where version_id = v_row.id; insert into public.anatomical_sheet_reviews ( version_id, round, revision, authors, submitted_by, submission_note, status ) values (v_row.id, v_round, v_row.revision, v_row.authors, v_actor, note, 'verifying') returning id into v_id; perform private.log_event( v_actor, 'anatomical_sheet_review.submitted', 'anatomical_sheet_review', v_id, null, null, jsonb_build_object('sheet_id', v_row.sheet_id, 'version_id', v_row.id, 'round', v_round, 'revision', v_row.revision) ); return v_id; end; $$; -- Withdraw a round of a draft in verifying, open or approved; the draft -- unfreezes. The round of a published version stays approved (§6.1): it is -- the version's review link and never withdrawn. create or replace function public.withdraw_sheet_review(review_id uuid, note text default null) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_review public.anatomical_sheet_reviews%rowtype; v_version public.anatomical_sheet_versions%rowtype; v_sheet uuid; begin select r.version_id into v_review.version_id from public.anatomical_sheet_reviews r where r.id = withdraw_sheet_review.review_id; if v_review.version_id is null then raise exception 'not_found' using errcode = '42501'; end if; -- Lock order version, then round (§6.1): a publication holding the version -- either completes first (the version is then no draft) or sees the round -- withdrawn. select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_review.version_id for share; v_sheet := v_version.sheet_id; perform private.require_sheet_author(v_sheet); select r.* into v_review from public.anatomical_sheet_reviews r where r.id = withdraw_sheet_review.review_id for update; if v_version.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; if v_review.status not in ('verifying', 'open', 'approved') then raise exception 'round.terminal' using errcode = '55000'; end if; if char_length(note) > 1000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_reviews set status = 'withdrawn', withdrawn_by = v_actor, withdrawn_at = now(), withdrawal_note = note where id = v_review.id; perform private.log_event( v_actor, 'anatomical_sheet_review.withdrawn', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_sheet, 'round', v_review.round) ); return v_review.id; end; $$; -- A comment on a round: editors, reviewers and publishers. create or replace function public.comment_sheet_review( review_id uuid, body text, group_key text default null ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_review public.anatomical_sheet_reviews%rowtype; v_sheet uuid; v_id uuid; begin if not private.caller_is_catalog_staff() then raise exception 'rights.capability' using errcode = '42501'; end if; select r.* into v_review from public.anatomical_sheet_reviews r where r.id = comment_sheet_review.review_id; if v_review.id is null then raise exception 'not_found' using errcode = '42501'; end if; select sheet_id into v_sheet from public.anatomical_sheet_versions where id = v_review.version_id; if char_length(body) not between 1 and 4000 or (group_key is not null and group_key !~ '^(general|view:|zone:)') then raise exception 'invalid_input' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); insert into public.anatomical_sheet_review_comments (review_id, author, group_key, body) values (comment_sheet_review.review_id, v_actor, group_key, body) returning id into v_id; perform private.log_event( v_actor, 'anatomical_sheet_review.commented', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_sheet, 'comment_id', v_id) ); return v_id; end; $$; -- The verdict's group of a key, with its digest (contract §6.3). The verdict -- carries `groups` as an array of {key, digest, coverable}. create or replace function private.verdict_group_digest(p_verdict jsonb, p_key text) returns text language sql immutable set search_path = '' as $$ select g ->> 'digest' from jsonb_array_elements(coalesce(p_verdict -> 'groups', '[]'::jsonb)) g where g ->> 'key' = p_key limit 1; $$; -- Acknowledge a group of an `open` round, against the verdict's digest. create or replace function public.acknowledge_sheet_review_group( review_id uuid, group_key text, group_digest text ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_reviewer'); v_review public.anatomical_sheet_reviews%rowtype; v_sheet uuid; v_group jsonb; v_id uuid; begin select r.* into v_review from public.anatomical_sheet_reviews r where r.id = acknowledge_sheet_review_group.review_id for update; if v_review.id is null then raise exception 'not_found' using errcode = '42501'; end if; select sheet_id into v_sheet from public.anatomical_sheet_versions where id = v_review.version_id; if v_review.status <> 'open' then raise exception 'round.not_open' using errcode = '55000'; end if; -- No author of the round acknowledges it (contract §5.5). if v_review.authors @> array[v_actor] then raise exception 'review.separation' using errcode = '42501'; end if; -- The group exists in the verdict, its digest matches, and it is coverable -- (no to_confirm or inherited element left in it). select g into v_group from jsonb_array_elements(coalesce(v_review.verdict -> 'groups', '[]'::jsonb)) g where g ->> 'key' = acknowledge_sheet_review_group.group_key limit 1; if v_group is null or v_group ->> 'digest' is distinct from acknowledge_sheet_review_group.group_digest then raise exception 'review.digest' using errcode = 'P0001'; end if; if coalesce((v_group ->> 'coverable')::boolean, false) is not true then raise exception 'review.uncoverable' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); -- Append-only (§6.3): acknowledging a group twice in the same round keeps the -- first row (the verdict, hence the digest, is fixed while the round is open). insert into public.anatomical_sheet_review_acknowledgments (review_id, group_key, group_digest, reviewer) values (acknowledge_sheet_review_group.review_id, group_key, group_digest, v_actor) on conflict (review_id, group_key, reviewer) do nothing returning id into v_id; if v_id is null then select a.id into v_id from public.anatomical_sheet_review_acknowledgments a where a.review_id = acknowledge_sheet_review_group.review_id and a.group_key = acknowledge_sheet_review_group.group_key and a.reviewer = v_actor; return v_id; end if; perform private.log_event( v_actor, 'anatomical_sheet_review.acknowledged', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_sheet, 'group_key', group_key) ); return v_id; end; $$; -- The groups the round must cover, uncovered so far (contract §6.3, §6.7): -- every verdict group when there is no base; for a derived version, every -- group whose digest differs from the base's group of the same key; a group -- is covered by a current or carried acknowledgment (same digest, a reviewer -- outside the authors with an active grant). create or replace function private.uncovered_review_groups(p_review_id uuid) returns text[] language plpgsql stable security definer set search_path = '' as $$ declare v_review public.anatomical_sheet_reviews%rowtype; v_base_verdict jsonb; v_result text[] := '{}'; g record; v_base_digest text; begin select * into v_review from public.anatomical_sheet_reviews where id = p_review_id; -- The base round's verdict, if the version derives from one. select r.verdict into v_base_verdict from public.anatomical_sheet_versions v join public.anatomical_sheet_reviews r on r.id = v.published_review_id where v.id = (select source_version_id from public.anatomical_sheet_versions where id = v_review.version_id); for g in select e ->> 'key' as key, e ->> 'digest' as digest from jsonb_array_elements(coalesce(v_review.verdict -> 'groups', '[]'::jsonb)) e loop v_base_digest := private.verdict_group_digest(v_base_verdict, g.key); -- A group equal to its base (same digest) is already covered by the base. if v_base_digest is not null and v_base_digest = g.digest then continue; end if; -- Covered by an acknowledgment of this or an earlier round, same digest, -- by a reviewer outside the round's authors whose grant is active now. if not exists ( select 1 from public.anatomical_sheet_review_acknowledgments a join public.anatomical_sheet_reviews ar on ar.id = a.review_id where ar.version_id = v_review.version_id and a.group_key = g.key and a.group_digest = g.digest and not (v_review.authors @> array[a.reviewer]) and private.grant_active(a.reviewer, 'sheet_reviewer') ) then v_result := v_result || g.key; end if; end loop; return v_result; end; $$; -- Approve or request changes on an `open` round (contract §6.7). create or replace function public.decide_sheet_review( review_id uuid, approve boolean, note text ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_reviewer'); v_review public.anatomical_sheet_reviews%rowtype; v_version public.anatomical_sheet_versions%rowtype; v_sheet public.anatomical_sheets%rowtype; v_uncovered text[]; begin if char_length(note) not between 1 and 4000 then raise exception 'invalid_input' using errcode = 'P0001'; end if; -- Lock order sheet, then version, then round (contract §6.1), as publish -- does. The sheet is share-locked: an archive (which updates the row) waits -- for the decision or is seen by it, so no approval lands on a sheet archived -- in the meantime (§6.7, M1). select v.sheet_id, v.id into v_sheet.id, v_version.id from public.anatomical_sheet_reviews r join public.anatomical_sheet_versions v on v.id = r.version_id where r.id = decide_sheet_review.review_id; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; select s.* into v_sheet from public.anatomical_sheets s where s.id = v_sheet.id for share; select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_version.id for update; select r.* into v_review from public.anatomical_sheet_reviews r where r.id = decide_sheet_review.review_id for update; if v_review.status <> 'open' then raise exception 'round.not_open' using errcode = '55000'; end if; if v_review.authors @> array[v_actor] then raise exception 'review.separation' using errcode = '42501'; end if; perform private.consume_catalog_write_budget(v_actor); if approve then -- Sheet active, official, other than the historical sheet (§6.7). if v_sheet.status <> 'active' then raise exception 'sheet.inactive' using errcode = '55000'; end if; if v_sheet.id = private.historical_sheet_id() then raise exception 'sheet.historical_read_only' using errcode = '42501'; end if; -- Publishable content: verdict present on the current revision, no -- to_confirm / inherited element, groups covered. if v_review.verdict is null then raise exception 'verdict.missing' using errcode = 'P0001'; end if; if v_review.revision <> v_version.revision then raise exception 'verdict.stale' using errcode = 'P0001'; end if; if private.sheet_has_to_confirm(v_version.content) then raise exception 'publish.to_confirm.open' using errcode = 'P0001'; end if; if not private.sheet_all_reviewed(v_version.content) then raise exception 'publish.inherited.present' using errcode = 'P0001'; end if; if not private.sheet_disclaimer_ok(v_version.content) then raise exception 'publish.disclaimer.missing' using errcode = 'P0001'; end if; v_uncovered := private.uncovered_review_groups(v_review.id); if coalesce(array_length(v_uncovered, 1), 0) > 0 then raise exception 'review.groups.uncovered' using errcode = 'P0001'; end if; update public.anatomical_sheet_reviews set status = 'approved', decided_by = v_actor, decided_at = now(), decision_note = note where id = v_review.id; perform private.log_event( v_actor, 'anatomical_sheet_review.approved', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_version.sheet_id, 'round', v_review.round) ); else update public.anatomical_sheet_reviews set status = 'changes_requested', decided_by = v_actor, decided_at = now(), decision_note = note where id = v_review.id; perform private.log_event( v_actor, 'anatomical_sheet_review.changes_requested', 'anatomical_sheet_review', v_review.id, null, null, jsonb_build_object('sheet_id', v_version.sheet_id, 'round', v_review.round) ); end if; return v_review.id; end; $$; -- =========================================================================== -- 6. Publication (atomic, contract §6.8) -- =========================================================================== create or replace function public.publish_sheet_version(review_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_review public.anatomical_sheet_reviews%rowtype; v_version public.anatomical_sheet_versions%rowtype; v_sheet public.anatomical_sheets%rowtype; v_actor uuid; v_fingerprint text; v_name text; v_description text; begin perform private.require_catalog_actor(); -- Lock order sheet, then version, then round (contract §6.1). select v.sheet_id, v.id into v_sheet.id, v_version.id from public.anatomical_sheet_versions v join public.anatomical_sheet_reviews r on r.version_id = v.id where r.id = publish_sheet_version.review_id; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; select s.* into v_sheet from public.anatomical_sheets s where s.id = v_sheet.id for update; v_actor := private.require_sheet_publisher(v_sheet.id); select v.* into v_version from public.anatomical_sheet_versions v where v.id = v_version.id for update; select r.* into v_review from public.anatomical_sheet_reviews r where r.id = publish_sheet_version.review_id for update; if v_sheet.status <> 'active' then raise exception 'sheet.inactive' using errcode = '55000'; end if; if v_sheet.id = private.historical_sheet_id() then raise exception 'sheet.historical_read_only' using errcode = '42501'; end if; if v_version.status <> 'draft' then raise exception 'draft.not_a_draft' using errcode = '55000'; end if; if v_review.status <> 'approved' or v_review.revision <> v_version.revision then raise exception 'publish.review.missing' using errcode = '55000'; end if; if v_review.verdict is null then raise exception 'verdict.missing' using errcode = 'P0001'; end if; -- The approver is outside the round's authors and its reviewer grant is -- still active at publication (§5.2, §6.7): a revoked reviewer's approval -- does not carry a publication. if v_review.decided_by is null or v_review.authors @> array[v_review.decided_by] or not private.grant_active(v_review.decided_by, 'sheet_reviewer') then raise exception 'publish.approval.invalid' using errcode = 'P0001'; end if; -- Species active and not `other` (§6.7). if not exists (select 1 from public.species s where s.id = v_sheet.species_id and s.active) then raise exception 'publish.species.inactive' using errcode = 'P0001'; end if; if v_sheet.species_id = 'other' then raise exception 'publish.species.other' using errcode = 'P0001'; end if; -- Status check kept in SQL (§12.2): no to_confirm, no inherited (or omitted). if private.sheet_has_to_confirm(v_version.content) then raise exception 'publish.to_confirm.open' using errcode = 'P0001'; end if; if not private.sheet_all_reviewed(v_version.content) then raise exception 'publish.inherited.present' using errcode = 'P0001'; end if; if not private.sheet_disclaimer_ok(v_version.content) then raise exception 'publish.disclaimer.missing' using errcode = 'P0001'; end if; -- Groups still covered at publication. if coalesce(array_length(private.uncovered_review_groups(v_review.id), 1), 0) > 0 then raise exception 'review.groups.uncovered' using errcode = 'P0001'; end if; -- Every drawing id registered for the sheet (§12.2), each referenced -- drawing confirmed, size and sha256 equal to the verdict's. if cardinality(private.sheet_document_unknown_assets(v_version.sheet_id, v_version.content)) > 0 then raise exception 'view.asset.unknown' using errcode = 'P0001'; end if; if exists ( select 1 from unnest(private.sheet_document_asset_ids(v_version.content)) as ref where not exists ( select 1 from public.anatomical_sheet_assets a where a.sheet_id = v_version.sheet_id and a.id::text = ref and a.uploaded_at is not null ) ) then raise exception 'publish.drawing.missing' using errcode = 'P0001'; end if; if exists ( select 1 from jsonb_array_elements(coalesce(v_review.verdict -> 'drawings', '[]'::jsonb)) d join public.anatomical_sheet_assets a on a.id = (d ->> 'asset_id')::uuid where a.sheet_id = v_version.sheet_id and a.sha256 <> (d ->> 'sha256') ) then raise exception 'publish.drawing.changed' using errcode = 'P0001'; end if; v_fingerprint := v_review.verdict ->> 'fingerprint'; if v_fingerprint is null or v_fingerprint !~ '^[0-9a-f]{64}$' then raise exception 'verdict.fingerprint' using errcode = 'P0001'; end if; v_name := left(coalesce(nullif(btrim(v_version.content -> 'name' ->> 'fr'), ''), v_sheet.name), 120); v_description := left(coalesce(v_version.content -> 'description' ->> 'fr', ''), 2000); perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_versions set status = 'published', published_at = now(), published_by = v_actor, published_review_id = v_review.id, document_fingerprint = v_fingerprint where id = v_version.id; update public.anatomical_sheets set current_version_id = v_version.id, name = v_name, description = v_description where id = v_sheet.id; perform private.log_event( v_actor, 'anatomical_sheet_version.published', 'anatomical_sheet_version', v_version.id, null, null, jsonb_build_object('sheet_id', v_sheet.id, 'version_number', v_version.version_number, 'revision', v_version.revision, 'review_id', v_review.id, 'fingerprint', v_fingerprint) ); return v_version.id; end; $$; -- =========================================================================== -- 7. Deprecation, archive, restore, delete (publisher / editor + aal2) -- =========================================================================== create or replace function public.deprecate_sheet_version(version_id uuid, reason text default null) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_version public.anatomical_sheet_versions%rowtype; v_next uuid; begin if char_length(reason) > 500 then raise exception 'invalid_input' using errcode = 'P0001'; end if; select v.sheet_id into v_version.sheet_id from public.anatomical_sheet_versions v where v.id = deprecate_sheet_version.version_id; if v_version.sheet_id is null then raise exception 'not_found' using errcode = '42501'; end if; perform private.require_sheet_publisher(v_version.sheet_id); -- Lock order sheet, then version (§6.1). Two deprecations of the same sheet -- are serialised on the sheet row, so each picks the next current version -- from the other's committed state and never names a deprecated one. perform 1 from public.anatomical_sheets s where s.id = v_version.sheet_id for update; select v.* into v_version from public.anatomical_sheet_versions v where v.id = deprecate_sheet_version.version_id for update; if v_version.status <> 'published' then raise exception 'version.not_published' using errcode = '55000'; end if; perform private.consume_catalog_write_budget(v_actor); update public.anatomical_sheet_versions set status = 'deprecated', deprecated_at = now(), deprecated_by = v_actor where id = v_version.id; select id into v_next from public.anatomical_sheet_versions where sheet_id = v_version.sheet_id and status = 'published' order by version_number desc limit 1; update public.anatomical_sheets set current_version_id = v_next where id = v_version.sheet_id and current_version_id = v_version.id; perform private.log_event( v_actor, 'anatomical_sheet_version.deprecated', 'anatomical_sheet_version', v_version.id, null, null, jsonb_build_object('sheet_id', v_version.sheet_id, 'reason', reason) ); return v_version.id; end; $$; create or replace function private.set_sheet_status( p_actor uuid, p_sheet uuid, p_from public.sheet_status, p_to public.sheet_status, p_action text ) returns uuid language plpgsql security definer set search_path = '' as $$ declare v_status public.sheet_status; begin if p_sheet = private.historical_sheet_id() then raise exception 'sheet.historical_read_only' using errcode = '42501'; end if; select status into v_status from public.anatomical_sheets where id = p_sheet for update; if v_status is null then raise exception 'not_found' using errcode = '42501'; end if; if v_status <> p_from then raise exception 'sheet.state' using errcode = '55000'; end if; perform private.consume_catalog_write_budget(p_actor); update public.anatomical_sheets set status = p_to, archived_at = case when p_to = 'archived' then now() when p_to = 'active' then null else archived_at end, deleted_at = case when p_to = 'deleted' then now() else deleted_at end where id = p_sheet; perform private.log_event(p_actor, p_action, 'anatomical_sheet', p_sheet); return p_sheet; end; $$; create or replace function public.archive_anatomical_sheet(sheet_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ declare v_actor uuid := private.require_sheet_publisher(sheet_id); begin return private.set_sheet_status(v_actor, sheet_id, 'active', 'archived', 'anatomical_sheet.archived'); end; $$; -- Restoring a working copy of the historical sheet keeps the single active -- slot (§14.3): refused while another copy is active. The historical sheet -- row is locked as in create_sheet_working_copy, so the two serialise. create or replace function public.restore_anatomical_sheet(sheet_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_sheet_publisher(sheet_id); begin if private.is_historical_working_copy(restore_anatomical_sheet.sheet_id) then perform 1 from public.anatomical_sheets s where s.id = private.historical_sheet_id() for no key update; if private.historical_working_copy_active(restore_anatomical_sheet.sheet_id) then raise exception 'working_copy.exists' using errcode = 'P0001'; end if; end if; return private.set_sheet_status(v_actor, restore_anatomical_sheet.sheet_id, 'archived', 'active', 'anatomical_sheet.restored'); end; $$; -- Delete a draft-only official sheet (never one that ever had a published -- version, §6.9). Editor capability. create or replace function public.delete_anatomical_sheet(sheet_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_sheet_author(sheet_id); begin perform 1 from public.anatomical_sheets s where s.id = delete_anatomical_sheet.sheet_id for update; if exists ( select 1 from public.anatomical_sheet_versions v where v.sheet_id = delete_anatomical_sheet.sheet_id and v.status in ('published', 'deprecated') ) then raise exception 'sheet.published_history' using errcode = '55000'; end if; return private.set_sheet_status(v_actor, delete_anatomical_sheet.sheet_id, (select status from public.anatomical_sheets where id = delete_anatomical_sheet.sheet_id), 'deleted', 'anatomical_sheet.deleted'); end; $$; -- Delete a draft version (the guard refuses published/deprecated and the -- historical sheet). Editor capability. create or replace function public.delete_sheet_version(version_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); v_version public.anatomical_sheet_versions%rowtype; begin select v.* into v_version from public.anatomical_sheet_versions v where v.id = delete_sheet_version.version_id for update; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; perform private.require_sheet_author(v_version.sheet_id); if exists (select 1 from public.anatomical_sheet_reviews r where r.version_id = v_version.id) then raise exception 'version.has_rounds' using errcode = '55000'; end if; perform private.consume_catalog_write_budget(v_actor); delete from public.anatomical_sheet_versions where id = v_version.id; perform private.log_event( v_actor, 'anatomical_sheet_version.deleted', 'anatomical_sheet_version', v_version.id, null, null, jsonb_build_object('sheet_id', v_version.sheet_id, 'version_number', v_version.version_number) ); return v_version.id; end; $$; -- =========================================================================== -- 8. Equine working copy (contract §14.3) -- =========================================================================== -- A sheet created as a working copy of a version of the historical sheet. create or replace function private.is_historical_working_copy(p_sheet_id uuid) returns boolean language sql stable security definer set search_path = '' as $$ select exists ( select 1 from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.working_copy_source_version_id where s.id = p_sheet_id and v.sheet_id = private.historical_sheet_id() ); $$; -- An active working copy of the historical sheet other than p_except. create or replace function private.historical_working_copy_active(p_except uuid) returns boolean language sql stable security definer set search_path = '' as $$ select exists ( select 1 from public.anatomical_sheets s where s.status = 'active' and s.id is distinct from p_except and private.is_historical_working_copy(s.id) ); $$; create or replace function public.create_sheet_working_copy(source_version_id uuid, slug text) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_editor'); v_source public.anatomical_sheet_versions%rowtype; v_sheet uuid; v_draft uuid; v_map jsonb := '{}'::jsonb; v_new uuid; r record; begin select v.* into v_source from public.anatomical_sheet_versions v where v.id = create_sheet_working_copy.source_version_id; -- Source restricted to the historical sheet, and no other (§14.3). if v_source.id is null or v_source.sheet_id <> private.historical_sheet_id() then raise exception 'working_copy.source_invalid' using errcode = 'P0001'; end if; -- At most one active working copy of the historical sheet. Two concurrent -- creations (or a creation and a restore) serialise on the historical sheet -- row; the lock writes nothing, so its protection trigger never fires. perform 1 from public.anatomical_sheets s where s.id = private.historical_sheet_id() for no key update; if private.historical_working_copy_active(null) then raise exception 'working_copy.exists' using errcode = 'P0001'; end if; -- Every referenced drawing uploaded, with an object of the recorded size. if exists ( select 1 from unnest(private.sheet_document_asset_ids(v_source.content)) as ref join public.anatomical_sheet_assets a on a.id::text = ref and a.sheet_id = v_source.sheet_id where a.uploaded_at is null or not exists ( select 1 from storage.objects o where o.bucket_id = 'anatomical-sheet-assets' and o.name = a.sha256 || '.svg' and coalesce((o.metadata ->> 'size')::bigint, a.byte_size) = a.byte_size ) ) then raise exception 'working_copy.assets_missing' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); select private.insert_official_sheet(s.species_id, left(coalesce(nullif(btrim(v_source.content -> 'name' ->> 'fr'), ''), s.name), 120), create_sheet_working_copy.slug, s.description, v_source.id) into v_sheet from public.anatomical_sheets s where s.id = v_source.sheet_id; -- Register the source drawings for the new sheet (same bytes, shared object). for r in select a.id, a.sha256, a.byte_size, a.content_type, a.file_name from public.anatomical_sheet_assets a where a.sheet_id = v_source.sheet_id and a.id::text = any (private.sheet_document_asset_ids(v_source.content)) loop insert into public.anatomical_sheet_assets (sheet_id, sha256, byte_size, content_type, file_name, created_by, uploaded_at) values (v_sheet, r.sha256, r.byte_size, r.content_type, r.file_name, v_actor, now()) returning id into v_new; v_map := v_map || jsonb_build_object(r.id::text, v_new::text); end loop; -- Size checked as in §6.2: the remapped document must fit the 2 MiB cap. perform private.check_document_structure(private.remap_document_assets(v_source.content, v_map)); v_draft := private.insert_sheet_draft( v_actor, v_sheet, private.remap_document_assets(v_source.content, v_map), 'Copie de travail de la fiche historique (version ' || v_source.version_number || ', révision ' || v_source.revision || ')' ); perform private.log_event( v_actor, 'anatomical_sheet.working_copy_created', 'anatomical_sheet', v_sheet, null, null, jsonb_build_object('source_sheet_id', v_source.sheet_id, 'source_version_id', v_source.id, 'source_revision', v_source.revision) ); return v_sheet; end; $$; -- =========================================================================== -- 9. Species RPCs (contract §7.2) -- =========================================================================== create or replace function public.create_species(id text, name_fr text, name_en text, sort_order integer default 100) returns text language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_editor'); begin if create_species.id is null or create_species.id !~ '^[a-z0-9][a-z0-9_-]{0,63}$' or create_species.id = 'other' or char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then raise exception 'invalid_input' using errcode = 'P0001'; end if; if exists (select 1 from public.species s where s.id = create_species.id) then raise exception 'species.exists' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); insert into public.species (id, name_fr, name_en, sort_order, active) values (create_species.id, name_fr, name_en, coalesce(sort_order, 100), false); perform private.log_event(v_actor, 'species.created', 'species', null, null, null, jsonb_build_object('id', create_species.id)); return create_species.id; end; $$; create or replace function public.update_inactive_species(id text, name_fr text, name_en text, sort_order integer) returns text language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_capability('sheet_editor'); begin if char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then raise exception 'invalid_input' using errcode = 'P0001'; end if; perform 1 from public.species s where s.id = update_inactive_species.id and not s.active for update; if not found then raise exception 'species.not_inactive' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); update public.species s set name_fr = update_inactive_species.name_fr, name_en = update_inactive_species.name_en, sort_order = coalesce(update_inactive_species.sort_order, s.sort_order) where s.id = update_inactive_species.id; perform private.log_event(v_actor, 'species.updated', 'species', null, null, null, jsonb_build_object('id', update_inactive_species.id)); return update_inactive_species.id; end; $$; create or replace function public.activate_species(id text) returns text language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); begin if not private.is_platform_owner(v_actor) then raise exception 'rights.owner' using errcode = '42501'; end if; perform 1 from public.species s where s.id = activate_species.id for update; if not found then raise exception 'not_found' using errcode = '42501'; end if; perform private.consume_catalog_write_budget(v_actor); update public.species s set active = true where s.id = activate_species.id and not s.active; perform private.log_event(v_actor, 'species.activated', 'species', null, null, null, jsonb_build_object('id', activate_species.id)); return activate_species.id; end; $$; create or replace function public.rename_species(id text, name_fr text, name_en text) returns text language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_catalog_actor(); begin if not private.is_platform_owner(v_actor) then raise exception 'rights.owner' using errcode = '42501'; end if; if char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 then raise exception 'invalid_input' using errcode = 'P0001'; end if; perform 1 from public.species s where s.id = rename_species.id and s.active for update; if not found then raise exception 'species.not_active' using errcode = 'P0001'; end if; perform private.consume_catalog_write_budget(v_actor); update public.species s set name_fr = rename_species.name_fr, name_en = rename_species.name_en where s.id = rename_species.id; perform private.log_event(v_actor, 'species.renamed', 'species', null, null, null, jsonb_build_object('id', rename_species.id)); return rename_species.id; end; $$; -- Catalogue species for the admin space (E, V, P, O at aal2): active and inactive. create or replace function public.list_catalog_species() returns jsonb language plpgsql stable security definer set search_path = '' as $$ begin perform private.require_catalog_actor(); if not (private.caller_is_catalog_staff() or private.is_platform_owner((select auth.uid()))) then raise exception 'rights.capability' using errcode = '42501'; end if; return coalesce(( select jsonb_agg(jsonb_build_object('id', s.id, 'name_fr', s.name_fr, 'name_en', s.name_en, 'sort_order', s.sort_order, 'active', s.active) order by s.sort_order, s.id) from public.species s ), '[]'::jsonb); end; $$; -- =========================================================================== -- 10. Read RPCs (contract §10) -- =========================================================================== -- One version by id, with its drawings, under the reader predicate (published -- or deprecated) or a capability at aal2 (any status). create or replace function public.get_sheet_version(version_id uuid) returns jsonb language plpgsql stable security definer set search_path = '' as $$ #variable_conflict use_column declare v_uid uuid := auth.uid(); v_version public.anatomical_sheet_versions%rowtype; v_sheet public.anatomical_sheets%rowtype; v_allowed boolean; begin if v_uid is null then raise exception 'not_found' using errcode = '42501'; end if; select v.* into v_version from public.anatomical_sheet_versions v where v.id = get_sheet_version.version_id; if v_version.id is null then raise exception 'not_found' using errcode = '42501'; end if; select s.* into v_sheet from public.anatomical_sheets s where s.id = v_version.sheet_id; v_allowed := private.caller_can_see_official_sheet(v_sheet.id) or (v_version.status in ('published', 'deprecated') and private.can_read_catalog_sheet(v_uid, v_sheet.id)); if not v_allowed then raise exception 'not_found' using errcode = '42501'; end if; return jsonb_build_object( 'sheet_id', v_sheet.id, 'version_id', v_version.id, 'version_number', v_version.version_number, 'status', v_version.status, 'species_id', v_sheet.species_id, 'document', v_version.content, 'revision', v_version.revision, 'fingerprint', case when v_version.status = 'published' then v_version.document_fingerprint end, 'drawings', coalesce(( select jsonb_agg(jsonb_build_object('asset_id', a.id, 'sha256', a.sha256, 'byte_size', a.byte_size) order by a.id) from public.anatomical_sheet_assets a where a.sheet_id = v_sheet.id and a.uploaded_at is not null and a.id::text = any (private.sheet_document_asset_ids(v_version.content)) ), '[]'::jsonb) ); end; $$; -- The published catalogue grouped by species (readers and capability holders). create or replace function public.list_official_catalog() returns jsonb language plpgsql stable security definer set search_path = '' as $$ declare v_uid uuid := auth.uid(); begin if v_uid is null or not private.can_read_official_catalog(v_uid) then raise exception 'rights.catalog' using errcode = '42501'; end if; return coalesce(( select jsonb_agg(jsonb_build_object( 'sheet_id', s.id, 'species_id', s.species_id, 'slug', s.slug, 'name', cur.content -> 'name', 'description', cur.content -> 'description', 'version_number', cur.version_number, 'version_id', cur.id ) order by s.species_id, s.slug) from public.anatomical_sheets s join public.anatomical_sheet_versions cur on cur.id = s.current_version_id where s.is_official and s.status = 'active' and cur.status = 'published' ), '[]'::jsonb); end; $$; -- =========================================================================== -- 11. Uploads (contract §9.3): bucket limit, register, confirm with the -- Storage check (F7), the INSERT policy, the operator read RPC -- =========================================================================== update storage.buckets set file_size_limit = 2097152 where id = 'anatomical-sheet-assets'; alter table public.anatomical_sheet_assets add constraint anatomical_sheet_assets_byte_size_2mib check (byte_size <= 2097152) not valid; -- Register a drawing for a sheet (editor, aal2), refused on the historical -- sheet; returns the existing row of the same hash or inserts a pending one. create or replace function public.register_sheet_asset( sheet_id uuid, sha256 text, byte_size integer, file_name text ) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid := private.require_sheet_author(sheet_id); v_id uuid; begin if sha256 !~ '^[0-9a-f]{64}$' or byte_size not between 1 and 2097152 or char_length(file_name) not between 1 and 255 then raise exception 'invalid_input' using errcode = 'P0001'; end if; select id into v_id from public.anatomical_sheet_assets a where a.sheet_id = register_sheet_asset.sheet_id and a.sha256 = register_sheet_asset.sha256; if v_id is not null then return v_id; end if; insert into public.anatomical_sheet_assets (sheet_id, sha256, byte_size, file_name, created_by) values (sheet_id, sha256, byte_size, file_name, v_actor) returning id into v_id; -- The budget row last, after the sheet row the insert locks through its key. perform private.consume_catalog_write_budget(v_actor); perform private.log_event( v_actor, 'anatomical_sheet_asset.registered', 'anatomical_sheet_asset', v_id, null, null, jsonb_build_object('sheet_id', sheet_id, 'sha256', sha256, 'byte_size', byte_size) ); return v_id; end; $$; -- Confirm an upload: the editor of the sheet at aal2, or the service role -- (operator tool). Checks the object exists and, when the backend records it, -- that its size equals the row's (F7). create or replace function public.confirm_sheet_asset_upload(asset_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ #variable_conflict use_column declare v_actor uuid; v_row public.anatomical_sheet_assets%rowtype; v_object storage.objects%rowtype; begin if auth.uid() is not null then v_actor := private.require_catalog_actor(); elsif auth.role() is distinct from 'service_role' then raise exception 'rights.capability' using errcode = '42501'; end if; select a.* into v_row from public.anatomical_sheet_assets a where a.id = confirm_sheet_asset_upload.asset_id for update; if v_row.id is null then raise exception 'not_found' using errcode = '42501'; end if; if v_actor is not null then perform private.require_sheet_author(v_row.sheet_id); end if; select o.* into v_object from storage.objects o where o.bucket_id = 'anatomical-sheet-assets' and o.name = v_row.sha256 || '.svg'; if v_object.name is null then raise exception 'upload_missing' using errcode = 'P0001'; end if; if coalesce((v_object.metadata ->> 'size')::bigint, v_row.byte_size) <> v_row.byte_size then raise exception 'size_mismatch' using errcode = 'P0001'; end if; if v_row.uploaded_at is null then -- The operator tool (service role, no actor) has no budget row. if v_actor is not null then perform private.consume_catalog_write_budget(v_actor); end if; update public.anatomical_sheet_assets set uploaded_at = now() where id = v_row.id; perform private.log_event(auth.uid(), 'anatomical_sheet_asset.uploaded', 'anatomical_sheet_asset', v_row.id); end if; return v_row.id; end; $$; -- Narrow read for the operator tool (service role): the state of one asset, -- replacing its former direct table read (F12). create or replace function public.get_sheet_asset_state(asset_id uuid) returns jsonb language plpgsql stable security definer set search_path = '' as $$ #variable_conflict use_column declare v_row public.anatomical_sheet_assets%rowtype; begin if auth.role() is distinct from 'service_role' then raise exception 'rights.capability' using errcode = '42501'; end if; select a.* into v_row from public.anatomical_sheet_assets a where a.id = get_sheet_asset_state.asset_id; -- Null for an unknown asset: the operator tool reads it as "no row yet". if v_row.id is null then return null; end if; return jsonb_build_object('asset_id', v_row.id, 'sheet_id', v_row.sheet_id, 'sha256', v_row.sha256, 'byte_size', v_row.byte_size, 'uploaded_at', v_row.uploaded_at); end; $$; -- The editor who registered a pending row uploads its key (contract §9.3 -- step 2: "exactly that key for the caller of a pending row"). Routed through -- a single granted predicate, as the avatar bucket is, so that evaluating this -- policy against another bucket's insert needs no EXECUTE on the internal -- helpers. create or replace function private.can_upload_sheet_asset_object(p_user_id uuid, p_object_name text) returns boolean language sql stable security definer set search_path = '' as $$ select p_user_id = (select auth.uid()) and private.caller_has('sheet_editor') and exists ( select 1 from public.anatomical_sheet_assets a where a.sha256 = left(p_object_name, 64) and p_object_name = a.sha256 || '.svg' and a.uploaded_at is null and a.created_by = p_user_id and private.caller_can_see_official_sheet(a.sheet_id) ); $$; comment on function private.can_upload_sheet_asset_object(uuid, text) is 'Storage INSERT predicate for bucket anatomical-sheet-assets: the caller holds sheet_editor at aal2 and registered a pending row of a non-deleted official sheet whose key is exactly .svg (contract §9.3).'; -- Delete an unreferenced asset row (editor, aal2), replacing the base -- version: closed codes, the historical sheet refused, the write budget. The -- object stays in Storage (objects are never deleted, §9.5). create or replace function public.delete_sheet_asset(asset_id uuid) returns uuid language plpgsql volatile security definer set search_path = '' as $$ declare v_actor uuid := private.require_catalog_actor(); v_row public.anatomical_sheet_assets%rowtype; begin select a.* into v_row from public.anatomical_sheet_assets a where a.id = delete_sheet_asset.asset_id for update; if v_row.id is null then raise exception 'not_found' using errcode = '42501'; end if; perform private.require_sheet_author(v_row.sheet_id); if exists ( select 1 from public.anatomical_sheet_versions v where v.sheet_id = v_row.sheet_id and v_row.id::text = any (private.sheet_document_asset_ids(v.content)) ) then raise exception 'asset.referenced' using errcode = '55000'; end if; perform private.consume_catalog_write_budget(v_actor); delete from public.anatomical_sheet_assets where id = v_row.id; perform private.log_event( v_actor, 'anatomical_sheet_asset.deleted', 'anatomical_sheet_asset', v_row.id, null, null, jsonb_build_object('sheet_id', v_row.sheet_id) ); return v_row.id; end; $$; revoke all on function private.can_upload_sheet_asset_object(uuid, text) from public, anon, authenticated, service_role; grant execute on function private.can_upload_sheet_asset_object(uuid, text) to authenticated; create policy anatomical_sheet_assets_object_insert on storage.objects for insert to authenticated with check ( bucket_id = 'anatomical-sheet-assets' and private.can_upload_sheet_asset_object((select auth.uid()), name) ); -- =========================================================================== -- 12. Triggers wired after every function exists -- =========================================================================== drop trigger anatomical_sheet_versions_guard_update on public.anatomical_sheet_versions; create trigger anatomical_sheet_versions_guard_update before update on public.anatomical_sheet_versions for each row execute function private.guard_sheet_version_update(); -- =========================================================================== -- 13. Privileges + RLS -- =========================================================================== revoke all on public.anatomical_sheet_reviews from public, anon, authenticated, service_role; revoke all on public.anatomical_sheet_review_comments from public, anon, authenticated, service_role; revoke all on public.anatomical_sheet_review_acknowledgments from public, anon, authenticated, service_role; -- The lease columns (attempts, lease_token, locked_at) are the worker's, read -- only by the M6 service-role RPCs; the admin screens never see them, as the -- avatar lease pattern hides its own (20261013100000_files_foundation.sql). grant select (id, version_id, round, revision, authors, submitted_by, submitted_at, submission_note, status, verdict, verified_at, verified_with, failure_outcome, failure_code, decided_by, decided_at, decision_note, withdrawn_by, withdrawn_at, withdrawal_note, created_at) on public.anatomical_sheet_reviews to authenticated; grant select on public.anatomical_sheet_review_comments to authenticated; grant select on public.anatomical_sheet_review_acknowledgments to authenticated; -- The editor needs the draft revision for the save-conflict check (§6.2); the -- other V1-2 columns (authors, provenance, review link, fingerprint) stay out -- of the direct grant and reach staff through the read RPCs. grant select (revision) on public.anatomical_sheet_versions to authenticated; alter table public.anatomical_sheet_reviews enable row level security; alter table public.anatomical_sheet_review_comments enable row level security; alter table public.anatomical_sheet_review_acknowledgments enable row level security; create policy anatomical_sheet_reviews_select on public.anatomical_sheet_reviews for select to authenticated using (private.caller_can_see_official_sheet( (select sheet_id from public.anatomical_sheet_versions v where v.id = version_id))); create policy anatomical_sheet_review_comments_select on public.anatomical_sheet_review_comments for select to authenticated using (private.caller_can_see_official_sheet( (select v.sheet_id from public.anatomical_sheet_reviews r join public.anatomical_sheet_versions v on v.id = r.version_id where r.id = review_id))); create policy anatomical_sheet_review_acks_select on public.anatomical_sheet_review_acknowledgments for select to authenticated using (private.caller_can_see_official_sheet( (select v.sheet_id from public.anatomical_sheet_reviews r join public.anatomical_sheet_versions v on v.id = r.version_id where r.id = review_id))); -- RPC privileges: authoring and review RPCs to authenticated only; the two -- service-role RPCs (upload confirmation, operator read) to service_role too. do $$ declare v_fn text; v_authn text[] := array[ 'public.create_official_sheet(text, jsonb)', 'public.create_sheet_draft(uuid, uuid, text)', 'public.save_sheet_draft(uuid, integer, jsonb, text)', 'public.submit_sheet_review(uuid, integer, text)', 'public.withdraw_sheet_review(uuid, text)', 'public.comment_sheet_review(uuid, text, text)', 'public.acknowledge_sheet_review_group(uuid, text, text)', 'public.decide_sheet_review(uuid, boolean, text)', 'public.publish_sheet_version(uuid)', 'public.deprecate_sheet_version(uuid, text)', 'public.archive_anatomical_sheet(uuid)', 'public.restore_anatomical_sheet(uuid)', 'public.delete_anatomical_sheet(uuid)', 'public.delete_sheet_version(uuid)', 'public.create_sheet_working_copy(uuid, text)', 'public.create_species(text, text, text, integer)', 'public.update_inactive_species(text, text, text, integer)', 'public.activate_species(text)', 'public.rename_species(text, text, text)', 'public.list_catalog_species()', 'public.get_sheet_version(uuid)', 'public.list_official_catalog()', 'public.register_sheet_asset(uuid, text, integer, text)' ]; begin foreach v_fn in array v_authn loop execute format('revoke all on function %s from public, anon, service_role', v_fn); execute format('grant execute on function %s to authenticated', v_fn); end loop; execute 'revoke all on function public.confirm_sheet_asset_upload(uuid) from public, anon'; execute 'grant execute on function public.confirm_sheet_asset_upload(uuid) to authenticated, service_role'; execute 'revoke all on function public.get_sheet_asset_state(uuid) from public, anon, authenticated'; execute 'grant execute on function public.get_sheet_asset_state(uuid) to service_role'; end; $$; -- Private helpers: EXECUTE for nobody except the predicates the review -- policies evaluate (caller_can_see_official_sheet, granted in M4). revoke all on function private.sheet_all_reviewed(jsonb) from public, anon, authenticated, service_role; revoke all on function private.sheet_has_to_confirm(jsonb) from public, anon, authenticated, service_role; revoke all on function private.sheet_disclaimer_ok(jsonb) from public, anon, authenticated, service_role; revoke all on function private.on_sheet_version_content() from public, anon, authenticated, service_role; revoke all on function private.guard_sheet_version_update() from public, anon, authenticated, service_role; revoke all on function private.require_catalog_actor() from public, anon, authenticated, service_role; revoke all on function private.require_capability(public.catalog_grant_kind) from public, anon, authenticated, service_role; revoke all on function private.check_document_structure(jsonb) from public, anon, authenticated, service_role; revoke all on function private.insert_official_sheet(text, text, text, text, uuid) from public, anon, authenticated, service_role; revoke all on function private.is_historical_working_copy(uuid) from public, anon, authenticated, service_role; revoke all on function private.historical_working_copy_active(uuid) from public, anon, authenticated, service_role; revoke all on function private.require_sheet_author(uuid) from public, anon, authenticated, service_role; revoke all on function private.require_sheet_publisher(uuid) from public, anon, authenticated, service_role; revoke all on function private.verdict_group_digest(jsonb, text) from public, anon, authenticated, service_role; revoke all on function private.uncovered_review_groups(uuid) from public, anon, authenticated, service_role; revoke all on function private.set_sheet_status(uuid, uuid, public.sheet_status, public.sheet_status, text) from public, anon, authenticated, service_role; -- The two obsolete editor predicates of the base migration are gone (M4 -- dropped can_use_sheet; require_sheet_editor / require_version_editor are no -- longer called). Drop them so no stale path survives. drop function if exists private.require_sheet_editor(uuid, uuid); drop function if exists private.require_version_editor(uuid, uuid); -- delete_sheet_asset survives from the base migration (editor, aal2, via -- can_edit_sheet); the service role never needs it (§5.4 limits its surface to -- the worker RPCs, the upload confirmation and the operator read). revoke all on function public.delete_sheet_asset(uuid) from service_role; -- §7.2: the species table is no longer write-only through migrations; editors -- create inactive species and the owner activates them, by audited RPC. comment on table public.species is 'Species of animals and of anatomical sheets. Written only by the audited RPCs create_species (editor, inactive), activate_species / rename_species (owner), update_inactive_species (editor); no direct API write path.';