-- V032 AI Studio & Agent Builder
CREATE TABLE IF NOT EXISTS ai_agent_versions_v032 (id varchar(36) primary key, tenant_id varchar(36) not null, agent_id varchar(36) not null, version integer not null, status varchar(30) not null default 'draft', definition json not null, change_notes text not null default '', created_by varchar(36) not null, approved_by varchar(36), created_at timestamp, approved_at timestamp, UNIQUE(agent_id,version));
CREATE TABLE IF NOT EXISTS ai_evaluation_suites_v032 (id varchar(36) primary key, tenant_id varchar(36) not null, name varchar(180) not null, description text not null default '', cases json not null, thresholds json not null, active boolean not null default true, created_by varchar(36) not null, created_at timestamp);
CREATE TABLE IF NOT EXISTS ai_evaluation_runs_v032 (id varchar(36) primary key, tenant_id varchar(36) not null, suite_id varchar(36) not null, agent_id varchar(36) not null, agent_version_id varchar(36), status varchar(30) not null, score integer not null default 0, results json not null, started_by varchar(36) not null, started_at timestamp, finished_at timestamp);
CREATE TABLE IF NOT EXISTS ai_budget_policies_v032 (id varchar(36) primary key, tenant_id varchar(36) not null, subject_type varchar(30) not null, subject_value varchar(120) not null, monthly_budget_micros bigint not null default 0, warning_percent integer not null default 80, hard_block boolean not null default true, allowed_model_ids json not null, active boolean not null default true, created_by varchar(36) not null, created_at timestamp, UNIQUE(tenant_id,subject_type,subject_value));
CREATE TABLE IF NOT EXISTS ai_agent_memory_v032 (id varchar(36) primary key, tenant_id varchar(36) not null, agent_id varchar(36) not null, user_id varchar(36) not null, memory_type varchar(30) not null, content text not null, metadata_json json not null, expires_at timestamp, created_at timestamp);
-- PostgreSQL production isolation
ALTER TABLE ai_agent_versions_v032 ENABLE ROW LEVEL SECURITY; ALTER TABLE ai_agent_versions_v032 FORCE ROW LEVEL SECURITY;
CREATE POLICY ai_agent_versions_v032_tenant ON ai_agent_versions_v032 USING (tenant_id::text=current_setting('app.current_tenant_id',true)) WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
ALTER TABLE ai_evaluation_suites_v032 ENABLE ROW LEVEL SECURITY; ALTER TABLE ai_evaluation_suites_v032 FORCE ROW LEVEL SECURITY;
CREATE POLICY ai_evaluation_suites_v032_tenant ON ai_evaluation_suites_v032 USING (tenant_id::text=current_setting('app.current_tenant_id',true)) WITH CHECK (tenant_id::text=current_setting('app.current_tenant_id',true));
