-- Durable business history survives task/attempt/attachment deletion. CREATE TABLE team_progress_owners ( organization_id uuid NOT NULL REFERENCES organizations(id), owner_user_id uuid NOT NULL, backfilled_at timestamptz, PRIMARY KEY (organization_id, owner_user_id), FOREIGN KEY (organization_id, owner_user_id) REFERENCES users(organization_id, id) ); CREATE TABLE team_progress_events ( id bigserial PRIMARY KEY, organization_id uuid NOT NULL REFERENCES organizations(id), owner_user_id uuid NOT NULL, group_key text NOT NULL, subject_key text NOT NULL, subject_kind text NOT NULL CHECK (subject_kind IN ('team', 'child')), event_key text NOT NULL, source_task_id text NOT NULL, execution_id text NOT NULL, effective_at timestamptz NOT NULL, recorded_at timestamptz NOT NULL, source_task_deleted_at timestamptz, detail_ciphertext text NOT NULL, UNIQUE (organization_id, owner_user_id, execution_id, event_key), FOREIGN KEY (organization_id, owner_user_id) REFERENCES users(organization_id, id) ); CREATE INDEX team_progress_group_idx ON team_progress_events (organization_id, owner_user_id, group_key, effective_at, id); CREATE INDEX team_progress_subject_idx ON team_progress_events (organization_id, owner_user_id, subject_key); CREATE INDEX team_progress_task_idx ON team_progress_events (organization_id, owner_user_id, source_task_id); CREATE TRIGGER team_progress_owner_not_admin BEFORE INSERT OR UPDATE OF organization_id, owner_user_id ON team_progress_owners FOR EACH ROW EXECUTE FUNCTION reject_admin_task_principal('owner_user_id', 'team_progress_owner_not_admin'); CREATE TRIGGER team_progress_event_not_admin BEFORE INSERT OR UPDATE OF organization_id, owner_user_id ON team_progress_events FOR EACH ROW EXECUTE FUNCTION reject_admin_task_principal('owner_user_id', 'team_progress_event_not_admin');