CREATE TABLE IF NOT EXISTS runs (
  run_id TEXT PRIMARY KEY,
  goal TEXT NOT NULL,
  summary TEXT NOT NULL DEFAULT '',
  status TEXT NOT NULL DEFAULT 'active',
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS tasks (
  run_id TEXT NOT NULL,
  task_id TEXT NOT NULL,
  title TEXT NOT NULL,
  summary TEXT NOT NULL DEFAULT '',
  status TEXT NOT NULL,
  default_to TEXT,
  priority TEXT NOT NULL DEFAULT 'normal',
  acceptance_json TEXT NOT NULL DEFAULT '[]',
  latest_attempt_no INTEGER,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  PRIMARY KEY (run_id, task_id),
  FOREIGN KEY(run_id) REFERENCES runs(run_id)
);

CREATE TABLE IF NOT EXISTS task_dependencies (
  run_id TEXT NOT NULL,
  task_id TEXT NOT NULL,
  depends_on_task_id TEXT NOT NULL,
  PRIMARY KEY (run_id, task_id, depends_on_task_id)
);

CREATE TABLE IF NOT EXISTS task_attempts (
  run_id TEXT NOT NULL,
  task_id TEXT NOT NULL,
  attempt_no INTEGER NOT NULL,
  assigned_to TEXT NOT NULL,
  thread_id TEXT NOT NULL,
  base_ref TEXT,
  base_commit TEXT,
  branch_name TEXT,
  worktree_path TEXT,
  workspace_status TEXT,
  result_commit TEXT,
  status TEXT NOT NULL,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  PRIMARY KEY (run_id, task_id, attempt_no)
);

CREATE INDEX IF NOT EXISTS idx_tasks_run_status
  ON tasks(run_id, status, priority, updated_at);
