ALTER TABLE attachments ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','ready','failed')); ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key text; ALTER TABLE attachments ADD COLUMN IF NOT EXISTS pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version > 0); ALTER TABLE attachments ADD COLUMN IF NOT EXISTS variants jsonb NOT NULL DEFAULT '[]'; ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code text; CREATE TABLE IF NOT EXISTS jobs ( id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id), pipeline_version integer NOT NULL CHECK(pipeline_version > 0), attempts integer NOT NULL DEFAULT 0, status text NOT NULL DEFAULT 'queued' CHECK(status IN ('queued','processing','ready','failed','superseded')), next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(), lease_until timestamptz, error_code text, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), UNIQUE(attachment_id,pipeline_version) ); CREATE INDEX IF NOT EXISTS jobs_due ON jobs(status,next_attempt_at); CREATE TABLE IF NOT EXISTS outbox ( job_id uuid PRIMARY KEY REFERENCES jobs(id), published_at timestamptz, publish_count integer NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS job_audit ( id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES jobs(id), event text NOT NULL, detail text NOT NULL DEFAULT '', created_at timestamptz NOT NULL DEFAULT clock_timestamp() ); CREATE TABLE IF NOT EXISTS fault_rules ( job_id uuid PRIMARY KEY REFERENCES jobs(id), point text NOT NULL, remaining integer NOT NULL DEFAULT 1 );