-- ADR-0017: once an Organization starts configuring roles, every committed -- state must contain exactly one active default. The deferred trigger permits -- an atomic default switch while rejecting zero-default transitions. CREATE FUNCTION cph_enforce_agent_role_default() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE target_organization_id TEXT := COALESCE(NEW."organizationId", OLD."organizationId"); active_default_count INTEGER; BEGIN IF NOT EXISTS (SELECT 1 FROM "Organization" WHERE "id" = target_organization_id) THEN RETURN NULL; END IF; SELECT count(*) INTO active_default_count FROM "OrganizationAgentRole" WHERE "organizationId" = target_organization_id AND "isDefault" = true AND "disabledAt" IS NULL; IF active_default_count <> 1 THEN RAISE EXCEPTION 'Organization % must have exactly one active default Agent role; found %', target_organization_id, active_default_count; END IF; RETURN NULL; END; $$; CREATE CONSTRAINT TRIGGER "OrganizationAgentRole_exactly_one_active_default" AFTER INSERT OR UPDATE OR DELETE ON "OrganizationAgentRole" DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION cph_enforce_agent_role_default();