-- 002-ai-runtime-store.sql
-- MNote ACP/Hermes runtime session store.

CREATE TABLE IF NOT EXISTS ai_runtime_runs (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  workspace_id TEXT,
  document_id TEXT,
  session_id TEXT NOT NULL,
  run_id TEXT NOT NULL UNIQUE,
  title TEXT,
  profile TEXT NOT NULL,
  acp_runtime TEXT NOT NULL,
  trace_id TEXT,
  status TEXT NOT NULL,
  runtime_json TEXT NOT NULL DEFAULT '{}',
  payload_json TEXT NOT NULL DEFAULT '{}',
  deleted_at TEXT,
  created_at TEXT NOT NULL,
  updated_at TEXT NOT NULL,
  revision INTEGER NOT NULL DEFAULT 1
);

CREATE INDEX IF NOT EXISTS idx_ai_runtime_runs_user_session
  ON ai_runtime_runs(user_id, session_id, updated_at);
CREATE INDEX IF NOT EXISTS idx_ai_runtime_runs_workspace
  ON ai_runtime_runs(workspace_id, updated_at);
CREATE INDEX IF NOT EXISTS idx_ai_runtime_runs_document
  ON ai_runtime_runs(document_id, updated_at);

CREATE TABLE IF NOT EXISTS ai_runtime_events (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  workspace_id TEXT,
  document_id TEXT,
  session_id TEXT NOT NULL,
  run_id TEXT NOT NULL,
  profile TEXT NOT NULL,
  acp_runtime TEXT NOT NULL,
  event_type TEXT NOT NULL,
  payload_json TEXT NOT NULL DEFAULT '{}',
  created_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_ai_runtime_events_run
  ON ai_runtime_events(user_id, run_id, created_at);
CREATE INDEX IF NOT EXISTS idx_ai_runtime_events_session
  ON ai_runtime_events(user_id, session_id, created_at);
