Spaces:
Runtime error

ai-tester-platform / supabase_schema_full.sql
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
14.9 kB
-- ============================================================
-- AI Tester Platform - Full Supabase Schema (idempotent)
-- ============================================================
-- Use in Supabase SQL Editor only if needed.
-- In production, app tables are also auto-created by the backend
-- when DATABASE_URL points to Supabase Postgres.
BEGIN;
-- Optional, useful for uuid generation in ad-hoc inserts
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- ============================================================
-- 1) AUTH PROFILE TABLE + POLICIES
-- ============================================================
CREATE TABLE IF NOT EXISTS public.profiles (
id uuid PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
email text NOT NULL,
full_name text,
avatar_url text,
role text DEFAULT 'user' CHECK (role IN ('admin', 'user')),
created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
updated_at timestamp with time zone DEFAULT timezone('utc'::text, now())
);
ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "Public profiles are viewable by everyone" ON public.profiles;
DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles;
DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles;
CREATE POLICY "Public profiles are viewable by everyone"
ON public.profiles FOR SELECT
USING (true);
CREATE POLICY "Users can insert their own profile"
ON public.profiles FOR INSERT
WITH CHECK (auth.uid() = id);
CREATE POLICY "Users can update own profile"
ON public.profiles FOR UPDATE
USING (auth.uid() = id);
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
BEGIN
INSERT INTO public.profiles (id, email, full_name, role)
VALUES (
NEW.id,
NEW.email,
NEW.raw_user_meta_data->>'full_name',
COALESCE(NEW.raw_user_meta_data->>'role', 'user')
)
ON CONFLICT (id) DO UPDATE
SET
email = EXCLUDED.email,
full_name = EXCLUDED.full_name,
updated_at = timezone('utc'::text, now());
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;
CREATE TRIGGER on_auth_user_created
AFTER INSERT ON auth.users
FOR EACH ROW EXECUTE FUNCTION public.handle_new_user();
-- ============================================================
-- 2) CORE APP TABLES
-- ============================================================
CREATE TABLE IF NOT EXISTS public.bots (
id varchar(36) PRIMARY KEY,
name varchar(255) NOT NULL,
description text,
url varchar(500) NOT NULL,
selectors jsonb DEFAULT '{}'::jsonb,
expected_tone jsonb DEFAULT '{}'::jsonb,
rag_config jsonb DEFAULT '{}'::jsonb,
is_active boolean DEFAULT true,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
updated_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
created_by varchar(255),
tags jsonb DEFAULT '[]'::jsonb,
auto_click_new_chat boolean DEFAULT false,
knowledge_boundary_url varchar(500)
);
CREATE TABLE IF NOT EXISTS public.personas (
id varchar(36) PRIMARY KEY,
name varchar(255) NOT NULL,
mood varchar(50) DEFAULT 'neutral',
goal text NOT NULL,
background text,
constraints jsonb DEFAULT '[]'::jsonb,
language varchar(50) DEFAULT 'italian',
communication_style varchar(50) DEFAULT 'normal',
typing_speed varchar(50) DEFAULT 'normal',
tech_proficiency varchar(50) DEFAULT 'average',
patience_level integer DEFAULT 5,
tone_of_voice varchar(50) DEFAULT 'neutral',
vocabulary_type varchar(50) DEFAULT 'standard',
sentence_structure varchar(50) DEFAULT 'mixed',
emotional_expression varchar(50) DEFAULT 'moderate',
response_pacing varchar(50) DEFAULT 'balanced',
is_template boolean DEFAULT false,
tags jsonb DEFAULT '[]'::jsonb,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
created_by varchar(255)
);
CREATE TABLE IF NOT EXISTS public.rag_documents (
id varchar(36) PRIMARY KEY,
bot_id varchar(36) NOT NULL REFERENCES public.bots(id) ON DELETE CASCADE,
filename varchar(255) NOT NULL,
content_hash varchar(64) NOT NULL,
file_size integer NOT NULL,
mime_type varchar(100) DEFAULT 'text/plain',
storage_path varchar(500) NOT NULL,
extracted_text text,
description text,
metadata jsonb DEFAULT '{}'::jsonb,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now())
);
CREATE TABLE IF NOT EXISTS public.bot_versions (
id varchar(36) PRIMARY KEY,
bot_id varchar(36) NOT NULL REFERENCES public.bots(id) ON DELETE CASCADE,
version varchar(50) NOT NULL,
release_notes text,
config_snapshot jsonb DEFAULT '{}'::jsonb,
rag_documents_snapshot jsonb DEFAULT '[]'::jsonb,
is_tested boolean DEFAULT false,
is_approved boolean DEFAULT false,
approved_at timestamp with time zone,
approved_by varchar(255),
created_at timestamp with time zone DEFAULT timezone('utc'::text, now())
);
CREATE TABLE IF NOT EXISTS public.scenarios (
id varchar(36) PRIMARY KEY,
bot_id varchar(36) NOT NULL REFERENCES public.bots(id) ON DELETE CASCADE,
name varchar(255) NOT NULL,
description text,
steps jsonb NOT NULL DEFAULT '[]'::jsonb,
success_criteria jsonb DEFAULT '{}'::jsonb,
is_template boolean DEFAULT false,
tags jsonb DEFAULT '[]'::jsonb,
category varchar(100),
priority integer DEFAULT 1,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
updated_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
created_by varchar(255)
);
CREATE TABLE IF NOT EXISTS public.test_sessions (
id varchar(36) PRIMARY KEY,
bot_id varchar(36) NOT NULL REFERENCES public.bots(id) ON DELETE RESTRICT,
bot_version varchar(50) NOT NULL,
session_name varchar(255),
description text,
config jsonb DEFAULT '{}'::jsonb,
status varchar(50) DEFAULT 'pending',
started_at timestamp with time zone,
completed_at timestamp with time zone,
total_tests integer DEFAULT 0,
passed integer DEFAULT 0,
failed integer DEFAULT 0,
skipped integer DEFAULT 0,
avg_response_time_ms integer,
rag_faithfulness_avg double precision,
tone_match_avg double precision,
error_message text,
max_messages integer,
messages_sent integer DEFAULT 0,
-- Post-session AIS judge orchestration (vedi src/api/routes/sessions.py
-- _run_session_judge_sync). judge_status: idle|pending|running|done|failed.
judge_status varchar(24) DEFAULT 'idle',
judge_started_at timestamp with time zone,
judge_completed_at timestamp with time zone,
judge_model varchar(128),
judge_error text,
judge_progress jsonb,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
created_by varchar(255)
);
CREATE TABLE IF NOT EXISTS public.test_results (
id varchar(36) PRIMARY KEY,
session_id varchar(36) NOT NULL REFERENCES public.test_sessions(id) ON DELETE CASCADE,
scenario_id varchar(36) NOT NULL,
persona_id varchar(36) NOT NULL,
steps_results jsonb DEFAULT '[]'::jsonb,
status varchar(50) NOT NULL,
total_steps integer DEFAULT 0,
passed_steps integer DEFAULT 0,
failed_steps integer DEFAULT 0,
total_duration_ms integer,
avg_response_time_ms integer,
rag_faithfulness_avg double precision,
tone_match_avg double precision,
error_message text,
failure_reason text,
screenshot_urls jsonb DEFAULT '[]'::jsonb,
conversation_log text,
scenario_results jsonb,
started_at timestamp with time zone,
completed_at timestamp with time zone,
created_at timestamp with time zone DEFAULT timezone('utc'::text, now())
);
CREATE TABLE IF NOT EXISTS public.session_scenario_links (
session_id varchar(36) NOT NULL REFERENCES public.test_sessions(id) ON DELETE CASCADE,
scenario_id varchar(36) NOT NULL REFERENCES public.scenarios(id) ON DELETE CASCADE,
persona_id varchar(36) NOT NULL REFERENCES public.personas(id) ON DELETE CASCADE,
priority integer DEFAULT 1,
config_override jsonb DEFAULT '{}'::jsonb,
PRIMARY KEY (session_id, scenario_id, persona_id)
);
-- Platform-level admin overrides. Backing store per /admin/settings:
-- ogni riga sovrascrive una env var a runtime su tutta la piattaforma.
-- Sostituisce il vecchio file `data/system_settings_overrides.json` che su
-- HF Spaces (filesystem ephemeral) si perdeva ad ogni rebuild del container.
CREATE TABLE IF NOT EXISTS public.platform_settings_overrides (
key varchar(128) PRIMARY KEY,
value text NOT NULL,
updated_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
updated_by varchar(255)
);
-- ============================================================
-- 3) COMPATIBILITY MIGRATIONS (safe if re-run)
-- ============================================================
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS max_messages integer;
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS messages_sent integer DEFAULT 0;
ALTER TABLE public.test_results ADD COLUMN IF NOT EXISTS scenario_results jsonb;
-- Post-session AIS judge state (additive). Vedi src/api/routes/sessions.py
-- _run_session_judge_sync: aggiornata in 4 fasi (idle → running → done|failed).
-- Platform settings overrides (idempotente: table created above; safe re-run).
CREATE TABLE IF NOT EXISTS public.platform_settings_overrides (
key varchar(128) PRIMARY KEY,
value text NOT NULL,
updated_at timestamp with time zone DEFAULT timezone('utc'::text, now()),
updated_by varchar(255)
);
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_status varchar(24) DEFAULT 'idle';
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_started_at timestamp with time zone;
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_completed_at timestamp with time zone;
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_model varchar(128);
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_error text;
ALTER TABLE public.test_sessions ADD COLUMN IF NOT EXISTS judge_progress jsonb;
-- ============================================================
-- 4) INDEXES
-- ============================================================
CREATE INDEX IF NOT EXISTS idx_bots_created_at ON public.bots(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_rag_documents_bot_id ON public.rag_documents(bot_id);
CREATE INDEX IF NOT EXISTS idx_bot_versions_bot_id ON public.bot_versions(bot_id);
CREATE INDEX IF NOT EXISTS idx_scenarios_bot_id ON public.scenarios(bot_id);
CREATE INDEX IF NOT EXISTS idx_test_sessions_bot_id ON public.test_sessions(bot_id);
CREATE INDEX IF NOT EXISTS idx_test_sessions_status ON public.test_sessions(status);
CREATE INDEX IF NOT EXISTS idx_test_sessions_judge_status ON public.test_sessions(judge_status);
CREATE INDEX IF NOT EXISTS idx_test_results_session_id ON public.test_results(session_id);
CREATE INDEX IF NOT EXISTS idx_test_results_scenario_id ON public.test_results(scenario_id);
CREATE INDEX IF NOT EXISTS idx_session_scenario_links_session_id ON public.session_scenario_links(session_id);
CREATE INDEX IF NOT EXISTS idx_session_scenario_links_scenario_id ON public.session_scenario_links(scenario_id);
CREATE INDEX IF NOT EXISTS idx_session_scenario_links_persona_id ON public.session_scenario_links(persona_id);
-- ============================================================
-- 5) SECURITY HARDENING (RLS FOR PUBLIC API TABLES)
-- ============================================================
-- The app is backend-driven (FastAPI + server-side DB/service-role access).
-- We keep direct PostgREST access closed for anon/authenticated users.
-- This resolves Supabase Security Advisor findings:
-- - rls_disabled_in_public
-- - sensitive_columns_exposed
ALTER TABLE public.bots ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.personas ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rag_documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.bot_versions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.scenarios ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.test_sessions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.test_results ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.session_scenario_links ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS "service_role_full_access_bots" ON public.bots;
DROP POLICY IF EXISTS "service_role_full_access_personas" ON public.personas;
DROP POLICY IF EXISTS "service_role_full_access_rag_documents" ON public.rag_documents;
DROP POLICY IF EXISTS "service_role_full_access_bot_versions" ON public.bot_versions;
DROP POLICY IF EXISTS "service_role_full_access_scenarios" ON public.scenarios;
DROP POLICY IF EXISTS "service_role_full_access_test_sessions" ON public.test_sessions;
DROP POLICY IF EXISTS "service_role_full_access_test_results" ON public.test_results;
DROP POLICY IF EXISTS "service_role_full_access_session_scenario_links" ON public.session_scenario_links;
CREATE POLICY "service_role_full_access_bots"
ON public.bots FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_personas"
ON public.personas FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_rag_documents"
ON public.rag_documents FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_bot_versions"
ON public.bot_versions FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_scenarios"
ON public.scenarios FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_test_sessions"
ON public.test_sessions FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_test_results"
ON public.test_results FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
CREATE POLICY "service_role_full_access_session_scenario_links"
ON public.session_scenario_links FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
REVOKE ALL ON TABLE public.bots FROM anon, authenticated;
REVOKE ALL ON TABLE public.personas FROM anon, authenticated;
REVOKE ALL ON TABLE public.rag_documents FROM anon, authenticated;
REVOKE ALL ON TABLE public.bot_versions FROM anon, authenticated;
REVOKE ALL ON TABLE public.scenarios FROM anon, authenticated;
REVOKE ALL ON TABLE public.test_sessions FROM anon, authenticated;
REVOKE ALL ON TABLE public.test_results FROM anon, authenticated;
REVOKE ALL ON TABLE public.session_scenario_links FROM anon, authenticated;
COMMIT;