-- Earlier generated revisions created execution_receipts with `skill_name`
-- and without the hashes/task metadata now written by ContractClock. Keep the
-- migration additive so existing receipts survive and fresh databases (whose
-- 001 migration already has these columns) remain idempotent.
ALTER TABLE execution_receipts
    ADD COLUMN IF NOT EXISTS tool_name TEXT,
    ADD COLUMN IF NOT EXISTS task_id TEXT,
    ADD COLUMN IF NOT EXISTS input_hash TEXT,
    ADD COLUMN IF NOT EXISTS result_hash TEXT;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = current_schema()
          AND table_name = 'execution_receipts'
          AND column_name = 'skill_name'
    ) THEN
        EXECUTE 'UPDATE execution_receipts
                 SET tool_name = COALESCE(tool_name, skill_name)';
        EXECUTE 'ALTER TABLE execution_receipts
                 ALTER COLUMN skill_name DROP NOT NULL';
    END IF;
END
$$;

UPDATE execution_receipts
SET tool_name = COALESCE(tool_name, 'legacy'),
    task_id = COALESCE(task_id, ''),
    input_hash = COALESCE(input_hash, 'legacy'),
    result_hash = COALESCE(result_hash, 'legacy');

ALTER TABLE execution_receipts
    ALTER COLUMN tool_name SET NOT NULL,
    ALTER COLUMN task_id SET NOT NULL,
    ALTER COLUMN input_hash SET NOT NULL,
    ALTER COLUMN result_hash SET NOT NULL;
