-- PBI-50: SPRINT_IMPLEMENTATION single-session sprint runner
-- Adds:
--  - PrStrategy.SPRINT_BATCH (third option)
--  - ClaudeJobKind.SPRINT_IMPLEMENTATION (fifth kind)
--  - SprintTaskExecutionStatus enum
--  - ClaudeJob.lease_until (for heartbeat-driven stale detection)
--  - SprintRun.previous_run_id (for branch reuse on resume)
--  - sprint_task_executions table (frozen scope-snapshot per claim)

-- AlterEnum: PrStrategy ADD VALUE (Postgres requires this outside transaction;
-- Prisma migrate handles it)
ALTER TYPE "PrStrategy" ADD VALUE 'SPRINT_BATCH';

-- AlterEnum: ClaudeJobKind ADD VALUE
ALTER TYPE "ClaudeJobKind" ADD VALUE 'SPRINT_IMPLEMENTATION';

-- CreateEnum
CREATE TYPE "SprintTaskExecutionStatus" AS ENUM ('PENDING', 'RUNNING', 'DONE', 'FAILED', 'SKIPPED');

-- AlterTable
ALTER TABLE "claude_jobs" ADD COLUMN     "lease_until" TIMESTAMP(3);

-- AlterTable
ALTER TABLE "sprint_runs" ADD COLUMN     "previous_run_id" TEXT;

-- CreateTable
CREATE TABLE "sprint_task_executions" (
    "id" TEXT NOT NULL,
    "sprint_job_id" TEXT NOT NULL,
    "task_id" TEXT NOT NULL,
    "order" INTEGER NOT NULL,
    "plan_snapshot" TEXT NOT NULL,
    "verify_required_snapshot" "VerifyRequired" NOT NULL,
    "verify_only_snapshot" BOOLEAN NOT NULL DEFAULT false,
    "base_sha" TEXT,
    "head_sha" TEXT,
    "status" "SprintTaskExecutionStatus" NOT NULL DEFAULT 'PENDING',
    "verify_result" "VerifyResult",
    "verify_summary" TEXT,
    "skip_reason" TEXT,
    "started_at" TIMESTAMP(3),
    "finished_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "sprint_task_executions_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "sprint_task_executions_sprint_job_id_order_idx" ON "sprint_task_executions"("sprint_job_id", "order");

-- CreateIndex
CREATE UNIQUE INDEX "sprint_task_executions_sprint_job_id_task_id_key" ON "sprint_task_executions"("sprint_job_id", "task_id");

-- CreateIndex
CREATE INDEX "claude_jobs_status_lease_until_idx" ON "claude_jobs"("status", "lease_until");

-- CreateIndex
CREATE UNIQUE INDEX "sprint_runs_previous_run_id_key" ON "sprint_runs"("previous_run_id");

-- AddForeignKey
ALTER TABLE "sprint_runs" ADD CONSTRAINT "sprint_runs_previous_run_id_fkey" FOREIGN KEY ("previous_run_id") REFERENCES "sprint_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sprint_task_executions" ADD CONSTRAINT "sprint_task_executions_sprint_job_id_fkey" FOREIGN KEY ("sprint_job_id") REFERENCES "claude_jobs"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "sprint_task_executions" ADD CONSTRAINT "sprint_task_executions_task_id_fkey" FOREIGN KEY ("task_id") REFERENCES "tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;
