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(routines): add Call started and Call ended triggers (#8064)
teo671c1aa7ccd9
diff --git a/.sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.json b/.sqlx/query-6ffb1830d2f531af477fdf40cc8269f4d0e4027101768ad0173331063445a415.jsonsimilarity index 50%rename from .sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.jsonrename to .sqlx/query-6ffb1830d2f531af477fdf40cc8269f4d0e4027101768ad0173331063445a415.jsonindex 0010b2933a..20d2f554f9 100644--- a/.sqlx/query-5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41.json+++ b/.sqlx/query-6ffb1830d2f531af477fdf40cc8269f4d0e4027101768ad0173331063445a415.json@@ -1,15 +1,23 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)\n SELECT $1, user_id, joined_at, left_at\n FROM call_participants\n WHERE call_id = $2\n ",+ "query": "\n INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)\n SELECT $1, user_id, joined_at, left_at\n FROM call_participants\n WHERE call_id = $2\n RETURNING user_id\n ","describe": {- "columns": [],+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ }+ ],"parameters": {"Left": ["Uuid","Uuid"]},- "nullable": []+ "nullable": [+ false+ ]},- "hash": "5d7c176f88f6883ffdd41a43969a101f26817ebd80c68dbeffe7c3226ab67a41"+ "hash": "6ffb1830d2f531af477fdf40cc8269f4d0e4027101768ad0173331063445a415"}diff --git a/Cargo.lock b/Cargo.lockindex fce86cd057..d398d53408 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -16706,6 +16706,7 @@ dependencies = ["axum","bot_id","bots",+ "call","channel_sender","channels","chrono",diff --git a/apps/web/src/features/routines/components/routine-triggers.tsx b/apps/web/src/features/routines/components/routine-triggers.tsxindex 1d271691e1..c72d4073db 100644--- a/apps/web/src/features/routines/components/routine-triggers.tsx+++ b/apps/web/src/features/routines/components/routine-triggers.tsx@@ -8,6 +8,7 @@ import EnvelopeIcon from '@phosphor/envelope.svg';import FileIcon from '@phosphor/file-text.svg';import HashIcon from '@phosphor/hash.svg';import SearchIcon from '@phosphor/magnifying-glass.svg';+import PhoneIcon from '@phosphor/phone.svg';import PlusIcon from '@phosphor/plus.svg';import { Button, badgeTriggerClasses } from '@ui';import { format } from 'date-fns';@@ -82,6 +83,9 @@ function EventIcon(props: { group: RoutineEventGroup; class: string }) {<Match when={props.group === 'Email'}><EnvelopeIcon class={props.class} /></Match>+ <Match when={props.group === 'Calls'}>+ <PhoneIcon class={props.class} />+ </Match></Switch>);}@@ -93,6 +97,7 @@ function TriggerIcon(props: { trigger?: RoutineTriggerDraft }) {if (kind === 'TASK') return 'Tasks';if (kind === 'THREAD') return 'Email';if (kind === 'DOCUMENT') return 'Documents';+ if (kind === 'CALL_RECORD') return 'Calls';return 'Channels';};return (diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.tsindex c816ee2ad2..2f68bc2ea6 100644--- a/apps/web/src/features/routines/core/routine-triggers.ts+++ b/apps/web/src/features/routines/core/routine-triggers.ts@@ -34,6 +34,8 @@ export const routineTriggerSchema = z.discriminatedUnion('kind', ['channel.mentioned','channel.message_patched','channel.message_attachment_created',+ 'call.started',+ 'call.ended',])).min(1),@@ -51,6 +53,7 @@ export const routineEventGroups = ['Documents','Tasks','Email',+ 'Calls',] as const;export type RoutineEventGroup = (typeof routineEventGroups)[number];export const routineEvents: {@@ -122,6 +125,20 @@ export const routineEvents: {description:'New mail arrives in your inbox. Excludes spam, trash, drafts and historical imports.',},+ {+ value: 'call.started',+ label: 'Call started',+ group: 'Calls',+ description:+ 'A call you start begins. The routine gets the call and who has joined so far.',+ },+ {+ value: 'call.ended',+ label: 'Call ended',+ group: 'Calls',+ description:+ 'A call you joined ends. The routine gets the call’s participants and transcript.',+ },];// Preserve saved selectors while keeping the creation menu focused on the@@ -138,6 +155,8 @@ export function eventScopeKind(trigger: EventTriggerDraft) {return 'DOCUMENT';if (trigger.events.every((event) => event.startsWith('email.')))return 'THREAD';+ if (trigger.events.every((event) => event.startsWith('call.')))+ return 'CALL_RECORD';return 'CHANNEL';}@@ -149,15 +168,29 @@ export function conditionPlaceholder(trigger: EventTriggerDraft) {.with('TASK', () => 'Is this task a bug report?').with('DOCUMENT', () => 'Is this document meeting notes?').with('CHANNEL', () => 'Is someone asking for help?')+ .with('CALL_RECORD', () => 'Was this a call with a customer?').exhaustive();}export function isGlobalEvent(events: readonly RoutineEventName[]) {return events.every(- (event) => event.endsWith('.created') || event === 'email.message_received'+ (event) =>+ event.endsWith('.created') ||+ event === 'email.message_received' ||+ event === 'call.started' ||+ event === 'call.ended');}+/** Chip label for a call trigger's global scope. */+export function callEventScopeLabel(events: readonly RoutineEventName[]) {+ const started = events.includes('call.started');+ const ended = events.includes('call.ended');+ if (started && ended) return 'Your calls';+ if (started) return 'Calls you start';+ return 'Calls you join';+}+export function eventTriggerLabel(trigger: EventTriggerDraft) {return trigger.events.map(diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.tsindex edb5c670f2..bd354f69b9 100644--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts@@ -132,6 +132,33 @@ describe('routine trigger mapping', () => {});});+describe('call triggers', () => {+ it('fire on every call the owner starts or joins, without choosing items', async () => {+ const { callEventScopeLabel, eventScopeKind, isGlobalEvent } = await import(+ '../core/routine-triggers'+ );+ for (const event of ['call.started', 'call.ended'] as const) {+ const trigger = {+ id: 'call',+ kind: 'event' as const,+ events: [event],+ };+ expect(isGlobalEvent(trigger.events)).toBe(true);+ expect(eventScopeKind(trigger)).toBe('CALL_RECORD');+ expect(validateTriggers([trigger], true)).toBeNull();+ expect(serializeTriggers([trigger])).toEqual({+ type: 'events',+ filters: [{ events: [event] }],+ });+ }+ expect(callEventScopeLabel(['call.started'])).toBe('Calls you start');+ expect(callEventScopeLabel(['call.ended'])).toBe('Calls you join');+ expect(callEventScopeLabel(['call.started', 'call.ended'])).toBe(+ 'Your calls'+ );+ });+});+describe('trigger conditions', () => {it('round trips a condition with its filter', () => {const config = {diff --git a/apps/web/src/features/routines/routine-event-scope.tsx b/apps/web/src/features/routines/routine-event-scope.tsxindex f921129958..adb20f7622 100644--- a/apps/web/src/features/routines/routine-event-scope.tsx+++ b/apps/web/src/features/routines/routine-event-scope.tsx@@ -2,10 +2,15 @@ import { useQuickAccessEntities } from '@property/editors/selectors/entityUtils'import { PropertyEntitySelector } from '@property/editors/selectors/PropertyEntitySelector';import { Suspense } from 'solid-js';import { match } from 'ts-pattern';+import {+ callEventScopeLabel,+ type RoutineEventName,+} from './core/routine-triggers';type ScopeProps = {- kind: 'CHANNEL' | 'DOCUMENT' | 'TASK' | 'THREAD';+ kind: 'CHANNEL' | 'DOCUMENT' | 'TASK' | 'THREAD' | 'CALL_RECORD';ids?: string[];+ events?: readonly RoutineEventName[];};function entityLabel(kind: ScopeProps['kind']) {@@ -14,6 +19,7 @@ function entityLabel(kind: ScopeProps['kind']) {.with('DOCUMENT', () => 'document').with('TASK', () => 'task').with('THREAD', () => 'email thread')+ .with('CALL_RECORD', () => 'call').exhaustive();}@@ -22,6 +28,8 @@ export function RoutineEventScopeLabel(props: ScopeProps) {const label = () => {const singular = entityLabel(props.kind);if (props.kind === 'THREAD' && props.ids === undefined) return 'Your inbox';+ if (props.kind === 'CALL_RECORD' && props.ids === undefined)+ return callEventScopeLabel(props.events ?? ['call.ended']);if (props.ids === undefined) return `Any ${singular}`;if (!props.ids.length) return `Choose ${singular}s`;if (props.ids.length > 1) return `${props.ids.length} ${singular}s`;diff --git a/apps/web/src/features/routines/routine-triggers.tsx b/apps/web/src/features/routines/routine-triggers.tsxindex 950b64acb6..3ab584c7f3 100644--- a/apps/web/src/features/routines/routine-triggers.tsx+++ b/apps/web/src/features/routines/routine-triggers.tsx@@ -33,6 +33,7 @@ export function RoutineTriggers(props: {<RoutineEventScopeLabelkind={eventScopeKind(trigger())}ids={trigger().ids}+ events={trigger().events}/></Suspense>)}diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.tsindex ec7598b579..9e61c99ca2 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts@@ -27,4 +27,6 @@ export const EventName = {channelmentioned: 'channel.mentioned',channelmessage_patched: 'channel.message_patched',channelmessage_attachment_created: 'channel.message_attachment_created',+ callstarted: 'call.started',+ callended: 'call.ended',} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.jsonindex 373779fff3..970f93d88b 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json@@ -902,7 +902,9 @@"channel.message_posted","channel.mentioned","channel.message_patched",- "channel.message_attachment_created"+ "channel.message_attachment_created",+ "call.started",+ "call.ended"]},"ExecutionResource": {diff --git a/crates/call/src/domain/activity/test.rs b/crates/call/src/domain/activity/test.rsindex 4b2979784e..0375124bb6 100644--- a/crates/call/src/domain/activity/test.rs+++ b/crates/call/src/domain/activity/test.rs@@ -23,6 +23,10 @@ fn archived(ended_at,duration_ms,participant_count: 2,+ participants: vec![+ "macro|[email protected]".to_string().try_into().unwrap(),+ "macro|[email protected]".to_string().try_into().unwrap(),+ ],has_recording: false,archive_reason: crate::domain::events::CallArchiveReason::LastParticipantLeft,}),diff --git a/crates/call/src/domain/events.rs b/crates/call/src/domain/events.rsindex c04a4491a8..12982d0eeb 100644--- a/crates/call/src/domain/events.rs+++ b/crates/call/src/domain/events.rs@@ -56,6 +56,10 @@ pub struct CallRecordArchivedMetadata {pub duration_ms: Option<i64>,/// Number of distinct participants over the call's lifetime.pub participant_count: usize,+ /// Macro accounts that joined the call over its lifetime. Empty in events+ /// published before this field existed.+ #[serde(default)]+ pub participants: Vec<MacroUserIdStr<'static>>,/// Whether the call has an associated recording.pub has_recording: bool,/// Reason the call was archived.diff --git a/crates/call/src/domain/events/test.rs b/crates/call/src/domain/events/test.rsindex 750169cf8c..cdaf2ecc18 100644--- a/crates/call/src/domain/events/test.rs+++ b/crates/call/src/domain/events/test.rs@@ -54,7 +54,11 @@ fn topic_events() -> Vec<(CallTopicEvent, Value)> {started_at: timestamp("2026-07-27T18:01:02Z"),ended_at: timestamp("2026-07-27T18:03:07Z"),duration_ms: None,- participant_count: 4,+ participant_count: 2,+ participants: vec![+ user_id("macro|[email protected]"),+ user_id("macro|[email protected]"),+ ],has_recording: true,archive_reason: CallArchiveReason::LastParticipantLeft,}),@@ -67,7 +71,8 @@ fn topic_events() -> Vec<(CallTopicEvent, Value)> {"started_at": "2026-07-27T18:01:02Z","ended_at": "2026-07-27T18:03:07Z","duration_ms": null,- "participant_count": 4,+ "participant_count": 2,+ "participants": ["macro|[email protected]", "macro|[email protected]"],"has_recording": true,"archive_reason": "last_participant_left",},@@ -195,6 +200,33 @@ fn constructors_use_calls_topic_bare_call_id_key_and_schema_version_one() {}}+#[test]+fn archived_events_published_before_participants_decode_without_them() {+ let payload = json!({+ "event_id": EVENT_ID,+ "schema_version": 1,+ "event_type": "call.record_archived",+ "metadata": {+ "call_id": CALL_ID,+ "channel_id": CHANNEL_ID,+ "created_by": "macro|[email protected]",+ "started_at": "2026-07-27T18:01:02Z",+ "ended_at": "2026-07-27T18:03:07Z",+ "duration_ms": 125_000,+ "participant_count": 3,+ "has_recording": false,+ "archive_reason": "room_finished",+ },+ });+ let decoded = CallMacroEvent::decode(CALL_ID, &serde_json::to_vec(&payload).unwrap())+ .expect("decodable event");+ let CallTopicEvent::RecordArchived(metadata) = &decoded.event().event else {+ panic!("expected an archived call");+ };+ assert_eq!(metadata.participant_count, 3);+ assert!(metadata.participants.is_empty());+}+#[test]fn archive_reasons_use_exact_wire_names() {assert_eq!(diff --git a/crates/call/src/domain/models.rs b/crates/call/src/domain/models.rsindex 4900b2d0fc..fa1f7cdaf3 100644--- a/crates/call/src/domain/models.rs+++ b/crates/call/src/domain/models.rs@@ -49,8 +49,8 @@ pub struct ArchivedCall {pub duration_ms: i64,/// Whether a recording egress was started before the call was archived.pub has_recording: bool,- /// Number of distinct participants over the call's lifetime.- pub participant_count: usize,+ /// Macro accounts that joined the call over its lifetime, once each.+ pub participants: Vec<String>,}/// The people known to have been on, or invited to, an archived call.diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rsindex 7f6df20843..bd9a517889 100644--- a/crates/call/src/domain/ports.rs+++ b/crates/call/src/domain/ports.rs@@ -1074,6 +1074,19 @@ pub trait CallRecordQueryService: Send + Sync + 'static {) -> impl Future<Output = Result<CallPeople, CallError>> + Send;}+/// Read-only port for one call record under its reader's access, for services+/// that react to calls rather than manage them.+pub trait CallRecordReader: Send + Sync + 'static {+ /// The record the receipt authorizes, with its participants, guests and+ /// transcript, and its channel named as the receipt's user sees it. The+ /// receipt must be for `EntityType::Call`, keyed by the call's UUID.+ /// Returns [`CallError::NotFound`] once the record is gone.+ fn get_call_record(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<CallRecord, CallError>> + Send;+}+/// No-op implementation of [`CallRecordQueryService`] for services/// that do not have call infrastructure.pub struct NoOpCallRecordQueryService;diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rsindex ec57e4130f..2527d2cd16 100644--- a/crates/call/src/domain/service.rs+++ b/crates/call/src/domain/service.rs@@ -58,8 +58,8 @@ use super::models::{LeaveCallResponse, RingStatus, RingStatusResponse, TranscriptSegmentRequest,};use super::ports::{- CallRecordQueryService, CallRepository, CallRtcClient, CallService, CallSummarizer,- NoOpVoiceRepository, RecordingStorage, VoiceRepository,+ CallRecordQueryService, CallRecordReader, CallRepository, CallRtcClient, CallService,+ CallSummarizer, NoOpVoiceRepository, RecordingStorage, VoiceRepository,};/// The concrete call service implementation.@@ -295,6 +295,23 @@ impl<}};+ let participants = archived+ .participants+ .iter()+ .filter_map(|participant| {+ MacroUserIdStr::parse_from_str(participant)+ .inspect_err(|error| {+ tracing::error!(+ error = ?error,+ call_id = %archived.call_id,+ "failed to parse stored call participant; omitting it from the archived event"+ );+ })+ .ok()+ .map(MacroUserIdStr::into_owned)+ })+ .collect();+self.publish_call_event(&CallMacroEvent::record_archived(CallRecordArchivedMetadata {call_id: archived.call_id,@@ -303,7 +320,8 @@ impl<started_at: archived.started_at,ended_at: archived.ended_at,duration_ms: Some(archived.duration_ms),- participant_count: archived.participant_count,+ participant_count: archived.participants.len(),+ participants,has_recording: archived.has_recording,archive_reason,},@@ -1491,32 +1509,11 @@ impl<&self,receipt: EntityAccessReceipt<ViewAccessLevel>,) -> Result<CallRecord, CallError> {- let entity = receipt.entity();- if entity.entity_type != EntityType::Call {- return Err(CallError::Internal(anyhow::anyhow!(- "expected Call entity in receipt, got {:?}",- entity.entity_type- )));- }- let call_id = Uuid::parse_str(&entity.entity_id)- .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;-+ let mut record = authorized_call_record(&self.repo, &receipt).await?;let user_id = receipt.get_authenticated_user().map_err(|_| CallError::Auth)?;- let mut record = self- .repo- .get_call_record_by_call_id(&call_id)- .await- .map_err(|e| CallError::Internal(e.into()))?- .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;-- record.user_access_level = match receipt.entity_permission() {- EntityPermission::AccessLevel { access_level } => Some(*access_level),- _ => None,- };-if let Some(recording_key) = &record.recording_key {record.recording_url = self.recording_storage@@ -1537,20 +1534,11 @@ impl<.ok();}- record.channel_name = match record.channel_id {- Some(channel_id) => self- .repo- .resolve_channel_name(&channel_id, user_id.copied())- .await- .map_err(|e| CallError::Internal(e.into()))?,- None => None,- };-// Only active calls keep decline rows; archived calls drop them with// the call, and an inactive record already resolves as ended.record.viewer_has_declined = if record.is_active {self.repo- .has_declined(&call_id, user_id.as_ref())+ .has_declined(&record.call_id, user_id.as_ref()).await.map_err(|e| CallError::Internal(e.into()))?} else {@@ -2401,9 +2389,52 @@ impl CallSummarizer for NoopCallSummarizer {}}-/// Lightweight implementation of [`CallRecordQueryService`] for read-only-/// call record queries. Unlike [`CallServiceImpl`], this only requires a-/// repository — no RTC client, notifications, or entity access.+/// The record a call receipt authorizes, at the receipt's access level, with+/// its channel named as the receipt's user sees it.+async fn authorized_call_record<R: CallRepository>(+ repo: &R,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+) -> Result<CallRecord, CallError> {+ let entity = receipt.entity();+ if entity.entity_type != EntityType::Call {+ return Err(CallError::Internal(anyhow::anyhow!(+ "expected Call entity in receipt, got {:?}",+ entity.entity_type+ )));+ }+ let call_id = Uuid::parse_str(&entity.entity_id)+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;++ let user_id = receipt+ .get_authenticated_user()+ .map_err(|_| CallError::Auth)?;++ let mut record = repo+ .get_call_record_by_call_id(&call_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?+ .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;++ record.user_access_level = match receipt.entity_permission() {+ EntityPermission::AccessLevel { access_level } => Some(*access_level),+ _ => None,+ };++ record.channel_name = match record.channel_id {+ Some(channel_id) => repo+ .resolve_channel_name(&channel_id, user_id.copied())+ .await+ .map_err(|e| CallError::Internal(e.into()))?,+ None => None,+ };++ Ok(record)+}++/// Lightweight implementation of [`CallRecordQueryService`] and+/// [`CallRecordReader`] for read-only call record queries. Unlike+/// [`CallServiceImpl`], this only requires a repository — no RTC client,+/// notifications, or entity access.pub struct CallRecordQueryServiceImpl<R: CallRepository> {repo: R,}@@ -2436,3 +2467,13 @@ impl<R: CallRepository> CallRecordQueryService for CallRecordQueryServiceImpl<R>.map_err(|e| CallError::Internal(e.into()))}}++impl<R: CallRepository> CallRecordReader for CallRecordQueryServiceImpl<R> {+ #[tracing::instrument(err, skip(self))]+ async fn get_call_record(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<CallRecord, CallError> {+ authorized_call_record(&self.repo, &receipt).await+ }+}diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rsindex d29a7f7a6a..f679c841a2 100644--- a/crates/call/src/domain/service/test.rs+++ b/crates/call/src/domain/service/test.rs@@ -6,7 +6,9 @@ use std::time::Duration;use chrono::{DateTime, Utc};use connection::domain::models::{ConnectionError, InvalidationEvent};use connection::domain::ports::ConnectionService;-use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, EntityType};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessReceipt, EntityType, ViewAccessLevel,+};use entity_access::domain::ports::NoOpEntityAccessService;use entity_mutation::{DeleteEntityPermanently, UpdateEntitySharePolicy};use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};@@ -932,6 +934,7 @@ const ARCHIVED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_7const ARCHIVED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x4f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a91);const ARCHIVED_EVENT_ROOM_NAME: &str = "archived-event-room";const ARCHIVED_EVENT_CREATOR: &str = "macro|[email protected]";+const ARCHIVED_EVENT_JOINER: &str = "macro|[email protected]";const ARCHIVED_EVENT_PARTICIPANT: &str = "[email protected]";const RECORDING_READY_EGRESS_ID: &str = "recording-ready-egress";const RECORDING_READY_FILE_URL: &str =@@ -963,7 +966,7 @@ fn active_call_for_archived_event(created_by: &str, egress_id: Option<&str>) ->fn archived_call_for_event(created_by: &str,- participant_count: usize,+ participants: &[&str],has_recording: bool,) -> ArchivedCall {ArchivedCall {@@ -974,7 +977,7 @@ fn archived_call_for_event(ended_at: archived_event_ended_at(),duration_ms: 183_000,has_recording,- participant_count,+ participants: participants.iter().map(ToString::to_string).collect(),}}@@ -1067,6 +1070,7 @@ fn assert_archived_event(event_broker: &RecordingEventBroker,archive_reason: &str,participant_count: usize,+ participants: &[&str],has_recording: bool,) {let events = event_broker.events();@@ -1099,6 +1103,7 @@ fn assert_archived_event("ended_at": "2026-07-27T18:04:05Z","duration_ms": 183_000,"participant_count": participant_count,+ "participants": participants,"has_recording": has_recording,"archive_reason": archive_reason,},@@ -1109,7 +1114,11 @@ fn assert_archived_event(#[tokio::test]async fn participant_left_publishes_last_participant_archived_event() {let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);- let archived_call = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 4, false);+ let archived_call = archived_call_for_event(+ ARCHIVED_EVENT_CREATOR,+ &[ARCHIVED_EVENT_CREATOR, ARCHIVED_EVENT_JOINER],+ false,+ );let mut repo = MockCallRepository::new();repo.expect_get_call_by_room_name().times(1)@@ -1156,7 +1165,13 @@ async fn participant_left_publishes_last_participant_archived_event() {.await.expect("participant-left webhook succeeds");- assert_archived_event(&event_broker, "last_participant_left", 4, false);+ assert_archived_event(+ &event_broker,+ "last_participant_left",+ 2,+ &[ARCHIVED_EVENT_CREATOR, ARCHIVED_EVENT_JOINER],+ false,+ );}#[tokio::test]@@ -1165,7 +1180,15 @@ async fn room_finished_publishes_room_finished_archived_event() {"macro|[email protected]",Some("archived-event-egress"),);- let archived_call = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 3, true);+ let archived_call = archived_call_for_event(+ ARCHIVED_EVENT_CREATOR,+ &[+ ARCHIVED_EVENT_CREATOR,+ ARCHIVED_EVENT_JOINER,+ "malformed-participant",+ ],+ true,+ );let mut repo = MockCallRepository::new();repo.expect_get_call_by_room_name().times(1)@@ -1189,7 +1212,14 @@ async fn room_finished_publishes_room_finished_archived_event() {.await.expect("room-finished webhook succeeds");- assert_archived_event(&event_broker, "room_finished", 3, true);+ // A malformed stored participant still counts, but is left off the list.+ assert_archived_event(+ &event_broker,+ "room_finished",+ 3,+ &[ARCHIVED_EVENT_CREATOR, ARCHIVED_EVENT_JOINER],+ true,+ );}#[tokio::test]@@ -1219,7 +1249,8 @@ async fn failed_archive_does_not_publish_archived_event() {#[tokio::test]async fn malformed_archived_creator_skips_event_without_undoing_archival() {let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);- let archived_call = archived_call_for_event("malformed-user-id", 1, false);+ let archived_call =+ archived_call_for_event("malformed-user-id", &[ARCHIVED_EVENT_CREATOR], false);let mut repo = MockCallRepository::new();repo.expect_get_call_by_room_name().times(1)@@ -4046,7 +4077,8 @@ async fn mixed_call_archives_only_after_both_users_and_guests_leave() {let mut active = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);active.channel_id = None;let second_leg = active.clone();- let mut archived = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 1, true);+ let mut archived =+ archived_call_for_event(ARCHIVED_EVENT_CREATOR, &[ARCHIVED_EVENT_CREATOR], true);archived.channel_id = None;let guest_id = GuestId::generate();@@ -4147,7 +4179,8 @@ async fn last_guest_leaving_archives_call_and_stops_recording() {let token = meeting.share_token.clone();let mut active = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, Some("recording"));active.channel_id = None;- let mut archived = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 1, true);+ let mut archived =+ archived_call_for_event(ARCHIVED_EVENT_CREATOR, &[ARCHIVED_EVENT_CREATOR], true);archived.channel_id = None;let guest_id = GuestId::generate();let identity = guest_id.to_string();@@ -4315,3 +4348,56 @@ async fn call_record_query_service_reads_the_people_on_a_call() {people);}++fn reader_receipt() -> EntityAccessReceipt<ViewAccessLevel> {+ EntityAccessReceipt::dangerously_assert_authenticated_user(+ user("[email protected]"),+ &MUTATED_EVENT_CALL_ID.to_string(),+ EntityType::Call,+ )+}++#[tokio::test]+async fn call_record_reader_names_the_channel_as_the_reader_sees_it() {+ use crate::domain::ports::CallRecordReader;++ let record = call_record_for_mutation();+ let mut repo = MockCallRepository::new();+ repo.expect_get_call_record_by_call_id()+ .times(1)+ .return_once(move |call_id| {+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);+ Box::pin(async move { Ok(Some(record)) })+ });+ repo.expect_resolve_channel_name()+ .times(1)+ .returning(|channel_id, user_id| {+ assert_eq!(*channel_id, MUTATED_EVENT_CHANNEL_ID);+ assert_eq!(user_id.as_ref(), "macro|[email protected]");+ Box::pin(async { Ok(Some("eng".to_string())) })+ });++ let record = super::CallRecordQueryServiceImpl::new(repo)+ .get_call_record(reader_receipt())+ .await+ .unwrap();+ assert_eq!(record.call_id, MUTATED_EVENT_CALL_ID);+ assert_eq!(record.channel_name.as_deref(), Some("eng"));+}++#[tokio::test]+async fn call_record_reader_reports_a_deleted_record_as_not_found() {+ use crate::domain::ports::CallRecordReader;++ let mut repo = MockCallRepository::new();+ repo.expect_get_call_record_by_call_id()+ .times(1)+ .return_once(|_| Box::pin(async { Ok(None) }));++ assert!(matches!(+ super::CallRecordQueryServiceImpl::new(repo)+ .get_call_record(reader_receipt())+ .await,+ Err(CallError::NotFound(_))+ ));+}diff --git a/crates/call/src/domain/service/test/meeting_startup.rs b/crates/call/src/domain/service/test/meeting_startup.rsindex 08b5b7e867..e7af2d04de 100644--- a/crates/call/src/domain/service/test/meeting_startup.rs+++ b/crates/call/src/domain/service/test/meeting_startup.rs@@ -152,7 +152,8 @@ async fn cancelling_an_unowned_or_claimed_preparation_never_deletes_media() {#[tokio::test]async fn previous_empty_call_cleanup_does_not_wait_for_media_teardown() {let active = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, Some("recording"));- let mut archived = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 1, true);+ let mut archived =+ archived_call_for_event(ARCHIVED_EVENT_CREATOR, &[ARCHIVED_EVENT_CREATOR], true);archived.channel_id = None;let mut repo = MockCallRepository::new();repo.expect_find_active_call_for_user()diff --git a/crates/call/src/outbound/pg_call_repo/lifecycle.rs b/crates/call/src/outbound/pg_call_repo/lifecycle.rsindex 12b6c6128d..8ea261fa1c 100644--- a/crates/call/src/outbound/pg_call_repo/lifecycle.rs+++ b/crates/call/src/outbound/pg_call_repo/lifecycle.rs@@ -87,19 +87,19 @@ impl PgCallRepo {// Copy all lifetime-distinct participants (including soft-deleted) to// call_record_participants. Each inserted row represents one participant.- let participant_count = sqlx::query!(+ let participants = sqlx::query_scalar!(r#"INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)SELECT $1, user_id, joined_at, left_atFROM call_participantsWHERE call_id = $2+ RETURNING user_id"#,call_id,call_id,)- .execute(tx.as_mut())- .await?- .rows_affected() as usize;+ .fetch_all(tx.as_mut())+ .await?;// Copy guests the same way; the archived rows keep the guest ids so// transcript speaker ids remain resolvable to display names.@@ -214,7 +214,7 @@ impl PgCallRepo {ended_at,duration_ms,has_recording,- participant_count,+ participants,};tx.commit().await?;diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rsindex fbb8af3de1..7a8be5d39c 100644--- a/crates/call/src/outbound/pg_call_repo/test.rs+++ b/crates/call/src/outbound/pg_call_repo/test.rs@@ -661,7 +661,7 @@ async fn archive_call_creates_record_and_deletes_ephemeral(assert_eq!(archived.ended_at, record.ended_at);assert_eq!(archived.duration_ms, record.duration_ms);assert!(archived.has_recording);- assert_eq!(archived.participant_count, 2);+ assert_eq!(archived.participants.len(), 2);assert_eq!(record.channel_id, archived.channel_id);assert_eq!(record.created_by, archived.created_by);@@ -681,7 +681,11 @@ async fn archive_call_creates_record_and_deletes_ephemeral(.fetch_all(&pool).await?;- assert_eq!(participants.len(), archived.participant_count);+ let mut returned = archived.participants.clone();+ returned.sort();+ let mut stored = participants.clone();+ stored.sort();+ assert_eq!(returned, stored);assert!(participants.contains(&USER_A.to_string()));assert!(participants.contains(&USER_B.to_string()));Ok(())@@ -709,7 +713,9 @@ async fn archive_call_preserves_soft_deleted_participants(// Archive the call.let archived = repo.archive_call(&CALL1).await?;- assert_eq!(archived.participant_count, 2);+ assert_eq!(archived.participants.len(), 2);+ assert!(archived.participants.contains(&USER_A.to_string()));+ assert!(archived.participants.contains(&USER_B.to_string()));assert!(!archived.has_recording);// call_record_participants should have both participants with left_at set.@@ -725,7 +731,7 @@ async fn archive_call_preserves_soft_deleted_participants(.fetch_all(&pool).await?;- assert_eq!(rows.len(), archived.participant_count);+ assert_eq!(rows.len(), archived.participants.len());let user_ids: Vec<&str> = rows.iter().map(|r| r.user_id.as_str()).collect();assert!(user_ids.contains(&USER_A.as_ref()));assert!(user_ids.contains(&USER_B.as_ref()));diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex 0cf82c1c5a..161b334d51 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -641,6 +641,8 @@ fn scheduled_actions_hang_off_the_authenticated_user() {"CHANNEL_MENTIONED","CHANNEL_MESSAGE_PATCHED","CHANNEL_MESSAGE_ATTACHMENT_CREATED",+ "CALL_STARTED",+ "CALL_ENDED",] {assert_sdl_line(&sdl, value);}diff --git a/crates/crm/src/inbound/call_archived/test.rs b/crates/crm/src/inbound/call_archived/test.rsindex 250b111d75..846f9880ed 100644--- a/crates/crm/src/inbound/call_archived/test.rs+++ b/crates/crm/src/inbound/call_archived/test.rs@@ -109,6 +109,7 @@ fn archived() -> CallTopicEvent {ended_at: Utc::now(),duration_ms: Some(1_000),participant_count: 1,+ participants: vec![MacroUserIdStr::try_from_email("[email protected]").unwrap()],has_recording: false,archive_reason: CallArchiveReason::LastParticipantLeft,})diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rsindex 4637f19412..d65e40df83 100644--- a/crates/graphql_scheduled_action/src/objects.rs+++ b/crates/graphql_scheduled_action/src/objects.rs@@ -123,6 +123,10 @@ pub(crate) enum GraphqlScheduledActionEventName {ChannelMessagePatched,/// A channel message attachment was created.ChannelMessageAttachmentCreated,+ /// A call the routine's owner started began.+ CallStarted,+ /// A call the routine's owner joined ended.+ CallEnded,}impl From<EventName> for GraphqlScheduledActionEventName {@@ -141,6 +145,8 @@ impl From<EventName> for GraphqlScheduledActionEventName {EventName::ChannelMentioned => Self::ChannelMentioned,EventName::ChannelMessagePatched => Self::ChannelMessagePatched,EventName::ChannelMessageAttachmentCreated => Self::ChannelMessageAttachmentCreated,+ EventName::CallStarted => Self::CallStarted,+ EventName::CallEnded => Self::CallEnded,}}}diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rsindex 2c1521f980..352a1d9d0f 100644--- a/crates/trigger_context/src/lib.rs+++ b/crates/trigger_context/src/lib.rs@@ -485,6 +485,80 @@ pub enum RoutineEvent {/// Its id.entity_id: String,},+ /// A call the routine's owner started began.+ CallStarted {+ /// The call as it stands at the start.+ call: CallStartedSnapshot,+ },+ /// A call the routine's owner joined ended.+ CallEnded {+ /// The call.+ call: CallSnapshot,+ },+}++/// A call that just started, read under the routine owner's access.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallStartedSnapshot {+ /// Call id.+ pub id: Uuid,+ /// The call's name, when it has one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// The channel the call is in; absent for meetings outside one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Uuid>,+ /// That channel's name.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_name: Option<String>,+ /// When it started.+ pub started_at: DateTime<Utc>,+ /// Who started it.+ pub started_by: ContextPerson,+ /// Everyone who has joined so far, people and guests.+ pub participants: Vec<ContextPerson>,+}++/// An ended call, read under the routine owner's access.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallSnapshot {+ /// Call id.+ pub id: Uuid,+ /// The call's name, when it has one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// The channel the call was held in; absent for meetings outside one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Uuid>,+ /// That channel's name.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_name: Option<String>,+ /// When it started.+ pub started_at: DateTime<Utc>,+ /// When it ended.+ pub ended_at: DateTime<Utc>,+ /// Everyone who joined, people and guests.+ pub participants: Vec<ContextPerson>,+ /// AI summary of the call, once one has been written.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub summary: Option<String>,+ /// What was said, oldest first.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub transcript: Vec<TranscriptLine>,+ /// Whether the end of the transcript was left out.+ pub transcript_omitted: bool,+}++/// One stretch of speech in a call transcript.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct TranscriptLine {+ /// Who spoke, as a reader would name them. Attributed by audio track, so+ /// people sharing a device share a speaker.+ pub speaker: String,+ /// What they said.+ pub text: String,+ /// When they started speaking.+ pub at: DateTime<Utc>,}/// A document, read under the routine owner's access.diff --git a/crates/trigger_context/src/test.rs b/crates/trigger_context/src/test.rsindex ea01c8813e..c86a38372a 100644--- a/crates/trigger_context/src/test.rs+++ b/crates/trigger_context/src/test.rs@@ -89,6 +89,106 @@ fn a_channel_follow_up_has_a_stable_wire_shape() {);}+#[test]+fn a_started_call_has_a_stable_wire_shape() {+ let event = RoutineEvent::CallStarted {+ call: CallStartedSnapshot {+ id: Uuid::parse_str("00000000-0000-0000-0000-0000000000ca").unwrap(),+ title: Some("Standup".to_owned()),+ channel_id: Some(Uuid::parse_str("00000000-0000-0000-0000-0000000000c1").unwrap()),+ channel_name: Some("eng".to_owned()),+ started_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 0, 0).unwrap(),+ started_by: ContextPerson {+ id: "macro|[email protected]".to_owned(),+ name: "[email protected]".to_owned(),+ email: Some("[email protected]".to_owned()),+ },+ participants: vec![ContextPerson {+ id: "macro|[email protected]".to_owned(),+ name: "[email protected]".to_owned(),+ email: Some("[email protected]".to_owned()),+ }],+ },+ };++ let wire = json!({+ "event": "call_started",+ "call": {+ "id": "00000000-0000-0000-0000-0000000000ca",+ "title": "Standup",+ "channel_id": "00000000-0000-0000-0000-0000000000c1",+ "channel_name": "eng",+ "started_at": "2026-10-08T14:00:00Z",+ "started_by": {+ "id": "macro|[email protected]",+ "name": "[email protected]",+ "email": "[email protected]"+ },+ "participants": [+ ]+ }+ });++ assert_eq!(serde_json::to_value(&event).unwrap(), wire);+ assert_eq!(serde_json::from_value::<RoutineEvent>(wire).unwrap(), event);+}++#[test]+fn an_ended_call_has_a_stable_wire_shape() {+ let event = RoutineEvent::CallEnded {+ call: CallSnapshot {+ id: Uuid::parse_str("00000000-0000-0000-0000-0000000000ca").unwrap(),+ title: None,+ channel_id: Some(Uuid::parse_str("00000000-0000-0000-0000-0000000000c1").unwrap()),+ channel_name: Some("eng".to_owned()),+ started_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 0, 0).unwrap(),+ ended_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 30, 0).unwrap(),+ participants: vec![+ ContextPerson {+ id: "macro|[email protected]".to_owned(),+ name: "[email protected]".to_owned(),+ email: Some("[email protected]".to_owned()),+ },+ ContextPerson {+ id: "guest_1".to_owned(),+ name: "Sam (Acme)".to_owned(),+ email: None,+ },+ ],+ summary: None,+ transcript: vec![TranscriptLine {+ speaker: "Sam (Acme)".to_owned(),+ text: "Can we ship Friday?".to_owned(),+ at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 1, 0).unwrap(),+ }],+ transcript_omitted: true,+ },+ };++ let wire = json!({+ "event": "call_ended",+ "call": {+ "id": "00000000-0000-0000-0000-0000000000ca",+ "channel_id": "00000000-0000-0000-0000-0000000000c1",+ "channel_name": "eng",+ "started_at": "2026-10-08T14:00:00Z",+ "ended_at": "2026-10-08T14:30:00Z",+ "participants": [+ {"id": "guest_1", "name": "Sam (Acme)"}+ ],+ "transcript": [+ {"speaker": "Sam (Acme)", "text": "Can we ship Friday?", "at": "2026-10-08T14:01:00Z"}+ ],+ "transcript_omitted": true+ }+ });++ assert_eq!(serde_json::to_value(&event).unwrap(), wire);+ assert_eq!(serde_json::from_value::<RoutineEvent>(wire).unwrap(), event);+}+#[test]fn a_task_assignment_has_a_stable_wire_shape() {let context = TriggerContext::TaskAssigned(TaskAssignedContext {diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 2d1f9ad56c..ea29bd26df 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -653,11 +653,14 @@ The event menu groups Macro activity triggers by surface:- **Documents:** **Document created** and **Document deleted**. Tasks are separate.- **Tasks:** **Task created**, **Status changed**, **Priority changed**, and **Any property changed**.- **Email:** **New email received** in the routine owner's inbox, excluding spam, trash, drafts, and historical imports.+- **Calls:** **Call started**, for calls the routine owner starts (receives the call and who has joined so far); and **Call ended**, for channel calls and meetings the owner joined (receives participants and transcript, cut short for long calls).For messages, mentions, deletion, and task changes, choose specific accessiblechannels/documents/tasks or any accessible item in the same panel. Creation-triggers cover newly created accessible items; email covers the owner's inbox.-Mentions match only @ mentions of the routine owner. **Any property changed**+triggers cover newly created accessible items; email covers the owner's inbox;+**Call started** shows **Calls you start** and **Call ended** shows **Calls you+join** — neither has an item picker. Calls the owner did not start never trigger+**Call started**; calls they did not join never trigger **Call ended**. Mentions match only @ mentions of the routine owner. **Any property changed**also includes status and priority; overlapping selectors start only one run forthe same event. These are Macro events, not incoming HTTP webhooks. Bot-authoredor delegated changes do not retrigger routines. Saved legacy selectors remain@@ -666,7 +669,7 @@ editable but are no longer offered in the new-trigger menu.When `enable-routine-conditions` is on, every activity trigger panel has an**Only run if** box for an optional yes/no question about each event, such as**Is this email an invoice or a receipt?** Before a run starts, the event's-content (the email, channel message, document, or task, read as the routine+content (the email, channel message, document, task, or call, read as the routineowner) is checked against it, and events answered no are skipped. The chipshows the question after **· if**. Saving a condition fails with "triggerconditions are not enabled" while the scheduled-action service has nodiff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.tsindex 660dbbaa04..12ca7c4702 100644--- a/packages/lexical-core/tests/agent-trigger-context.test.ts+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts@@ -548,6 +548,184 @@ describe('composeAgentContextPrompt with a trigger', () => {);});+ it('renders a routine fired by a started call with who started it', () => {+ const markdown = composeAgentContextPrompt({+ promptMarkdown: 'Prepare notes.',+ trigger: {+ kind: 'routine',+ routine_id: 'r-4',+ name: 'Call prep',+ owner: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ instructions: 'Draft talking points for this call.',+ triggers: [{ type: 'events', events: ['call.started'] }],+ firing: {+ type: 'event',+ event: {+ event: 'call_started',+ call: {+ id: 'call-0',+ title: 'Standup',+ channel_id: 'c1',+ channel_name: 'eng',+ started_at: '2026-10-08T14:00:00Z',+ started_by: {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ participants: [+ {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ ],+ },+ },+ },+ },+ });++ expect(hiddenContext(markdown)).toBe(+ [+ '<trigger kind="routine">',+ ' <note>The routine Call prep, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',+ ' <routine id="r-4" name="Call prep" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',+ ' <instructions>Draft talking points for this call.</instructions>',+ ' <triggers>',+ ' <events names="call.started"/>',+ ' </triggers>',+ ' <event type="call_started">',+ ' <call id="call-0" title="Standup" channel="eng" channel_id="c1" started_at="2026-10-08T14:00:00Z">',+ ' <participants>',+ ' <participant name="[email protected]" email="[email protected]" id="macro|[email protected]"/>',+ ' </participants>',+ ' </call>',+ ' </event>',+ '</trigger>',+ ].join('\n')+ );+ });++ it('renders a routine fired by an ended call with its people and a cut transcript', () => {+ const markdown = composeAgentContextPrompt({+ promptMarkdown: 'Post the recap.',+ trigger: {+ kind: 'routine',+ routine_id: 'r-5',+ name: 'Call recap',+ owner: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ instructions: 'Post a recap with action items.',+ triggers: [{ type: 'events', events: ['call.ended'] }],+ firing: {+ type: 'event',+ event: {+ event: 'call_ended',+ call: {+ id: 'call-1',+ title: 'Acme renewal',+ channel_id: 'c1',+ channel_name: 'sales',+ started_at: '2026-10-08T14:00:00Z',+ ended_at: '2026-10-08T14:30:00Z',+ participants: [+ {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ { id: 'g-1', name: 'Sam (Acme)' },+ ],+ transcript: [+ {+ speaker: 'Sam (Acme)',+ text: 'We renew if SSO ships.',+ at: '2026-10-08T14:01:00Z',+ },+ ],+ transcript_omitted: true,+ },+ },+ },+ },+ });++ expect(hiddenContext(markdown)).toBe(+ [+ '<trigger kind="routine">',+ ' <note>The routine Call recap, owned by Julia, fired. The prompt is what the routine asks you to do.</note>',+ ' <routine id="r-5" name="Call recap" owner="Julia" owner_email="[email protected]" owner_id="macro|[email protected]"/>',+ ' <instructions>Post a recap with action items.</instructions>',+ ' <triggers>',+ ' <events names="call.ended"/>',+ ' </triggers>',+ ' <event type="call_ended">',+ ' <call id="call-1" title="Acme renewal" channel="sales" channel_id="c1" started_at="2026-10-08T14:00:00Z" ended_at="2026-10-08T14:30:00Z">',+ ' <participants>',+ ' <participant name="[email protected]" email="[email protected]" id="macro|[email protected]"/>',+ ' <participant name="Sam (Acme)" id="g-1"/>',+ ' </participants>',+ ' <transcript omitted="true">',+ ' <note>Speakers are named by audio track, so people sharing a device share a speaker.</note>',+ ' <line speaker="Sam (Acme)" at="2026-10-08T14:01:00Z">We renew if SSO ships.</line>',+ ' <note>The rest of the transcript is not shown. ReadCallRecord with this call id returns all of it.</note>',+ ' </transcript>',+ ' </call>',+ ' </event>',+ '</trigger>',+ ].join('\n')+ );+ });++ it('says so when an ended call has no transcript', () => {+ const markdown = composeAgentContextPrompt({+ promptMarkdown: 'Post the recap.',+ trigger: {+ kind: 'routine',+ routine_id: 'r-6',+ name: 'Call recap',+ owner: { id: 'macro|[email protected]', name: 'Julia' },+ instructions: 'Post a recap.',+ triggers: [{ type: 'events', events: ['call.ended'] }],+ firing: {+ type: 'event',+ event: {+ event: 'call_ended',+ call: {+ id: 'call-2',+ started_at: '2026-10-08T14:00:00Z',+ ended_at: '2026-10-08T14:05:00Z',+ participants: [],+ summary: 'A short check-in.',+ transcript_omitted: false,+ },+ },+ },+ },+ });++ expect(hiddenContext(markdown)).toContain(+ [+ ' <call id="call-2" started_at="2026-10-08T14:00:00Z" ended_at="2026-10-08T14:05:00Z">',+ ' <participants/>',+ ' <summary>A short check-in.</summary>',+ ' <transcript>',+ ' <note>Nothing was transcribed.</note>',+ ' </transcript>',+ ' </call>',+ ].join('\n')+ );+ });+it('refuses a trigger beside the legacy conversation fields', () => {expect(() =>composeAgentContextPrompt({diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.tsindex e8cfe162a6..91bf91f588 100644--- a/packages/lexical-core/utils/agent-context.ts+++ b/packages/lexical-core/utils/agent-context.ts@@ -220,7 +220,44 @@ export type RoutineEvent =discussion: DiscussionContext;entity_type: string;entity_id: string;- };+ }+ | { event: 'call_started'; call: CallStartedSnapshot }+ | { event: 'call_ended'; call: CallSnapshot };++/** A call that just started, read under the routine owner's access. */+export type CallStartedSnapshot = {+ id: string;+ title?: string;+ /** Absent for meetings outside a channel. */+ channel_id?: string;+ channel_name?: string;+ started_at: string;+ started_by: ContextPerson;+ /** People and guests who have joined so far. */+ participants: ContextPerson[];+};++/** An ended call, read under the routine owner's access. */+export type CallSnapshot = {+ id: string;+ title?: string;+ /** Absent for meetings outside a channel. */+ channel_id?: string;+ channel_name?: string;+ started_at: string;+ ended_at: string;+ /** People and guests who joined. */+ participants: ContextPerson[];+ /** Absent until an AI summary has been written. */+ summary?: string;+ /** Oldest first; absent when empty. */+ transcript?: TranscriptLine[];+ /** Whether the end of the transcript was left out. */+ transcript_omitted: boolean;+};++/** One stretch of speech in a call transcript. */+export type TranscriptLine = { speaker: string; text: string; at: string };/** A document, read under the routine owner's access. */export type DocumentSnapshot = {@@ -963,6 +1000,75 @@ function documentNode(document: DocumentSnapshot): FxpNode {);}+function transcriptNode(call: CallSnapshot): FxpNode {+ const lines = call.transcript ?? [];+ return el(+ 'transcript',+ [+ note(+ lines.length === 0 && !call.transcript_omitted+ ? 'Nothing was transcribed.'+ : 'Speakers are named by audio track, so people sharing a device share a speaker.'+ ),+ ...lines.map((line) =>+ el('line', [text(line.text)], { speaker: line.speaker, at: line.at })+ ),+ ...(call.transcript_omitted+ ? [+ note(+ 'The rest of the transcript is not shown. ReadCallRecord with this call id returns all of it.'+ ),+ ]+ : []),+ ],+ present({ omitted: call.transcript_omitted ? 'true' : undefined })+ );+}++function callStartedNode(call: CallStartedSnapshot): FxpNode {+ return el(+ 'call',+ [+ personNode('started_by', call.started_by),+ el(+ 'participants',+ call.participants.map((person) => personNode('participant', person))+ ),+ ],+ present({+ id: call.id,+ title: call.title,+ channel: call.channel_name,+ channel_id: call.channel_id,+ started_at: call.started_at,+ })+ );+}++function callNode(call: CallSnapshot): FxpNode {+ return el(+ 'call',+ [+ el(+ 'participants',+ call.participants.map((person) => personNode('participant', person))+ ),+ ...(call.summary === undefined+ ? []+ : [el('summary', [text(call.summary)])]),+ transcriptNode(call),+ ],+ present({+ id: call.id,+ title: call.title,+ channel: call.channel_name,+ channel_id: call.channel_id,+ started_at: call.started_at,+ ended_at: call.ended_at,+ })+ );+}+function mentionedNode(discussion: DiscussionContext): FxpNode {return el('trigger',@@ -1140,6 +1246,8 @@ function routineEventChildren(event: RoutineEvent): FxpNode[] {discussionNode(discussion, routineDiscussion),])+ .with({ event: 'call_started' }, ({ call }) => [callStartedNode(call)])+ .with({ event: 'call_ended' }, ({ call }) => [callNode(call)]).exhaustive();}diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 3d479113b9..ecf7d4947e 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -147,7 +147,7 @@ export type EventFilters = Array<EventFilter>;* Closed allowlist: unknown names, deletions and ambiguous attribution are not* selectors. Adding a broker variant does not automatically enable routines.*/-export type EventName = 'document.created' | 'document.updated' | 'document.deleted' | 'task.created' | 'task.status_changed' | 'task.priority_changed' | 'task.property_changed' | 'email.message_received' | 'channel.created' | 'channel.message_posted' | 'channel.mentioned' | 'channel.message_patched' | 'channel.message_attachment_created';+export type EventName = 'document.created' | 'document.updated' | 'document.deleted' | 'task.created' | 'task.status_changed' | 'task.priority_changed' | 'task.property_changed' | 'email.message_received' | 'channel.created' | 'channel.message_posted' | 'channel.mentioned' | 'channel.message_patched' | 'channel.message_attachment_created' | 'call.started' | 'call.ended';/*** Transcript resource created by a run. Never infer this from current task configuration.diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex 373779fff3..970f93d88b 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -902,7 +902,9 @@"channel.message_posted","channel.mentioned","channel.message_patched",- "channel.message_attachment_created"+ "channel.message_attachment_created",+ "call.started",+ "call.ended"]},"ExecutionResource": {diff --git a/services/bots/ROUTINES.md b/services/bots/ROUTINES.mdindex 30b5389a54..eac555fd03 100644--- a/services/bots/ROUTINES.md+++ b/services/bots/ROUTINES.md@@ -13,6 +13,8 @@ Ideas to configure through **Agents → Routines → Create Routine**:| Keep the team in sync | Referenced project channels | Friday, 16:00 | Draft progress report and next priorities || Catch work that slipped | Open tasks and project conversations | Monday/Wednesday/Friday, 15:00 | Prioritized follow-up list || Walk into meetings prepared | Calendar and linked Macro context | Weekdays, 08:30 | Objectives, recent decisions, open questions |+| Prep before the call settles | The call and who has joined so far | **Call started** trigger | Talking points, open questions, linked context |+| Follow up after calls | The call's transcript and participants | **Call ended** trigger | Recap, decisions, owners for action items || Spot revenue signals | Stripe bot channel messages | Weekdays, 09:30 | Payment events and cancellation follow-ups || Follow up on incidents | Anthropic status bot posts | Daily, 10:00 | Active incidents, latest updates, observed impact || Review what shipped | An agent's GitHub connection | Weekdays, 16:30 | Merges, releases, failed checks, waiting reviews |diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.tsindex ce94da5fdc..7f23f13235 100644--- a/services/lexical-service/src/endpoints/agent-context.ts+++ b/services/lexical-service/src/endpoints/agent-context.ts@@ -214,6 +214,37 @@ const emailSnapshot = z.object({body: z.string(),});+const callStartedSnapshot = z.object({+ id: z.string().min(1),+ title: z.string().optional(),+ channel_id: z.string().min(1).optional(),+ channel_name: z.string().optional(),+ started_at: z.string().min(1),+ started_by: triggerPerson,+ participants: z.array(triggerPerson),+});++const callSnapshot = z.object({+ id: z.string().min(1),+ title: z.string().optional(),+ channel_id: z.string().min(1).optional(),+ channel_name: z.string().optional(),+ started_at: z.string().min(1),+ ended_at: z.string().min(1),+ participants: z.array(triggerPerson),+ summary: z.string().optional(),+ transcript: z+ .array(+ z.object({+ speaker: z.string(),+ text: z.string(),+ at: z.string().min(1),+ })+ )+ .optional(),+ transcript_omitted: z.boolean(),+});+const routineEvent = z.discriminatedUnion('event', [z.object({event: z.literal('document_created'),@@ -256,6 +287,8 @@ const routineEvent = z.discriminatedUnion('event', [entity_type: z.string().min(1),entity_id: z.string().min(1),}),+ z.object({ event: z.literal('call_started'), call: callStartedSnapshot }),+ z.object({ event: z.literal('call_ended'), call: callSnapshot }),]);const routineFiring = z.discriminatedUnion('type', [diff --git a/services/lexical-service/test/agent-context.test.ts b/services/lexical-service/test/agent-context.test.tsindex 28c2e629ed..e99fe39795 100644--- a/services/lexical-service/test/agent-context.test.ts+++ b/services/lexical-service/test/agent-context.test.ts@@ -85,6 +85,88 @@ const dispatchedWire = {from_bot: null,};+const callStartedRoutineWire = {+ kind: 'routine',+ routine_id: '00000000-0000-0000-0000-0000000000f0',+ name: 'Call prep',+ owner: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ instructions: 'Draft talking points for this call.',+ triggers: [{ type: 'events', events: ['call.started'] }],+ firing: {+ type: 'event',+ // The `call` is the wire example in crates/trigger_context/src/test.rs.+ event: {+ event: 'call_started',+ call: {+ id: '00000000-0000-0000-0000-0000000000ca',+ title: 'Standup',+ channel_id: '00000000-0000-0000-0000-0000000000c1',+ channel_name: 'eng',+ started_at: '2026-10-08T14:00:00Z',+ started_by: {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ participants: [+ {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ ],+ },+ },+ },+};++const callEndedRoutineWire = {+ kind: 'routine',+ routine_id: '00000000-0000-0000-0000-0000000000f1',+ name: 'Call recap',+ owner: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ instructions: 'Post a recap with action items.',+ triggers: [{ type: 'events', events: ['call.ended'] }],+ firing: {+ type: 'event',+ // The `call` is the wire example in crates/trigger_context/src/test.rs.+ event: {+ event: 'call_ended',+ call: {+ id: '00000000-0000-0000-0000-0000000000ca',+ channel_id: '00000000-0000-0000-0000-0000000000c1',+ channel_name: 'eng',+ started_at: '2026-10-08T14:00:00Z',+ ended_at: '2026-10-08T14:30:00Z',+ participants: [+ {+ id: 'macro|[email protected]',+ name: '[email protected]',+ email: '[email protected]',+ },+ { id: 'guest_1', name: 'Sam (Acme)' },+ ],+ transcript: [+ {+ speaker: 'Sam (Acme)',+ text: 'Can we ship Friday?',+ at: '2026-10-08T14:01:00Z',+ },+ ],+ transcript_omitted: true,+ },+ },+ },+};+function endpoint() {const app = new Hono();fromHono(app).post('/agent-context', AgentContextEndpoint);@@ -98,7 +180,13 @@ function endpoint() {describe('agent-context request schema', () => {it('accepts each Rust wire example as the trigger, unchanged', () => {- for (const trigger of [followUpWire, taskAssignedWire, dispatchedWire]) {+ for (const trigger of [+ followUpWire,+ taskAssignedWire,+ dispatchedWire,+ callStartedRoutineWire,+ callEndedRoutineWire,+ ]) {const parsed = agentContextRequest.safeParse({promptMarkdown: 'please fix',trigger,@@ -140,7 +228,13 @@ describe('agent-context request schema', () => {describe('POST /agent-context', () => {it('composes a prompt from each Rust wire example', async () => {const post = endpoint();- for (const trigger of [followUpWire, taskAssignedWire, dispatchedWire]) {+ for (const trigger of [+ followUpWire,+ taskAssignedWire,+ dispatchedWire,+ callStartedRoutineWire,+ callEndedRoutineWire,+ ]) {const response = await post({ promptMarkdown: 'please fix', trigger });expect(response.status).toBe(200);const { markdown } = (await response.json()) as { markdown: string };diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex 47af6b0abb..70a74947e9 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -31,6 +31,7 @@ activity = { path = "../../crates/activity", default-features = false }agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", default-features = false }agent_session = { path = "../../crates/agent_session", default-features = false, features = ["admission"] }bot_id = { path = "../../crates/bot_id" }+call = { path = "../../crates/call", default-features = false, features = ["outbound"] }channel_sender = { path = "../../crates/channel_sender" }channels = { path = "../../crates/channels", default-features = false, features = ["outbound"] }crm = { path = "../../crates/crm", default-features = false, features = ["ports"] }diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rsindex 1864223d31..e29d11beb6 100644--- a/services/scheduled_action/src/bins/service.rs+++ b/services/scheduled_action/src/bins/service.rs@@ -303,6 +303,9 @@ fn event_content(Some(properties::PermissionServiceImpl::new(db.clone(), access)),None::<NoTaskNotifications>,),+ call::domain::service::CallRecordQueryServiceImpl::new(+ call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),+ ),lexical_client::LexicalClient::new(config.internal_api_key.to_string(),LexicalServiceUrl::new()?.to_string(),diff --git a/services/scheduled_action/src/domain/event_runs.rs b/services/scheduled_action/src/domain/event_runs.rsindex 2d2398353c..e914abb857 100644--- a/services/scheduled_action/src/domain/event_runs.rs+++ b/services/scheduled_action/src/domain/event_runs.rs@@ -209,6 +209,7 @@ pub enum EventAccessCapability {Document(EntityAccessReceipt<ViewAccessLevel>),Channel(EntityAccessReceipt<ViewOnly>),EmailThread(EntityAccessReceipt<ViewAccessLevel>),+ Call(EntityAccessReceipt<ViewAccessLevel>),}impl EventAccessCapability {@@ -225,6 +226,9 @@ impl EventAccessCapability {(Self::EmailThread(receipt), EventEntityType::EmailThread) => {receipt_matches(receipt, owner, event, EntityType::EmailThread)}+ (Self::Call(receipt), EventEntityType::Call) => {+ receipt_matches(receipt, owner, event, EntityType::Call)+ }_ => false,}}diff --git a/services/scheduled_action/src/domain/event_runs/admission/test.rs b/services/scheduled_action/src/domain/event_runs/admission/test.rsindex 2ac50f3f16..228e136c1b 100644--- a/services/scheduled_action/src/domain/event_runs/admission/test.rs+++ b/services/scheduled_action/src/domain/event_runs/admission/test.rs@@ -126,16 +126,16 @@ async fn denied_and_mismatched_receipts_skip_but_unavailable_access_defers_intak}#[tokio::test]-async fn mentions_and_mail_only_admit_their_recipient_even_when_others_have_access() {+async fn mentions_mail_and_calls_only_admit_their_recipient_even_when_others_have_access() {use crate::domain::event_trigger::{EventPayload, MessageFact};- for is_email in [false, true] {+ for name in [+ "channel.mentioned",+ "email.message_received",+ "call.started",+ "call.ended",+ ] {let owner = user();let mut subscribed = configuration();- let name = if is_email {- "email.message_received"- } else {- "channel.mentioned"- };subscribed.filters = serde_json::from_value(json!([{"events":[name]}])).unwrap();let mut other = subscribed.clone();other.action_id = generate_uuid_v7();@@ -152,23 +152,36 @@ async fn mentions_and_mail_only_admit_their_recipient_even_when_others_have_accelet service =EventAdmissionService::new(repo.clone(), access.clone(), 10.try_into().unwrap());let id = generate_uuid_v7();- let payload = if is_email {- EventPayload::Email(serde_json::from_value(json!({+ let payload = match name {+ "email.message_received" => EventPayload::Email(serde_json::from_value(json!({"event_type":"email.message_received", "metadata": {"link_id": id, "owner": owner, "message_id": id, "thread_id": id,"provider_message_id": "message", "provider_thread_id": "thread","is_new_thread": true, "to_emails": [], "attachment_count": 0, "is_spam_or_trash": false}- })).unwrap())- } else {- EventPayload::Message(MessageFact::Mentioned(+ })).unwrap()),+ "call.started" => EventPayload::Call(serde_json::from_value(json!({+ "event_type":"call.started", "metadata": {+ "call_id": id, "channel_id": null, "created_by": owner,+ "created_at": Utc::now(), "recording_enabled": false+ }+ })).unwrap()),+ "call.ended" => EventPayload::Call(serde_json::from_value(json!({+ "event_type":"call.record_archived", "metadata": {+ "call_id": id, "channel_id": null, "created_by": "macro|[email protected]",+ "started_at": Utc::now(), "ended_at": Utc::now(), "duration_ms": 1_000,+ "participant_count": 2, "participants": ["macro|[email protected]", owner],+ "has_recording": false, "archive_reason": "last_participant_left"+ }+ })).unwrap()),+ _ => EventPayload::Message(MessageFact::Mentioned(serde_json::from_value(json!({"parent": {"type":"channel", "id": id}, "message_id": id, "root_id": id,"sender": "macro|[email protected]", "content":"", "created_at": Utc::now(),"mentioned": {"entity_type":"user", "entity_id": owner}})).unwrap(),- ))+ )),};let event = IncomingEvent {event_id: generate_uuid_v7(),diff --git a/services/scheduled_action/src/domain/event_runs/test_support.rs b/services/scheduled_action/src/domain/event_runs/test_support.rsindex 94de043c26..fba209b7fb 100644--- a/services/scheduled_action/src/domain/event_runs/test_support.rs+++ b/services/scheduled_action/src/domain/event_runs/test_support.rs@@ -62,6 +62,7 @@ pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> EveEventEntityType::Document => EntityType::Document,EventEntityType::Channel => EntityType::Channel,EventEntityType::EmailThread => EntityType::EmailThread,+ EventEntityType::Call => EntityType::Call,},};match event.entity_type() {@@ -93,6 +94,16 @@ pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> Eve).unwrap(),),+ EventEntityType::Call => EventAccessCapability::Call(+ EntityAccessReceipt::try_new_authenticated_user(+ owner,+ entity,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .unwrap(),+ ),}}diff --git a/services/scheduled_action/src/domain/event_trigger.rs b/services/scheduled_action/src/domain/event_trigger.rsindex 051c4974fb..b154f27e95 100644--- a/services/scheduled_action/src/domain/event_trigger.rs+++ b/services/scheduled_action/src/domain/event_trigger.rs@@ -1,9 +1,11 @@//! Routine-owned event eligibility and exact selector matching.//!//! Adapters strip the broker envelope into [`IncomingEvent`]. Only explicitly-//! allowlisted human actions and inbound emails become compact [`EventReference`]s.+//! allowlisted human actions, inbound emails and call lifecycle events become+//! compact [`EventReference`]s.use activity::Actor;+use call::domain::events::CallTopicEvent;use channels::domain::broker_events::ChannelTopicEvent;use chrono::{DateTime, Utc};use chrono_tz::Tz;@@ -33,7 +35,7 @@ mod test;/// Limits apply before deduplication, including repeated values.pub const MAX_FILTERS: usize = 32;-pub const MAX_EVENTS_PER_FILTER: usize = 13;+pub const MAX_EVENTS_PER_FILTER: usize = 15;pub const MAX_IDS_PER_FILTER: usize = 100;/// A routine may run on one trigger or any of several schedules and Macro events.@@ -180,6 +182,10 @@ pub enum EventName {ChannelMessagePatched,#[serde(rename = "channel.message_attachment_created")]ChannelMessageAttachmentCreated,+ #[serde(rename = "call.started")]+ CallStarted,+ #[serde(rename = "call.ended")]+ CallEnded,}impl EventName {@@ -198,6 +204,8 @@ impl EventName {Self::ChannelMentioned => "channel.mentioned",Self::ChannelMessagePatched => "channel.message_patched",Self::ChannelMessageAttachmentCreated => "channel.message_attachment_created",+ Self::CallStarted => "call.started",+ Self::CallEnded => "call.ended",}}@@ -211,7 +219,12 @@ impl EventName {| Self::TaskPriorityChanged| Self::TaskPropertyChanged => EventEntityType::Document,Self::EmailMessageReceived => EventEntityType::EmailThread,- _ => EventEntityType::Channel,+ Self::CallStarted | Self::CallEnded => EventEntityType::Call,+ Self::ChannelCreated+ | Self::ChannelMessagePosted+ | Self::ChannelMentioned+ | Self::ChannelMessagePatched+ | Self::ChannelMessageAttachmentCreated => EventEntityType::Channel,}}@@ -242,13 +255,14 @@ pub enum EventEntityType {Document,Channel,EmailThread,+ Call,}#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]pub enum FilterValidationError {#[error("expected between 1 and 32 filters")]FilterCount,- #[error("expected between 1 and 13 event names per filter")]+ #[error("expected between 1 and 15 event names per filter")]EventCount,#[error("expected at most 100 entity IDs per filter")]IdCount,@@ -521,6 +535,7 @@ pub enum EventPayload {Message(MessageFact),Property(PropertyTopicEvent),Email(EmailTopicEvent),+ Call(CallTopicEvent),}/// The message facts routines can trigger on, from `macro.messages`. Anything@@ -589,15 +604,20 @@ fn document_actor(}impl IncomingEvent {- /// Mentions belong to the mentioned user and inbound mail to its inbox- /// owner. Entity access is checked separately at admission and dispatch.- /// These audience restrictions never turn an event into an access grant.+ /// Mentions belong to the mentioned user, inbound mail to its inbox owner,+ /// a started call to who created it, and an ended call to who joined it.+ /// Entity access is checked separately at admission and dispatch. These+ /// audience restrictions never turn an event into an access grant.pub fn is_for_owner(&self, owner: &MacroUserIdStr<'static>) -> bool {match &self.payload {EventPayload::Message(MessageFact::Mentioned(data)) => {data.mentioned.entity_type == "user" && data.mentioned.entity_id == owner.as_ref()}EventPayload::Email(EmailTopicEvent::MessageReceived(data)) => &data.owner == owner,+ EventPayload::Call(CallTopicEvent::Started(data)) => &data.created_by == owner,+ EventPayload::Call(CallTopicEvent::RecordArchived(data)) => {+ data.participants.contains(owner)+ }_ => true,}}@@ -714,6 +734,19 @@ impl IncomingEvent {)}EventPayload::Email(_) => return Err(EventRejection::UnsupportedEvent),+ EventPayload::Call(CallTopicEvent::Started(data)) => {+ // The creator is always a Macro account; the call is theirs.+ (EventName::CallStarted, data.call_id, None)+ }+ EventPayload::Call(CallTopicEvent::RecordArchived(data)) => {+ // A call ends when its people leave, not by anyone's action;+ // it is theirs only if a Macro account joined it.+ if data.participants.is_empty() {+ return Err(EventRejection::UnsafeAttribution);+ }+ (EventName::CallEnded, data.call_id, None)+ }+ EventPayload::Call(_) => return Err(EventRejection::UnsupportedEvent),};Ok(EventReference {event_id,diff --git a/services/scheduled_action/src/domain/event_trigger/test.rs b/services/scheduled_action/src/domain/event_trigger/test.rsindex d824004bb4..4394fa8b14 100644--- a/services/scheduled_action/src/domain/event_trigger/test.rs+++ b/services/scheduled_action/src/domain/event_trigger/test.rs@@ -558,6 +558,72 @@ fn mention_trigger_is_only_for_the_mentioned_user() {);}+fn call_event(event_type: &str, participants: &[&str]) -> IncomingEvent {+ IncomingEvent {+ event_id: Uuid::parse_str(EVENT_ID).unwrap(),+ schema_version: 1,+ payload: EventPayload::Call(+ serde_json::from_value(json!({+ "event_type": event_type, "metadata": {+ "call_id": ENTITY_ID, "channel_id": OTHER_ID, "created_by": HUMAN,+ "created_at": "2024-01-01T00:00:00Z", "recording_enabled": true,+ "started_at": "2024-01-01T00:00:00Z", "ended_at": "2024-01-01T00:30:00Z",+ "duration_ms": 1_800_000, "participant_count": participants.len(),+ "participants": participants, "has_recording": true,+ "archive_reason": "last_participant_left", "ai_name_generated": false+ }+ }))+ .unwrap(),+ ),+ }+}++#[test]+fn started_calls_keep_only_ids_and_belong_to_who_created_them() {+ let event = call_event("call.started", &[]);+ let normalized = event.normalize().unwrap();+ assert_eq!(normalized.event_name(), EventName::CallStarted);+ assert_eq!(normalized.entity_type(), EventEntityType::Call);+ assert_eq!(normalized.entity_id().to_string(), ENTITY_ID);+ assert_eq!(normalized.message_id(), None);+ let stored = serde_json::to_string(&normalized).unwrap();+ assert!(!stored.contains("example.com"));+ assert!(!stored.contains(OTHER_ID));++ assert!(event.is_for_owner(&MacroUserIdStr::parse_from_str(HUMAN).unwrap()));+ assert!(+ !event.is_for_owner(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())+ );+}++#[test]+fn ended_calls_keep_only_ids_and_belong_to_the_people_who_joined() {+ let event = call_event("call.record_archived", &[HUMAN, "macro|[email protected]"]);+ let normalized = event.normalize().unwrap();+ assert_eq!(normalized.event_name(), EventName::CallEnded);+ assert_eq!(normalized.entity_type(), EventEntityType::Call);+ assert_eq!(normalized.entity_id().to_string(), ENTITY_ID);+ assert_eq!(normalized.message_id(), None);+ let stored = serde_json::to_string(&normalized).unwrap();+ assert!(!stored.contains("example.com"));+ assert!(!stored.contains(OTHER_ID));++ assert!(event.is_for_owner(&MacroUserIdStr::parse_from_str(HUMAN).unwrap()));+ assert!(+ !event.is_for_owner(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())+ );+ assert_eq!(+ call_event("call.record_archived", &[]).normalize(),+ Err(EventRejection::UnsafeAttribution)+ );+ for name in ["call.record_summarized", "call.recording_ready"] {+ assert_eq!(+ call_event(name, &[HUMAN]).normalize(),+ Err(EventRejection::UnsupportedEvent)+ );+ }+}+#[test]fn email_receipts_keep_only_ids_and_exclude_spam_and_backfills() {use email::domain::events::ThreadBackfilledMetadata;diff --git a/services/scheduled_action/src/inbound/kafka_consumer.rs b/services/scheduled_action/src/inbound/kafka_consumer.rsindex eda470e825..0f8076f67a 100644--- a/services/scheduled_action/src/inbound/kafka_consumer.rs+++ b/services/scheduled_action/src/inbound/kafka_consumer.rs@@ -7,6 +7,7 @@ mod test;use std::future::Future;use std::time::Duration;+use call::domain::events::CallMacroEvent;use channels::domain::broker_events::ChannelMacroEvent;use documents::domain::events::DocumentMacroEvent;use email::domain::events::EmailMacroEvent;@@ -30,15 +31,17 @@ macro_event_broker::declare_topics!(ChannelMacroEvent,MessageMacroEvent,PropertyMacroEvent,- EmailMacroEvent+ EmailMacroEvent,+ CallMacroEvent);struct ScheduledActionEventIngestionGroup;impl GroupName for ScheduledActionEventIngestionGroup {const GROUP_NAME: &'static str = "scheduled-action-event-ingestion";- // `macro.messages` joined this group's subscription with no committed- // offset; starting at its head avoids replaying the topic's retention.+ // Topics such as `macro.messages` and `macro.calls` joined this group's+ // subscription with no committed offset; starting at their head avoids+ // replaying each topic's retention.const INITIAL_OFFSET: InitialOffset = InitialOffset::Latest;}@@ -105,6 +108,14 @@ fn incoming_event(event: DeclaredMacroEvent) -> IncomingEvent {payload: EventPayload::Email(envelope.event.clone()),}}+ DeclaredMacroEvent::CallMacroEvent(event) => {+ let envelope = event.event();+ IncomingEvent {+ event_id: envelope.event_id,+ schema_version: envelope.schema_version,+ payload: EventPayload::Call(envelope.event.clone()),+ }+ }}}@@ -239,7 +250,7 @@ where}}-/// Consume exactly document and channel topics under a dedicated durable group.+/// Consume exactly the declared topics under a dedicated durable group.////// Only durable admission or a permanent rejection permits committing. Admission/// errors get five attempts with bounded exponential backoff. Exhausted retries,diff --git a/services/scheduled_action/src/inbound/kafka_consumer/test.rs b/services/scheduled_action/src/inbound/kafka_consumer/test.rsindex 17c84f7504..7f8dd5830d 100644--- a/services/scheduled_action/src/inbound/kafka_consumer/test.rs+++ b/services/scheduled_action/src/inbound/kafka_consumer/test.rs@@ -184,7 +184,8 @@ fn subscriptions_are_exact_and_group_is_dedicated() {"macro.channels","macro.messages","macro.properties",- "macro.email"+ "macro.email",+ "macro.calls"]);assert_eq!(@@ -390,3 +391,34 @@ fn document_conversion_preserves_the_envelope() {assert_eq!(event.schema_version, original.schema_version);assert_eq!(payload, original.event);}++#[test]+fn call_conversion_preserves_the_envelope() {+ let archived = json!({+ "event_id": EVENT_ID,+ "schema_version": 1,+ "event_type": "call.record_archived",+ "metadata": {+ "call_id": ENTITY_ID, "channel_id": null, "created_by": "macro|[email protected]",+ "started_at": "2026-10-08T14:00:00Z", "ended_at": "2026-10-08T14:30:00Z",+ "duration_ms": 1_800_000, "participant_count": 1,+ "participants": ["macro|[email protected]"], "has_recording": false,+ "archive_reason": "last_participant_left"+ }+ });+ let message = message(+ "macro.calls",+ Some(serde_json::to_vec(&archived).unwrap()),+ Some(ENTITY_ID.as_bytes().to_vec()),+ 10,+ );+ let event = incoming_event(DeclaredMacroEvent::decode(&message).unwrap());+ let EventPayload::Call(payload) = event.payload else {+ panic!("expected call payload");+ };+ let original: Event<call::domain::events::CallTopicEvent> =+ serde_json::from_value(archived).unwrap();+ assert_eq!(event.event_id, original.event_id);+ assert_eq!(event.schema_version, original.schema_version);+ assert_eq!(payload, original.event);+}diff --git a/services/scheduled_action/src/outbound/event_access.rs b/services/scheduled_action/src/outbound/event_access.rsindex 9ea7d5a0c9..e9e6d8d3f3 100644--- a/services/scheduled_action/src/outbound/event_access.rs+++ b/services/scheduled_action/src/outbound/event_access.rs@@ -72,6 +72,16 @@ impl<S: EntityAccessService> CurrentOwnerAccess for EventAccessAdapter<S> {).await.map(EventAccessCapability::EmailThread),+ EventEntityType::Call => self+ .service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ owner,+ None,+ &id,+ EntityType::Call,+ )+ .await+ .map(EventAccessCapability::Call),};access_result(result)}diff --git a/services/scheduled_action/src/outbound/event_access/test.rs b/services/scheduled_action/src/outbound/event_access/test.rsindex b8991616da..40e0671438 100644--- a/services/scheduled_action/src/outbound/event_access/test.rs+++ b/services/scheduled_action/src/outbound/event_access/test.rs@@ -135,6 +135,20 @@ async fn mints_entity_specific_receipts_for_exact_owner_and_entity() {access_level: AccessLevel::View,},),+ (+ "call.started",+ EntityType::Call,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ ),+ (+ "call.ended",+ EntityType::Call,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ ),("channel.created",EntityType::Channel,@@ -168,6 +182,8 @@ async fn wrong_permission_family_is_denied_not_reinterpreted() {let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();for (name, permission) in [("document.updated", EntityPermission::ChannelViewOnly),+ ("call.started", EntityPermission::ChannelViewOnly),+ ("call.ended", EntityPermission::ChannelViewOnly),("channel.created",EntityPermission::AccessLevel {diff --git a/services/scheduled_action/src/outbound/event_content.rs b/services/scheduled_action/src/outbound/event_content.rsindex 0ed9dad60b..f9ee4a4081 100644--- a/services/scheduled_action/src/outbound/event_content.rs+++ b/services/scheduled_action/src/outbound/event_content.rs@@ -6,6 +6,10 @@//! is logged: the content is the user's, and only the classifier and the//! routine's agent see it.+use call::domain::{+ models::{CallError, CallRecord},+ ports::CallRecordReader,+};use channels::domain::{models::{ChannelMetadata, ChannelType},ports::ChannelService,@@ -49,26 +53,31 @@ mod test;/// Longest text passed on per field, in characters. Jev reads up to 32k/// tokens of state; a few fields at this size stay well inside it.const MAX_TEXT_CHARS: usize = 8_000;+/// Longest call transcript passed on, in characters: about half an hour of+/// conversation, and still well inside what Jev reads.+const MAX_TRANSCRIPT_CHARS: usize = 24_000;/// Messages per thread page searched for the triggering email, newest first.const EMAIL_PAGE: i64 = 20;const MARKDOWN_FILE_TYPE: &str = "md";-pub struct EventContentAdapter<E, M, C, D, P> {+pub struct EventContentAdapter<E, M, C, D, P, K> {email: E,messages: M,channels: C,documents: D,properties: P,+ calls: K,markdown: LexicalClient,}-impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P> {+impl<E, M, C, D, P, K> EventContentAdapter<E, M, C, D, P, K> {pub fn new(email: E,messages: M,channels: C,documents: D,properties: P,+ calls: K,markdown: LexicalClient,) -> Self {Self {@@ -77,18 +86,20 @@ impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P> {channels,documents,properties,+ calls,markdown,}}}-impl<E, M, C, D, P> EventContentReader for EventContentAdapter<E, M, C, D, P>+impl<E, M, C, D, P, K> EventContentReader for EventContentAdapter<E, M, C, D, P, K>whereE: EmailContentService,M: MessageReader,C: ChannelService,D: DocumentRepo,P: PropertiesService,+ K: CallRecordReader,{async fn read(&self,@@ -101,13 +112,14 @@ where}}-impl<E, M, C, D, P> RoutineEventReader for EventContentAdapter<E, M, C, D, P>+impl<E, M, C, D, P, K> RoutineEventReader for EventContentAdapter<E, M, C, D, P, K>whereE: EmailContentService,M: MessageReader,C: ChannelService,D: DocumentRepo,P: PropertiesService,+ K: CallRecordReader,{async fn read_event(&self,@@ -138,6 +150,8 @@ enum EventContent {/// Body of Macro's own documents, when lexical could render it.markdown: Option<String>,},+ /// The ended call; None once its record has been deleted.+ Call(Option<CallRecord>),}struct ChannelMessage {@@ -146,13 +160,14 @@ struct ChannelMessage {thread: Option<MessageThread>,}-impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P>+impl<E, M, C, D, P, K> EventContentAdapter<E, M, C, D, P, K>whereE: EmailContentService,M: MessageReader,C: ChannelService,D: DocumentRepo,P: PropertiesService,+ K: CallRecordReader,{async fn content(&self,@@ -168,6 +183,20 @@ whereself.channel(owner, receipt.clone(), event).await}EventAccessCapability::Document(receipt) => self.document(receipt, event).await,+ EventAccessCapability::Call(receipt) => {+ Ok(EventContent::Call(self.call(receipt.clone()).await?))+ }+ }+ }++ async fn call(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<Option<CallRecord>, Report> {+ match self.calls.get_call_record(receipt).await {+ Ok(record) => Ok(Some(record)),+ Err(CallError::NotFound(_)) => Ok(None),+ Err(error) => Err(Report::new(error).into_dynamic()),}}@@ -329,6 +358,12 @@ fn content_json(event: &EventReference, content: &EventContent) -> Value {properties,markdown,} => json!({ "item": document_json(document, properties, markdown.as_deref()) }),+ EventContent::Call(record) => json!({+ "call": record.as_ref().map_or_else(+ || unavailable("the call record is no longer available"),+ call_json,+ ),+ }),}}@@ -350,7 +385,11 @@ fn unavailable(note: &str) -> Value {}fn truncate(text: &str) -> String {- match text.char_indices().nth(MAX_TEXT_CHARS) {+ truncate_to(text, MAX_TEXT_CHARS)+}++fn truncate_to(text: &str, max_chars: usize) -> String {+ match text.char_indices().nth(max_chars) {Some((end, _)) => format!("{}…", &text[..end]),None => text.to_owned(),}@@ -443,6 +482,26 @@ fn document_json(})}+fn call_json(record: &CallRecord) -> Value {+ let (transcript, transcript_omitted) = routine_event::call_transcript(record);+ json!({+ "title": record.custom_name,+ "channel": record.channel_name,+ "started_at": record.started_at,+ "ended_at": record.ended_at,+ "participants": routine_event::call_participants(record)+ .into_iter()+ .map(|person| person.name)+ .collect::<Vec<_>>(),+ "summary": record.summary.as_deref().map(truncate),+ "transcript": transcript+ .into_iter()+ .map(|line| format!("{}: {}", line.speaker, line.text))+ .collect::<Vec<_>>(),+ "transcript_omitted": transcript_omitted,+ })+}+/// A property's value as people read it: option labels rather than ids.fn property_value(property: &EntityPropertyInfo) -> Option<Value> {match property.value.as_ref()? {diff --git a/services/scheduled_action/src/outbound/event_content/routine_event.rs b/services/scheduled_action/src/outbound/event_content/routine_event.rsindex caabdd4d87..ad851de66f 100644--- a/services/scheduled_action/src/outbound/event_content/routine_event.rs+++ b/services/scheduled_action/src/outbound/event_content/routine_event.rs@@ -1,6 +1,9 @@//! The typed event a routine's agent is told about, from the same content the//! condition classifier reads.+use std::collections::HashMap;++use call::domain::models::CallRecord;use channel_sender::ChannelSender;use channels::domain::models::{ChannelMetadata, ChannelType as ChannelKind};use email::domain::models::{ContactInfo, ParsedMessage};@@ -15,11 +18,14 @@ use properties::EntityPropertyInfo;use rootcause::Report;use system_properties::SystemPropertyKey;use trigger_context::{- ChannelType, ContextMessage, ContextPerson, ContextThread, DiscussionContext,- DiscussionSurface, DocumentSnapshot, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,+ CallSnapshot, CallStartedSnapshot, ChannelType, ContextMessage, ContextPerson, ContextThread,+ DiscussionContext, DiscussionSurface, DocumentSnapshot, EmailSnapshot, ReplyTarget,+ RoutineEvent, TaskSnapshot, TranscriptLine,};-use super::{ChannelMessage, EventContent, email_body, truncate};+use super::{+ ChannelMessage, EventContent, MAX_TRANSCRIPT_CHARS, email_body, truncate, truncate_to,+};use crate::domain::event_trigger::{EventName, EventReference};#[cfg(test)]@@ -53,6 +59,18 @@ pub(super) fn routine_event(EventContent::Channel { channel, message } => {channel_event(name, event.entity_id(), channel, message)}+ EventContent::Call(record) => match (name, record) {+ (EventName::CallStarted, Some(record)) => Ok(RoutineEvent::CallStarted {+ call: call_started_snapshot(event.entity_id(), record)?,+ }),+ (EventName::CallEnded, Some(record)) => Ok(RoutineEvent::CallEnded {+ call: call_snapshot(event.entity_id(), record)?,+ }),+ (EventName::CallStarted | EventName::CallEnded, None) => {+ Err(rootcause::report!("the call record is no longer available"))+ }+ (name, _) => Err(mismatch(name)),+ },}}@@ -204,6 +222,96 @@ fn email_snapshot(thread_id: Uuid, message: &ParsedMessage) -> EmailSnapshot {}}+fn call_started_snapshot(call_id: Uuid, record: CallRecord) -> Result<CallStartedSnapshot, Report> {+ if record.call_id != call_id {+ return Err(mismatch(EventName::CallStarted));+ }+ let started_by = principal(&record.created_by);+ let participants = call_participants(&record);+ Ok(CallStartedSnapshot {+ id: record.call_id,+ title: record.custom_name,+ channel_id: record.channel_id,+ channel_name: record.channel_name,+ started_at: record.started_at,+ started_by,+ participants,+ })+}++fn call_snapshot(call_id: Uuid, record: CallRecord) -> Result<CallSnapshot, Report> {+ if record.call_id != call_id {+ return Err(mismatch(EventName::CallEnded));+ }+ let ended_at = record+ .ended_at+ .ok_or_else(|| rootcause::report!("the call has not ended"))?;+ let participants = call_participants(&record);+ let (transcript, transcript_omitted) = call_transcript(&record);+ Ok(CallSnapshot {+ id: record.call_id,+ title: record.custom_name,+ channel_id: record.channel_id,+ channel_name: record.channel_name,+ started_at: record.started_at,+ ended_at,+ participants,+ summary: record.summary.as_deref().map(truncate),+ transcript,+ transcript_omitted,+ })+}++/// Everyone who joined: Macro accounts first, then guests by their own names.+pub(super) fn call_participants(record: &CallRecord) -> Vec<ContextPerson> {+ record+ .participants+ .iter()+ .map(|participant| principal(&participant.user_id))+ .chain(record.guests.iter().map(|guest| ContextPerson {+ id: guest.id.to_string(),+ name: guest.display_name.clone(),+ email: None,+ }))+ .collect()+}++/// What was said, oldest first, up to [`MAX_TRANSCRIPT_CHARS`] of speech; true+/// when the rest was left out.+pub(super) fn call_transcript(record: &CallRecord) -> (Vec<TranscriptLine>, bool) {+ let guests: HashMap<String, &str> = record+ .guests+ .iter()+ .map(|guest| (guest.id.to_string(), guest.display_name.as_str()))+ .collect();+ let line = |speaker_id: &str, text: String, at| TranscriptLine {+ speaker: guests+ .get(speaker_id)+ .map_or_else(|| principal(speaker_id).name, |name| (*name).to_owned()),+ text,+ at,+ };+ let mut room = MAX_TRANSCRIPT_CHARS;+ let mut lines = Vec::new();+ for segment in &record.transcript {+ let length = segment.content.chars().count();+ if length > room {+ if room > 0 {+ let text = truncate_to(&segment.content, room);+ lines.push(line(&segment.speaker_id, text, segment.started_at));+ }+ return (lines, true);+ }+ room -= length;+ lines.push(line(+ &segment.speaker_id,+ segment.content.clone(),+ segment.started_at,+ ));+ }+ (lines, false)+}+fn address(contact: &ContactInfo) -> String {match &contact.name {Some(name) => format!("{name} <{}>", contact.email),diff --git a/services/scheduled_action/src/outbound/event_content/routine_event/test.rs b/services/scheduled_action/src/outbound/event_content/routine_event/test.rsindex c15d6376ab..99542eb476 100644--- a/services/scheduled_action/src/outbound/event_content/routine_event/test.rs+++ b/services/scheduled_action/src/outbound/event_content/routine_event/test.rs@@ -1,5 +1,9 @@+use call::domain::{+ meetings::GuestId,+ models::{CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordTranscriptSegment},+};use channels::domain::models::{ChannelMetadata, ChannelType as ChannelKind};-use chrono::{TimeZone, Utc};+use chrono::{DateTime, TimeZone, Utc};use document_sub_type::DocumentSubType;use email::domain::models::{ContactInfo, ParsedLabel, ParsedMessage};use macro_user_id::user_id::MacroUserIdStr;@@ -16,14 +20,205 @@ use properties::{EntityPropertyInfo, PropertyOptionInfo};use serde_json::json;use system_properties::SystemPropertyKey;use trigger_context::{- ChannelType, ContextMessage, ContextPerson, ContextThread, DiscussionContext,- DiscussionSurface, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,+ CallSnapshot, CallStartedSnapshot, ChannelType, ContextMessage, ContextPerson, ContextThread,+ DiscussionContext, DiscussionSurface, EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot,+ TranscriptLine,};-use super::super::{ChannelMessage, EventContent};-use super::routine_event;+use super::super::{ChannelMessage, EventContent, MAX_TRANSCRIPT_CHARS};+use super::{call_transcript, routine_event};use crate::domain::event_trigger::EventReference;+const CALL_ID: &str = "01928f3e-6a2b-7c3d-8e4f-0000000ca11e";++fn call_started() -> EventReference {+ serde_json::from_value(json!({+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",+ "event_name": "call.started",+ "entity_id": CALL_ID,+ "message_id": null,+ }))+ .unwrap()+}++fn call_ended() -> EventReference {+ serde_json::from_value(json!({+ "event_id": "01928f3e-6a2b-7c3d-8e4f-0123456789cd",+ "event_name": "call.ended",+ "entity_id": CALL_ID,+ "message_id": null,+ }))+ .unwrap()+}++fn at(minute: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 10, 8, 14, minute, 0).unwrap()+}++fn segment(speaker_id: &str, content: &str, minute: u32) -> CallRecordTranscriptSegment {+ CallRecordTranscriptSegment {+ transcript_id: macro_uuid::generate_uuid_v7(),+ segment_id: None,+ speaker_id: speaker_id.into(),+ diarized_speaker_id: None,+ content: content.into(),+ started_at: at(minute),+ ended_at: None,+ sequence_num: minute as i32,+ }+}++fn ended_call(transcript: Vec<CallRecordTranscriptSegment>) -> CallRecord {+ CallRecord {+ call_id: Uuid::parse_str(CALL_ID).unwrap(),+ channel_id: Some(Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0000000c4a77").unwrap()),+ room_name: "room".into(),+ created_by: "macro|[email protected]".into(),+ started_at: at(0),+ ended_at: Some(at(30)),+ duration_ms: Some(1_800_000),+ egress_id: None,+ recording_started_at: None,+ recording_key: None,+ preview_key: None,+ recording_url: None,+ recording_preview_url: None,+ channel_name: Some("eng".into()),+ custom_name: None,+ summary: None,+ team_share_access_level: None,+ share_with_team: false,+ is_active: false,+ status: None,+ user_access_level: None,+ viewer_has_declined: false,+ participants: vec![CallRecordParticipant {+ user_id: "macro|[email protected]".into(),+ joined_at: at(0),+ left_at: Some(at(30)),+ }],+ guests: Vec::new(),+ transcript,+ }+}++#[test]+fn a_started_call_carries_who_started_it_and_who_has_joined() {+ let mut record = ended_call(Vec::new());+ record.ended_at = None;+ record.duration_ms = None;+ record.is_active = true;+ record.participants[0].left_at = None;+ record.custom_name = Some("Standup".into());++ assert_eq!(+ routine_event(&call_started(), EventContent::Call(Some(record))).unwrap(),+ RoutineEvent::CallStarted {+ call: CallStartedSnapshot {+ id: Uuid::parse_str(CALL_ID).unwrap(),+ title: Some("Standup".into()),+ channel_id: Some(Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0000000c4a77").unwrap()),+ channel_name: Some("eng".into()),+ started_at: at(0),+ started_by: ContextPerson {+ id: "macro|[email protected]".into(),+ name: "[email protected]".into(),+ email: Some("[email protected]".into()),+ },+ participants: vec![ContextPerson {+ id: "macro|[email protected]".into(),+ name: "[email protected]".into(),+ email: Some("[email protected]".into()),+ }],+ },+ }+ );+}++#[test]+fn an_ended_call_carries_its_people_and_what_they_said() {+ let guest =+ GuestId::from_uuid(Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-00000000065e").unwrap());+ let mut record = ended_call(vec![+ segment("macro|[email protected]", "Can we ship Friday?", 1),+ segment(&guest.to_string(), "Yes, after QA signs off.", 2),+ ]);+ record.custom_name = Some("Release sync".into());+ record.guests = vec![CallRecordGuest {+ id: guest,+ display_name: "Sam (Acme)".into(),+ joined_at: at(0),+ left_at: Some(at(29)),+ }];++ assert_eq!(+ routine_event(&call_ended(), EventContent::Call(Some(record))).unwrap(),+ RoutineEvent::CallEnded {+ call: CallSnapshot {+ id: Uuid::parse_str(CALL_ID).unwrap(),+ title: Some("Release sync".into()),+ channel_id: Some(Uuid::parse_str("01928f3e-6a2b-7c3d-8e4f-0000000c4a77").unwrap()),+ channel_name: Some("eng".into()),+ started_at: at(0),+ ended_at: at(30),+ participants: vec![+ ContextPerson {+ id: "macro|[email protected]".into(),+ name: "[email protected]".into(),+ email: Some("[email protected]".into()),+ },+ ContextPerson {+ id: guest.to_string(),+ name: "Sam (Acme)".into(),+ email: None,+ },+ ],+ summary: None,+ transcript: vec![+ TranscriptLine {+ speaker: "[email protected]".into(),+ text: "Can we ship Friday?".into(),+ at: at(1),+ },+ TranscriptLine {+ speaker: "Sam (Acme)".into(),+ text: "Yes, after QA signs off.".into(),+ at: at(2),+ },+ ],+ transcript_omitted: false,+ },+ }+ );+}++#[test]+fn a_long_transcript_is_cut_mid_speech_and_says_so() {+ let record = ended_call(vec![+ segment(+ "macro|[email protected]",+ &"a".repeat(MAX_TRANSCRIPT_CHARS - 10),+ 1,+ ),+ segment("macro|[email protected]", &"b".repeat(20), 2),+ segment("macro|[email protected]", "never reached", 3),+ ]);+ let (lines, omitted) = call_transcript(&record);+ assert!(omitted);+ assert_eq!(lines.len(), 2);+ assert_eq!(lines[1].text, format!("{}…", "b".repeat(10)));+}++#[test]+fn a_deleted_call_or_another_calls_record_does_not_become_the_event() {+ assert!(routine_event(&call_started(), EventContent::Call(None)).is_err());+ assert!(routine_event(&call_ended(), EventContent::Call(None)).is_err());+ let mut other = ended_call(Vec::new());+ other.call_id = macro_uuid::generate_uuid_v7();+ assert!(routine_event(&call_started(), EventContent::Call(Some(other.clone()))).is_err());+ assert!(routine_event(&call_ended(), EventContent::Call(Some(other))).is_err());+}+#[test]fn a_task_status_change_carries_the_task_as_it_reads_now() {let event: EventReference = serde_json::from_value(json!({diff --git a/services/scheduled_action/src/outbound/event_content/test.rs b/services/scheduled_action/src/outbound/event_content/test.rsindex 0495cf24e9..3b31620b7f 100644--- a/services/scheduled_action/src/outbound/event_content/test.rs+++ b/services/scheduled_action/src/outbound/event_content/test.rs@@ -223,6 +223,77 @@ fn tasks_show_option_labels_and_skip_unset_properties() {);}+#[test]+fn calls_show_who_joined_and_what_they_said() {+ use call::domain::models::{CallRecordParticipant, CallRecordTranscriptSegment};+ let at = Utc.with_ymd_and_hms(2026, 10, 8, 14, 0, 0).unwrap();+ let record = CallRecord {+ call_id: Uuid::nil(),+ channel_id: None,+ room_name: "room".into(),+ created_by: "macro|[email protected]".into(),+ started_at: at,+ ended_at: Some(at + chrono::Duration::minutes(30)),+ duration_ms: Some(1_800_000),+ egress_id: None,+ recording_started_at: None,+ recording_key: Some("private/recording.mp4".into()),+ preview_key: None,+ recording_url: None,+ recording_preview_url: None,+ channel_name: None,+ custom_name: Some("Acme renewal".into()),+ summary: Some("Acme will renew if we ship SSO.".into()),+ team_share_access_level: None,+ share_with_team: false,+ is_active: false,+ status: None,+ user_access_level: None,+ viewer_has_declined: false,+ participants: vec![CallRecordParticipant {+ user_id: "macro|[email protected]".into(),+ joined_at: at,+ left_at: None,+ }],+ guests: Vec::new(),+ transcript: vec![CallRecordTranscriptSegment {+ transcript_id: Uuid::nil(),+ segment_id: None,+ speaker_id: "macro|[email protected]".into(),+ diarized_speaker_id: None,+ content: "When do you need SSO?".into(),+ started_at: at,+ ended_at: None,+ sequence_num: 0,+ }],+ };++ let event = event("call.ended", None);+ let value = envelope(+ &owner(),+ &event,+ content_json(&event, &EventContent::Call(Some(record))),+ );+ assert_eq!(value["event"], "call.ended");+ assert_eq!(+ value["call"],+ json!({+ "title": "Acme renewal",+ "channel": null,+ "started_at": "2026-10-08T14:00:00Z",+ "ended_at": "2026-10-08T14:30:00Z",+ "participants": ["[email protected]"],+ "summary": "Acme will renew if we ship SSO.",+ "transcript": ["[email protected]: When do you need SSO?"],+ "transcript_omitted": false,+ })+ );+ assert_eq!(+ content_json(&event, &EventContent::Call(None))["call"],+ json!({"unavailable": "the call record is no longer available"})+ );+}+#[test]fn deleted_documents_say_so_without_content() {let mut document = task();diff --git a/services/scheduled_action/tests/event_routines.rs b/services/scheduled_action/tests/event_routines.rsindex 364a062325..74d01f1906 100644--- a/services/scheduled_action/tests/event_routines.rs+++ b/services/scheduled_action/tests/event_routines.rs@@ -113,6 +113,7 @@ impl CurrentOwnerAccess for FakeAccess {EventEntityType::Document => EntityType::Document,EventEntityType::Channel => EntityType::Channel,EventEntityType::EmailThread => EntityType::EmailThread,+ EventEntityType::Call => EntityType::Call,},};let access = match event.entity_type() {@@ -144,6 +145,16 @@ impl CurrentOwnerAccess for FakeAccess {).unwrap(),),+ EventEntityType::Call => EventAccessCapability::Call(+ EntityAccessReceipt::try_new_authenticated_user(+ owner.clone(),+ entity,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .unwrap(),+ ),};Ok(Some(access))}diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex a1199db500..b3a7d9201c 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -167,7 +167,8 @@ fn archived_event() -> CallTopicEvent {started_at: Utc::now(),ended_at: Utc::now(),duration_ms: Some(1_000),- participant_count: 2,+ participant_count: 1,+ participants: vec![user_id()],has_recording: true,archive_reason: CallArchiveReason::LastParticipantLeft,})diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 0d6d657ef7..c4f9426ab2 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -5997,6 +5997,14 @@ enum GraphqlScheduledActionEventName {A channel message attachment was created."""CHANNEL_MESSAGE_ATTACHMENT_CREATED+ """+ A call the routine's owner started began.+ """+ CALL_STARTED+ """+ A call the routine's owner joined ended.+ """+ CALL_ENDED}"""