Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calls): LLM to smart assign custom speakers (#3397)
Will Hutchinson36f5ee8fd996
diff --git a/rust/cloud-storage/.sqlx/query-89a884bd52b26e8aaed865bb4f8916be18a81bc149bfb4cc170586f707de7cc3.json b/rust/cloud-storage/.sqlx/query-89a884bd52b26e8aaed865bb4f8916be18a81bc149bfb4cc170586f707de7cc3.jsonnew file mode 100644index 0000000000..8811cf4519--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-89a884bd52b26e8aaed865bb4f8916be18a81bc149bfb4cc170586f707de7cc3.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE call_record_transcripts AS t\n SET custom_speaker = u.custom_speaker\n FROM UNNEST($1::uuid[], $2::text[]) AS u(transcript_id, custom_speaker)\n WHERE t.id = u.transcript_id\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "89a884bd52b26e8aaed865bb4f8916be18a81bc149bfb4cc170586f707de7cc3"+}diff --git a/rust/cloud-storage/.sqlx/query-c4116c441fc76ecc39a9db7c29da7b5a952ef5031c2737d084da33a24af2c8ad.json b/rust/cloud-storage/.sqlx/query-c4116c441fc76ecc39a9db7c29da7b5a952ef5031c2737d084da33a24af2c8ad.jsonnew file mode 100644index 0000000000..d80f30ce43--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c4116c441fc76ecc39a9db7c29da7b5a952ef5031c2737d084da33a24af2c8ad.json@@ -0,0 +1,82 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n call_record_id,\n segment_id,\n speaker_id,\n diarized_speaker_id,\n custom_speaker,\n voice_id,\n content,\n started_at,\n ended_at,\n sequence_num\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "call_record_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "segment_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "speaker_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "diarized_speaker_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "custom_speaker",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "voice_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 7,+ "name": "content",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "started_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "ended_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 10,+ "name": "sequence_num",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ true,+ true,+ true,+ false,+ false,+ true,+ false+ ]+ },+ "hash": "c4116c441fc76ecc39a9db7c29da7b5a952ef5031c2737d084da33a24af2c8ad"+}diff --git a/rust/cloud-storage/.sqlx/query-ee374b0fcc0e59609fbc6368541c65cc9e27d786fd2648040cc9f2c6a3295d8e.json b/rust/cloud-storage/.sqlx/query-ee374b0fcc0e59609fbc6368541c65cc9e27d786fd2648040cc9f2c6a3295d8e.jsonnew file mode 100644index 0000000000..32f9a9bade--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-ee374b0fcc0e59609fbc6368541c65cc9e27d786fd2648040cc9f2c6a3295d8e.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH participant_ids AS (\n SELECT user_id\n FROM call_record_participants\n WHERE call_record_id = $1\n ),\n participant_team_ids AS (\n SELECT DISTINCT tu.team_id\n FROM team_user tu\n JOIN participant_ids p ON p.user_id = tu.user_id\n ),\n candidate_user_ids AS (\n SELECT user_id FROM participant_ids\n UNION\n SELECT tu.user_id\n FROM team_user tu\n JOIN participant_team_ids t ON t.team_id = tu.team_id\n )\n SELECT DISTINCT user_id AS \"user_id!\"\n FROM candidate_user_ids\n ORDER BY user_id ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "ee374b0fcc0e59609fbc6368541c65cc9e27d786fd2648040cc9f2c6a3295d8e"+}diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex 5707b3da72..2fdd90b878 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -157,6 +157,52 @@ pub struct TranscriptSegmentRequest {pub embedding: Option<Vec<f32>>,}+/// Full archived transcript row used by the AI speaker-attribution pipeline.+///+/// This mirrors every column currently stored in `call_record_transcripts` so+/// the AI adapter can reason from both the raw archived speaker data and any+/// existing overrides.+#[derive(Debug, Clone, serde::Serialize)]+pub struct EnrichedCallTranscript {+ /// Stable DB-row id for this archived transcript segment.+ pub id: Uuid,+ /// The archived call record this transcript row belongs to.+ pub call_record_id: Uuid,+ /// LiveKit segment ID, when the archived row has one.+ pub segment_id: Option<String>,+ /// The speaker's original user ID from the transcribed track.+ pub speaker_id: String,+ /// Stable diarization label emitted by the STT provider, when present.+ pub diarized_speaker_id: Option<String>,+ /// Existing custom speaker override, when one has already been assigned.+ pub custom_speaker: Option<String>,+ /// Speaker voice id attached to the transcript row, when available.+ pub voice_id: Option<Uuid>,+ /// The transcribed text content.+ pub content: String,+ /// When the speaker started this segment.+ pub started_at: DateTime<Utc>,+ /// When the speaker stopped this segment, if known.+ pub ended_at: Option<DateTime<Utc>>,+ /// Ordering within the archived call.+ pub sequence_num: i32,+}++/// Backwards-compatible name for callers that refer to the AI transcript input+/// as "enhanced" rather than "enriched".+pub type EnhancedCallTranscript = EnrichedCallTranscript;++/// AI-generated speaker attribution for one archived transcript row.+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]+pub struct CallTranscriptCustomSpeakerResult {+ /// The call transcript id.+ #[serde(alias = "callTranscriptId")]+ pub call_transcript_id: Uuid,+ /// The custom speaker override for the transcript.+ #[serde(alias = "customSpeaker")]+ pub custom_speaker: String,+}+/// Edit call request#[derive(Debug, Clone, serde::Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex 28ba9c6f94..f75e99bd00 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -17,9 +17,10 @@ use crate::domain::models::{use super::models::{AddParticipantError, Call, CallActiveResponse, CallError, CallParticipant, CallRecord,- CallRecordPreview, CallRecordTranscriptSegment, CallTokenResponse, CallWebhookEvent,- EgressS3Config, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse,- GetCallRecordsRequest, LeaveCallResponse, TranscriptSegmentRequest,+ CallRecordPreview, CallRecordTranscriptSegment, CallTokenResponse,+ CallTranscriptCustomSpeakerResult, CallWebhookEvent, EgressS3Config, EnrichedCallTranscript,+ GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetCallRecordsRequest,+ LeaveCallResponse, TranscriptSegmentRequest,};/// Repository port for persisting call state to the database.@@ -95,6 +96,16 @@ pub trait CallRepository: Send + Sync + 'static {call_id: &Uuid,) -> impl Future<Output = Result<i64, Self::Err>> + Send;+ /// Fetch the archived call participants plus all users on those+ /// participants' teams.+ ///+ /// The returned user ids are distinct and owned. This is used as the+ /// candidate speaker set for AI-generated archived transcript attribution.+ fn get_call_participants_with_team_members(+ &self,+ call_record_id: &Uuid,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Self::Err>> + Send;+/// Check if a user is already a participant in a call.fn is_participant(&self,@@ -266,6 +277,26 @@ pub trait CallRepository: Send + Sync + 'static {assignments: &[CustomSpeakerAssignment],) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Fetch archived transcript rows directly from `call_record_transcripts`.+ ///+ /// Unlike [`get_call_record_by_call_id`](Self::get_call_record_by_call_id),+ /// this never consults active call transcript rows and does not collapse+ /// `custom_speaker` over `speaker_id`; callers get the raw archived row.+ fn get_enhanced_call_record_transcripts(+ &self,+ call_record_id: &Uuid,+ ) -> impl Future<Output = Result<Vec<EnrichedCallTranscript>, Self::Err>> + Send;++ /// Overwrite `custom_speaker` for archived transcript rows by row id.+ ///+ /// Each tuple is `(call_record_transcripts.id, custom_speaker)`. Unknown+ /// transcript ids are ignored by the database update. Empty assignment+ /// vectors are a no-op.+ fn overwrite_custom_speakers(+ &self,+ assignments: Vec<(Uuid, String)>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Stable `(macro_user_id, voice_id)` pairs inferred from a finished/// call's archived transcripts. A speaker is returned only when every/// transcript row for that `speaker_id` has the same non-NULL@@ -379,6 +410,18 @@ pub trait CallSummarizer: Send + Sync + 'static {call_id: &Uuid,summary: &str,) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;++ /// Generate row-level `custom_speaker` assignments for archived transcript+ /// rows from the full archived transcript data and a candidate speaker set.+ ///+ /// Implementations should return an empty vector when no confident+ /// attribution can be made. Callers persist non-empty results with+ /// [`CallRepository::overwrite_custom_speakers`].+ fn generate_custom_speakers(+ &self,+ transcript: Vec<EnrichedCallTranscript>,+ candidate_speakers: Vec<MacroUserIdStr<'static>>,+ ) -> impl Future<Output = Result<Vec<CallTranscriptCustomSpeakerResult>, Self::Err>> + Send;}/// RTC client port for interacting with the real-time communication service (e.g., LiveKit).diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 8732f0f448..55b6b13c29 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -28,9 +28,9 @@ use crate::domain::models::{EditCallRecordRequest, EditCallTranscriptRequest};use super::models::{AddParticipantError, CallActiveResponse, CallError, CallRecord, CallRecordTranscriptSegment,- CallTokenResponse, EgressS3Config, GetBatchCallRecordPreviewRequest,- GetBatchCallRecordPreviewResponse, GetCallRecordsRequest, LeaveCallResponse,- TranscriptSegmentRequest,+ CallTokenResponse, CallTranscriptCustomSpeakerResult, EgressS3Config, EnrichedCallTranscript,+ GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetCallRecordsRequest,+ LeaveCallResponse, TranscriptSegmentRequest,};use super::ports::{CallRecordQueryService, CallRepository, CallRtcClient, CallSearchIndexer, CallService,@@ -1155,8 +1155,15 @@ impl<return Ok(());};- // Load the finalized call record. May race with deletion, in which- // case there's nothing to summarize — log and move on.+ if let Err(e) = generate_and_persist_custom_speakers(&self.repo, summarizer, call_id).await+ {+ tracing::error!(error=?e, %call_id, "failed to generate custom speakers before summarization");+ }++ // Load the finalized call record after the custom-speaker step so the+ // summary prompt sees any newly persisted speaker overrides. May race+ // with deletion, in which case there's nothing to summarize — log and+ // move on.let Some(record) = self.repo.get_call_record_by_call_id(call_id)@@ -1276,6 +1283,11 @@ impl<};let repo = self.repo.clone();tokio::spawn(async move {+ if let Err(e) = generate_and_persist_custom_speakers(&repo, &summarizer, &call_id).await+ {+ tracing::error!(error=?e, %call_id, "failed to generate custom speakers before summarization");+ }+let record = match repo.get_call_record_by_call_id(&call_id).await {Ok(Some(record)) => record,Ok(None) => {@@ -1345,8 +1357,8 @@ impl</// Called from `process_webhook_event` immediately after `archive_call`/// finalizes the `call_records` row. Voice ids for consistently diarized/// speakers are enrolled for the users who spoke them. This intentionally- /// does not populate `custom_speaker`; speaker overrides are only changed- /// through explicit edit requests.+ /// does not populate `custom_speaker`; AI speaker attribution is handled+ /// separately before summarization.fn spawn_process_voices_for_call(&self, call_record_id: Uuid) {let repo = self.repo.clone();let voice_repo = self.voice_repo.clone();@@ -1356,6 +1368,56 @@ impl<}}+async fn generate_and_persist_custom_speakers<R, Sm>(+ repo: &R,+ summarizer: &Sm,+ call_record_id: &Uuid,+) -> anyhow::Result<()>+where+ R: CallRepository,+ Sm: CallSummarizer,+{+ let transcripts = repo+ .get_enhanced_call_record_transcripts(call_record_id)+ .await+ .map_err(Into::into)?;+ if transcripts.is_empty() {+ tracing::info!(%call_record_id, "call has empty archived transcript; skipping custom speaker generation");+ return Ok(());+ }++ let candidate_speakers = repo+ .get_call_participants_with_team_members(call_record_id)+ .await+ .map_err(Into::into)?;+ if candidate_speakers.is_empty() {+ tracing::info!(%call_record_id, "call has no candidate speakers; skipping custom speaker generation");+ return Ok(());+ }++ let assignments = summarizer+ .generate_custom_speakers(transcripts, candidate_speakers)+ .await+ .map_err(Into::into)?;+ if assignments.is_empty() {+ tracing::info!(%call_record_id, "custom speaker generation returned no assignments");+ return Ok(());+ }++ let num_assignments = assignments.len();+ repo.overwrite_custom_speakers(+ assignments+ .into_iter()+ .map(|result| (result.call_transcript_id, result.custom_speaker))+ .collect(),+ )+ .await+ .map_err(Into::into)?;++ tracing::info!(%call_record_id, num_assignments, "persisted generated custom speaker assignments");+ Ok(())+}+/// Enroll stable speaker voice ids observed in a freshly archived call.////// For each `speaker_id` in the call transcript, the repository returns@@ -1452,6 +1514,16 @@ impl CallSummarizer for NoopCallSummarizer {"NoopCallSummarizer::generate_call_name invoked; it exists only as a type placeholder when the optional summarizer is None")}++ async fn generate_custom_speakers(+ &self,+ _transcript: Vec<EnrichedCallTranscript>,+ _candidate_speakers: Vec<MacroUserIdStr<'static>>,+ ) -> Result<Vec<CallTranscriptCustomSpeakerResult>, Self::Err> {+ unreachable!(+ "NoopCallSummarizer::generate_custom_speakers invoked; it exists only as a type placeholder when the optional summarizer is None"+ )+ }}/// Lightweight implementation of [`CallRecordQueryService`] for read-onlydiff --git a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rsindex 3b17aeee89..f77a76b8b5 100644--- a/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs+++ b/rust/cloud-storage/call/src/outbound/ai_call_summarizer.rs@@ -6,13 +6,18 @@//! internally constructs its own provider client (see the `memory` crate's//! `judge_memory` for the same pattern this mirrors).+use std::collections::HashSet;use std::fmt::Write as _;use ai::chat_completion::get_chat_completion;use ai::types::{Model, RequestBuilder};use uuid::Uuid;-use crate::domain::models::CallRecordTranscriptSegment;+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::models::{+ CallRecordTranscriptSegment, CallTranscriptCustomSpeakerResult, EnrichedCallTranscript,+};use crate::domain::ports::CallSummarizer;/// Default model used when summarizing a call transcript.@@ -85,6 +90,24 @@ Summary: `Intro call between Jordan (Macro) and Lee (Acme) about a possible \SSO integration.` → `Macro & Acme SSO Intro Call`Summary: `No speech detected in the transcript.` → `UNTITLED_CALL`";+/// System prompt for assigning archived transcript rows to known Macro users.+const CUSTOM_SPEAKER_SYSTEM_PROMPT: &str = "\+You assign speakers in archived call transcript rows to Macro user ids. You are \+given JSON transcript rows from the `call_record_transcripts` table and a JSON \+array of candidate Macro user ids. Your job is to infer the actual speaker for \+each row only when the transcript content and surrounding context make that \+attribution clear.++Rules:+- Output strictly valid JSON and nothing else.+- The JSON must be an array of objects with exactly these keys: \+ `call_transcript_id` and `custom_speaker`.+- `call_transcript_id` must be the `id` value from an input transcript row.+- `custom_speaker` must be one of the candidate Macro user ids exactly.+- Return an entry only when you are confident. If unsure, omit that row.+- If you cannot confidently identify any speaker, return exactly `[]`.+- Do not invent users, do not use display names, and do not include reasons.";+/// Sentinel the model is asked to emit when the summary has no substantive/// content. Mapped to `None` so the caller leaves the existing name untouched.const UNTITLED_CALL_SENTINEL: &str = "UNTITLED_CALL";@@ -180,6 +203,43 @@ impl CallSummarizer for AiCallSummarizer {Ok(sanitize_call_name(&raw))}++ #[tracing::instrument(+ skip(self, transcript, candidate_speakers),+ fields(segment_count = transcript.len(), candidate_count = candidate_speakers.len()),+ err+ )]+ async fn generate_custom_speakers(+ &self,+ transcript: Vec<EnrichedCallTranscript>,+ candidate_speakers: Vec<MacroUserIdStr<'static>>,+ ) -> Result<Vec<CallTranscriptCustomSpeakerResult>, Self::Err> {+ if transcript.is_empty() || candidate_speakers.is_empty() {+ return Ok(Vec::new());+ }++ let transcript_ids: HashSet<Uuid> = transcript.iter().map(|row| row.id).collect();+ let candidate_user_ids: HashSet<String> = candidate_speakers+ .iter()+ .map(|user_id| user_id.as_ref().to_string())+ .collect();+ let user_message = format_custom_speakers_prompt(&transcript, &candidate_speakers);++ let request = RequestBuilder::new()+ .model(SUMMARIZATION_MODEL)+ .system_prompt(CUSTOM_SPEAKER_SYSTEM_PROMPT)+ .user_message(user_message)+ .build();++ let raw = get_chat_completion(request)+ .await+ .map_err(|e| anyhow::anyhow!(e))+ .inspect_err(|e| {+ tracing::error!(error = ?e, "ai custom-speaker generation failed");+ })?;++ parse_custom_speaker_results(&raw, &transcript_ids, &candidate_user_ids)+ }}#[cfg(test)]@@ -235,6 +295,76 @@ fn sanitize_call_name(raw: &str) -> Option<String> {if cut.is_empty() { None } else { Some(cut) }}+/// Render archived transcript rows and candidate speakers for the speaker+/// attribution prompt.+fn format_custom_speakers_prompt(+ transcript: &[EnrichedCallTranscript],+ candidate_speakers: &[MacroUserIdStr<'static>],+) -> String {+ let candidate_user_ids: Vec<&str> = candidate_speakers+ .iter()+ .map(|user_id| user_id.as_ref())+ .collect();+ let transcript_json =+ serde_json::to_string_pretty(transcript).unwrap_or_else(|_| "[]".to_string());+ let candidate_json =+ serde_json::to_string_pretty(&candidate_user_ids).unwrap_or_else(|_| "[]".to_string());++ format!(+ "Candidate Macro user ids:\n{candidate_json}\n\nArchived transcript rows:\n{transcript_json}\n\nReturn only the JSON array of confident custom speaker assignments."+ )+}++/// Parse and validate model output for custom-speaker attribution.+fn parse_custom_speaker_results(+ raw: &str,+ valid_transcript_ids: &HashSet<Uuid>,+ candidate_user_ids: &HashSet<String>,+) -> anyhow::Result<Vec<CallTranscriptCustomSpeakerResult>> {+ let json = extract_json_array(raw)?;+ let parsed: Vec<CallTranscriptCustomSpeakerResult> = serde_json::from_str(json)?;+ let mut seen_transcript_ids = HashSet::new();+ let mut results = Vec::with_capacity(parsed.len());++ for result in parsed {+ if !valid_transcript_ids.contains(&result.call_transcript_id) {+ continue;+ }++ let Ok(normalized_user_id) = MacroUserIdStr::try_from(result.custom_speaker) else {+ continue;+ };+ let normalized_custom_speaker = normalized_user_id.as_ref().to_string();+ if !candidate_user_ids.contains(&normalized_custom_speaker)+ || !seen_transcript_ids.insert(result.call_transcript_id)+ {+ continue;+ }++ results.push(CallTranscriptCustomSpeakerResult {+ call_transcript_id: result.call_transcript_id,+ custom_speaker: normalized_custom_speaker,+ });+ }++ Ok(results)+}++/// Extract the first JSON array from a model response.+fn extract_json_array(raw: &str) -> anyhow::Result<&str> {+ let trimmed = raw.trim();+ let Some(start) = trimmed.find('[') else {+ anyhow::bail!("custom speaker response did not contain a JSON array");+ };+ let Some(end) = trimmed.rfind(']') else {+ anyhow::bail!("custom speaker response did not contain a complete JSON array");+ };+ if end < start {+ anyhow::bail!("custom speaker response had malformed JSON array bounds");+ }+ Ok(&trimmed[start..=end])+}+/// Render the transcript as a chronological, speaker-labeled block suitable/// for inclusion in an LLM user message. Segments are expected to already be/// ordered by `sequence_num` ascending; we preserve that order verbatim.diff --git a/rust/cloud-storage/call/src/outbound/ai_call_summarizer/test.rs b/rust/cloud-storage/call/src/outbound/ai_call_summarizer/test.rsindex 7169fe62f3..77131e3ff4 100644--- a/rust/cloud-storage/call/src/outbound/ai_call_summarizer/test.rs+++ b/rust/cloud-storage/call/src/outbound/ai_call_summarizer/test.rs@@ -1,6 +1,11 @@+use std::collections::HashSet;++use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;+use super::{- CALL_NAME_MAX_CHARS, NULL_SUMMARY_SENTINEL, UNTITLED_CALL_SENTINEL, parse_summary,- sanitize_call_name,+ CALL_NAME_MAX_CHARS, NULL_SUMMARY_SENTINEL, UNTITLED_CALL_SENTINEL,+ parse_custom_speaker_results, parse_summary, sanitize_call_name,};#[test]@@ -94,3 +99,82 @@ fn sanitize_preserves_short_titles_verbatim() {let input = "Rocket Launch Postmortem";assert_eq!(sanitize_call_name(input).as_deref(), Some(input));}++#[test]+fn parse_custom_speaker_results_accepts_json_array() {+ let transcript_id = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaaa);+ let valid_transcript_ids = HashSet::from([transcript_id]);+ let candidate_user_ids = HashSet::from(["macro|[email protected]".to_string()]);++ let results = parse_custom_speaker_results(+ r#"[{"call_transcript_id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","custom_speaker":"macro|[email protected]"}]"#,+ &valid_transcript_ids,+ &candidate_user_ids,+ )+ .expect("valid result should parse");++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].call_transcript_id, transcript_id);+ assert_eq!(results[0].custom_speaker, "macro|[email protected]");+}++#[test]+fn parse_custom_speaker_results_accepts_fenced_json_and_camel_case() {+ let transcript_id = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbbb);+ let valid_transcript_ids = HashSet::from([transcript_id]);+ let candidate_user_ids = HashSet::from(["macro|[email protected]".to_string()]);++ let results = parse_custom_speaker_results(+ "```json\n[{\"callTranscriptId\":\"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb\",\"customSpeaker\":\"macro|[email protected]\"}]\n```",+ &valid_transcript_ids,+ &candidate_user_ids,+ )+ .expect("fenced json should parse");++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].call_transcript_id, transcript_id);+ assert_eq!(results[0].custom_speaker, "macro|[email protected]");+}++#[test]+fn parse_custom_speaker_results_filters_unknown_invalid_and_duplicate_entries() {+ let transcript_id = Uuid::from_u128(0xcccccccc_cccc_cccc_cccc_cccccccccccc);+ let unknown_id = Uuid::from_u128(0xdddddddd_dddd_dddd_dddd_dddddddddddd);+ let valid_transcript_ids = HashSet::from([transcript_id]);+ let candidate_user_ids = HashSet::from(["macro|[email protected]".to_string()]);++ let raw = format!(+ r#"[+ {{"call_transcript_id":"{transcript_id}","custom_speaker":"macro|[email protected]"}},+ {{"call_transcript_id":"{transcript_id}","custom_speaker":"macro|[email protected]"}},+ {{"call_transcript_id":"{unknown_id}","custom_speaker":"macro|[email protected]"}},+ {{"call_transcript_id":"{transcript_id}","custom_speaker":"macro|[email protected]"}},+ {{"call_transcript_id":"{transcript_id}","custom_speaker":"not-a-user"}}+ ]"#+ );++ let results = parse_custom_speaker_results(&raw, &valid_transcript_ids, &candidate_user_ids)+ .expect("json should parse");++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].call_transcript_id, transcript_id);+ assert_eq!(results[0].custom_speaker, "macro|[email protected]");+}++#[test]+fn parse_custom_speaker_results_normalizes_candidate_user_ids() {+ let transcript_id = Uuid::from_u128(0xeeeeeeee_eeee_eeee_eeee_eeeeeeeeeeee);+ let valid_transcript_ids = HashSet::from([transcript_id]);+ let candidate = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let candidate_user_ids = HashSet::from([candidate.as_ref().to_string()]);++ let results = parse_custom_speaker_results(+ r#"[{"call_transcript_id":"eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee","custom_speaker":"macro|[email protected]"}]"#,+ &valid_transcript_ids,+ &candidate_user_ids,+ )+ .expect("valid result should parse");++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].custom_speaker, "macro|[email protected]");+}diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex b571e792f5..2ab818e171 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -21,7 +21,7 @@ use uuid::Uuid;use crate::domain::models::{AddParticipantError, Call, CallParticipant, CallRecord, CallRecordParticipant,CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,- EditCallRecordRequest, TranscriptSegmentRequest, WithCallId,+ EditCallRecordRequest, EnrichedCallTranscript, TranscriptSegmentRequest, WithCallId,};use crate::domain::ports::CallRepository;@@ -412,6 +412,46 @@ impl CallRepository for PgCallRepo {.await}+ #[tracing::instrument(err, skip(self))]+ async fn get_call_participants_with_team_members(+ &self,+ call_record_id: &Uuid,+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ WITH participant_ids AS (+ SELECT user_id+ FROM call_record_participants+ WHERE call_record_id = $1+ ),+ participant_team_ids AS (+ SELECT DISTINCT tu.team_id+ FROM team_user tu+ JOIN participant_ids p ON p.user_id = tu.user_id+ ),+ candidate_user_ids AS (+ SELECT user_id FROM participant_ids+ UNION+ SELECT tu.user_id+ FROM team_user tu+ JOIN participant_team_ids t ON t.team_id = tu.team_id+ )+ SELECT DISTINCT user_id AS "user_id!"+ FROM candidate_user_ids+ ORDER BY user_id ASC+ "#,+ call_record_id,+ )+ .fetch_all(&self.pool)+ .await?;++ rows.into_iter()+ .map(|row| {+ MacroUserIdStr::try_from(row.user_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))+ })+ .collect()+ }+#[tracing::instrument(err, skip(self))]async fn is_participant(&self, call_id: &Uuid, user_id: &str) -> Result<bool, Self::Err> {sqlx::query_scalar!(@@ -1445,6 +1485,80 @@ impl CallRepository for PgCallRepo {Ok(())}+ #[tracing::instrument(err, skip(self))]+ async fn get_enhanced_call_record_transcripts(+ &self,+ call_record_id: &Uuid,+ ) -> Result<Vec<EnrichedCallTranscript>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ SELECT+ id,+ call_record_id,+ segment_id,+ speaker_id,+ diarized_speaker_id,+ custom_speaker,+ voice_id,+ content,+ started_at,+ ended_at,+ sequence_num+ FROM call_record_transcripts+ WHERE call_record_id = $1+ ORDER BY sequence_num ASC+ "#,+ call_record_id,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| EnrichedCallTranscript {+ id: row.id,+ call_record_id: row.call_record_id,+ segment_id: row.segment_id,+ speaker_id: row.speaker_id,+ diarized_speaker_id: row.diarized_speaker_id,+ custom_speaker: row.custom_speaker,+ voice_id: row.voice_id,+ content: row.content,+ started_at: row.started_at,+ ended_at: row.ended_at,+ sequence_num: row.sequence_num,+ })+ .collect())+ }++ #[tracing::instrument(skip(self, assignments), fields(num_assignments = assignments.len()), err)]+ async fn overwrite_custom_speakers(+ &self,+ assignments: Vec<(Uuid, String)>,+ ) -> Result<(), Self::Err> {+ if assignments.is_empty() {+ return Ok(());+ }++ let (transcript_ids, custom_speakers): (Vec<Uuid>, Vec<String>) =+ assignments.into_iter().unzip();++ sqlx::query!(+ r#"+ UPDATE call_record_transcripts AS t+ SET custom_speaker = u.custom_speaker+ FROM UNNEST($1::uuid[], $2::text[]) AS u(transcript_id, custom_speaker)+ WHERE t.id = u.transcript_id+ "#,+ &transcript_ids,+ &custom_speakers,+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }+/// Return stable `(macro_user_id, voice_id)` pairs for one archived call.////// `call_record_id` scopes the scan to a single call's archived transcript rows.diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex 9e5105fafe..58c27b1fc7 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -2461,6 +2461,190 @@ async fn insert_call_summary_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhowOk(())}+// -- get_call_participants_with_team_members ----------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_participants_with_team_members_returns_distinct_users(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let team_id = Uuid::from_u128(0x00000000_0000_0000_0000_00000000beef);++ insert_user_mapping(&pool, USER_A.deref(), MACRO_USER_A).await?;+ insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;+ insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;++ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#,+ team_id,+ "speaker candidates",+ USER_A.deref().as_ref(),+ )+ .execute(&pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role) VALUES+ ($1, $2, 'owner'),+ ($3, $2, 'member'),+ ($4, $2, 'member')+ "#,+ USER_A.deref().as_ref(),+ team_id,+ USER_B.deref().as_ref(),+ USER_C.deref().as_ref(),+ )+ .execute(&pool)+ .await?;++ let users = repo+ .get_call_participants_with_team_members(&CALL_ARCHIVED)+ .await?;+ let user_ids: Vec<String> = users+ .into_iter()+ .map(|user_id| user_id.as_ref().to_string())+ .collect();++ assert_eq!(+ user_ids,+ vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ]+ );+ Ok(())+}++// -- get_enhanced_call_record_transcripts -------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_enhanced_call_record_transcripts_returns_archived_rows(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ let transcripts = repo+ .get_enhanced_call_record_transcripts(&CALL_ARCHIVED)+ .await?;++ assert_eq!(transcripts.len(), 3);+ assert_eq!(transcripts[0].call_record_id, CALL_ARCHIVED);+ assert_eq!(transcripts[0].segment_id.as_deref(), Some("seg-arch-1"));+ assert_eq!(transcripts[0].speaker_id, "macro|[email protected]");+ assert_eq!(+ transcripts[0].diarized_speaker_id.as_deref(),+ Some("spk-arch-a0")+ );+ assert!(transcripts[0].custom_speaker.is_none());+ assert!(transcripts[0].voice_id.is_none());+ assert_eq!(transcripts[0].content, "archived hello");+ assert_eq!(transcripts[0].sequence_num, 1);++ assert_eq!(transcripts[2].segment_id.as_deref(), Some("seg-arch-3"));+ assert_eq!(+ transcripts[2].custom_speaker.as_deref(),+ Some(USER_B.deref().as_ref())+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_enhanced_call_record_transcripts_unknown_call_returns_empty(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ let transcripts = repo+ .get_enhanced_call_record_transcripts(&Uuid::now_v7())+ .await?;++ assert!(transcripts.is_empty());+ Ok(())+}++// -- overwrite_custom_speakers ------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn overwrite_custom_speakers_sets_rows_by_transcript_id(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ let rows = sqlx::query!(+ r#"+ SELECT id+ FROM call_record_transcripts+ WHERE call_record_id = $1+ ORDER BY sequence_num ASC+ "#,+ CALL_ARCHIVED,+ )+ .fetch_all(&pool)+ .await?;+ let first_id = rows[0].id;+ let second_id = rows[1].id;++ repo.overwrite_custom_speakers(vec![+ (first_id, USER_C.deref().to_string()),+ (second_id, USER_A.deref().to_string()),+ ])+ .await?;++ let stored = sqlx::query!(+ r#"+ SELECT custom_speaker+ FROM call_record_transcripts+ WHERE call_record_id = $1+ ORDER BY sequence_num ASC+ "#,+ CALL_ARCHIVED,+ )+ .fetch_all(&pool)+ .await?;++ let first_custom_speaker = stored[0].custom_speaker.as_deref();+ let second_custom_speaker = stored[1].custom_speaker.as_deref();+ let third_custom_speaker = stored[2].custom_speaker.as_deref();++ assert_eq!(first_custom_speaker, Some(USER_C.deref().as_ref()));+ assert_eq!(second_custom_speaker, Some(USER_A.deref().as_ref()));+ assert_eq!(third_custom_speaker, Some(USER_B.deref().as_ref()));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn overwrite_custom_speakers_empty_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool.clone());++ repo.overwrite_custom_speakers(Vec::new()).await?;++ let count = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM call_record_transcripts WHERE call_record_id = $1"#,+ CALL_ARCHIVED,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 3);+ Ok(())+}+// -- patch_call_transcript_custom_speakers ------------------------------------#[sqlx::test(