-- 015_agent_sessions.up.sql
-- Nomos agent sessions: persist conversations across restarts.
-- agent_messages stores the full message history (JSONB).
-- agent_activity is joined via correlation_id for tool-call tracing.

CREATE TABLE IF NOT EXISTS agent_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title TEXT NOT NULL DEFAULT '',
    actor TEXT NOT NULL DEFAULT 'agent:nomos',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_active_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS agent_messages (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
    role TEXT NOT NULL,
    content JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_agent_messages_session
    ON agent_messages(session_id, created_at);
CREATE INDEX IF NOT EXISTS idx_agent_sessions_active
    ON agent_sessions(last_active_at DESC);
