-- Apply once before enabling the reconciliation service (also safe to reapply). CREATE TABLE IF NOT EXISTS historical_assignment_audit ( id bigserial PRIMARY KEY, machine_id text NOT NULL, source_table text NOT NULL, record_identity jsonb NOT NULL, previous_order text NOT NULL, new_order text NOT NULL, run_id text NOT NULL, reason text NOT NULL, action text NOT NULL DEFAULT 'updated', retained_run_id text, reconciled_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, CHECK (previous_order <> new_order) ); ALTER TABLE historical_assignment_audit ADD COLUMN IF NOT EXISTS action text NOT NULL DEFAULT 'updated'; ALTER TABLE historical_assignment_audit ADD COLUMN IF NOT EXISTS retained_run_id text; CREATE INDEX IF NOT EXISTS historical_assignment_audit_machine_time_idx ON historical_assignment_audit (machine_id, reconciled_at);