CREATE TABLE incidents ( id uuid PRIMARY KEY, correlation_key text NOT NULL CHECK (char_length(correlation_key) BETWEEN 1 AND 255), title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 240), summary text NOT NULL DEFAULT '' CHECK (char_length(summary) <= 2000), severity text NOT NULL CHECK (severity IN ('attention', 'degraded', 'critical')), status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'acknowledged', 'resolved')), started_at timestamptz NOT NULL, resolved_at timestamptz, owner_user_id uuid REFERENCES users(id) ON DELETE SET NULL, correlation_method text NOT NULL CHECK (char_length(correlation_method) BETWEEN 1 AND 80), confidence numeric(4,3) NOT NULL CHECK (confidence >= 0 AND confidence <= 1), revision bigint NOT NULL DEFAULT 1 CHECK (revision > 0), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), CHECK (status <> 'resolved' OR resolved_at IS NOT NULL), CHECK (status = 'resolved' OR resolved_at IS NULL) ); CREATE UNIQUE INDEX incidents_active_correlation_key_uq ON incidents (correlation_key) WHERE status <> 'resolved'; CREATE INDEX incidents_list_idx ON incidents (status, severity, updated_at DESC, id ASC); CREATE INDEX incidents_correlation_idx ON incidents (correlation_key, updated_at DESC, id ASC); CREATE TABLE incident_alerts ( incident_id uuid NOT NULL REFERENCES incidents(id) ON DELETE CASCADE, alert_id uuid NOT NULL REFERENCES alert_instances(id) ON DELETE RESTRICT, rationale text NOT NULL CHECK (char_length(rationale) BETWEEN 1 AND 500), confidence numeric(4,3) NOT NULL CHECK (confidence >= 0 AND confidence <= 1), correlation_method text NOT NULL CHECK (char_length(correlation_method) BETWEEN 1 AND 80), is_manual boolean NOT NULL DEFAULT false, added_by text NOT NULL DEFAULT '' CHECK (char_length(added_by) <= 160), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (incident_id, alert_id) ); CREATE INDEX incident_alerts_alert_idx ON incident_alerts (alert_id, incident_id); CREATE INDEX incident_alerts_incident_idx ON incident_alerts (incident_id, created_at ASC, alert_id ASC); CREATE TABLE incident_entities ( incident_id uuid NOT NULL REFERENCES incidents(id) ON DELETE CASCADE, entity_id uuid NOT NULL REFERENCES entities(id) ON DELETE RESTRICT, rationale text NOT NULL CHECK (char_length(rationale) BETWEEN 1 AND 500), confidence numeric(4,3) NOT NULL CHECK (confidence >= 0 AND confidence <= 1), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (incident_id, entity_id) ); CREATE INDEX incident_entities_entity_idx ON incident_entities (entity_id, incident_id);