Files
archie/internal/platform/pg/migrations/00009_chat.sql
T

76 lines
3.2 KiB
SQL

-- +goose Up
CREATE SCHEMA chat;
-- A session is one conversation between the operator and Archie.
CREATE TABLE chat.sessions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
title text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
owner_id text NOT NULL,
tainted boolean NOT NULL DEFAULT false
);
CREATE INDEX sessions_by_owner ON chat.sessions (org_id, owner_id, updated_at DESC);
-- A turn is one message from the operator and Archie's reply to it. It is
-- stored before it is acknowledged and queued until the turn before it in the
-- same session has ended. Judgement and approvals record the turn's actions
-- with the turn's id as their run id.
CREATE TABLE chat.turns (
seq bigserial PRIMARY KEY,
id uuid NOT NULL UNIQUE,
org_id text NOT NULL,
session_id uuid NOT NULL REFERENCES chat.sessions (id) ON DELETE CASCADE,
state text NOT NULL CHECK (state IN ('queued', 'running', 'succeeded', 'failed', 'cancelled')),
text text NOT NULL,
page text NOT NULL DEFAULT '',
page_label text NOT NULL DEFAULT '',
reply text NOT NULL DEFAULT '',
reasoning text NOT NULL DEFAULT '',
error text NOT NULL DEFAULT '',
cancel boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
started_at timestamptz,
finished_at timestamptz
);
CREATE INDEX turns_by_session ON chat.turns (session_id, seq);
CREATE INDEX turns_queued ON chat.turns (seq) WHERE (state IN ('queued', 'running'));
-- An event is one item a turn streamed: reasoning, reply text, a tool call or
-- its result, an approval request, or how the turn ended. A client resumes the
-- stream by reading the events after the last seq it received.
CREATE TABLE chat.events (
seq bigserial PRIMARY KEY,
turn_id uuid NOT NULL REFERENCES chat.turns (id) ON DELETE CASCADE,
kind text NOT NULL,
data jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX events_by_turn ON chat.events (turn_id, seq);
-- An action is a tool call by a turn's agent that judgement held for approval.
-- The answer arrives through approvals, and an approved action runs once.
CREATE TABLE chat.actions (
id uuid PRIMARY KEY,
org_id text NOT NULL,
turn_id uuid NOT NULL REFERENCES chat.turns (id) ON DELETE CASCADE,
key text NOT NULL,
decision jsonb NOT NULL,
request_id uuid NOT NULL,
path jsonb NOT NULL,
step integer NOT NULL DEFAULT 0,
step_due timestamptz NOT NULL,
state text NOT NULL CHECK (state IN ('waiting', 'approved', 'running', 'succeeded', 'failed', 'unknown', 'denied', 'expired')),
answer jsonb,
result text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now(),
binding jsonb,
binding_digest text NOT NULL DEFAULT '',
UNIQUE (turn_id, key)
);
CREATE INDEX actions_open ON chat.actions (state) WHERE (state IN ('waiting', 'approved', 'running'));
-- +goose Down
DROP SCHEMA chat CASCADE;