ALTER TABLE IF EXISTS gateway_runner_policies
  ADD COLUMN IF NOT EXISTS priority_demote_policy jsonb NOT NULL DEFAULT '{}'::jsonb;

UPDATE gateway_runner_policies
SET priority_demote_policy = CASE
      WHEN COALESCE(priority_demote_policy, '{}'::jsonb) = '{}'::jsonb THEN
        '{
          "enabled": true,
          "categories": ["network", "timeout", "stream_error", "rate_limit", "provider_5xx", "provider_overloaded"],
          "codes": ["network", "timeout", "stream_read_error", "rate_limit", "server_error", "overloaded"],
          "statusCodes": [408, 429, 500, 502, 503, 504],
          "keywords": ["timeout", "network", "rate_limit", "overloaded", "temporarily_unavailable", "server_error", "429", "5xx"]
        }'::jsonb
      ELSE priority_demote_policy
    END,
    metadata = metadata || jsonb_build_object('priorityDemotePolicyRepair', '0034_runner_priority_demote_policy_repair'),
    updated_at = now()
WHERE policy_key = 'default-runner-v1';
