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
calendar_events
What it is
Part of Calendar: owns the stable CalendarEvent entity — parsing from
external sources (Google Calendar, Outlook, email invitations), mutation,
reminder dispatch, team availability, and provider/Postgres persistence.
Start here
src/domain/models.rs+src/domain/events.rs: theCalendarEvententity and recurrence-occurrence projections.src/domain/mutations.rs,src/domain/invitations.rs,src/domain/meeting_links.rs: write paths — mutations, email invitations, and Macro-call meeting links.src/domain/capabilities.rs: Google's organizer-setGuestPolicyand theViewerCapabilitiesevery read surface exposes asviewerCan.src/domain/team_availability.rs+src/domain/team.rs: team sharing/availability.src/outbound/google.rs,src/outbound/pg.rs: Google Calendar and Postgres adapters.src/outbound/pg/outlook.rs: durable Outlook synchronization; preserve provider-specific coverage on discovery.src/inbound/dispatch_worker.rs+src/outbound/sqs_dispatch_queue.rs: reminder dispatch queue (featuredispatch/dispatch-sqs).
Scope
- Owns: the
CalendarEvententity, its Google/Outlook/email sources, recurrence occurrences, reminder dispatch, and team calendar sharing/availability. - Not here: booking links, scheduling pages, and host/attendee booking policy →
crates/calendar_scheduling; the calendar service's HTTP composition root →services/calendar_service.
Boundaries
- Depends on:
call(featurecall-meetings, meeting links),macro_user_id,notification(featurenotify),model_notifications,aws-sdk-sqs(featuredispatch-sqs). - Used by:
email,ai_tools,channel_bots,graphql_calendar,complete_graph,calendar_scheduling,search_service.
Recipes
- Add a mutation:
src/domain/mutations.rs→src/outbound/pg.rs(orsrc/outbound/calendar_service_mutations.rsfor the HTTP client adapter) →src/inbound/mutation_router.rs/src/inbound/toolset.rs. - Add a reminder type:
src/domain/reminder_dispatch.rs→src/inbound/dispatch_worker.rs→src/outbound/notification_notifier.rs. - Change team availability:
src/domain/team_availability.rs→src/outbound/pg_team.rs→src/inbound/team_router.rs/src/inbound/team_toolset.rs.
Checks
cargo test -p calendar_events(SQLX_OFFLINEunset).
Gotchas
CalendarEventis the stable Macro entity; external calendars and email invitations are sources feeding it, and recurrence instances are queryable occurrence projections, not separate events — don't model them as new entities.- Imported point (non-recurring) events must survive sync and cache round-trips unchanged (#7762) — a regression here silently drops user events.
- Normalize imported Google all-day events with matching start/end dates to one day in the adapter, including recurring instances and overrides; preserve the raw provider payload and keep reversed dates invalid.
- Only an organizer (or a guest the organizer lets modify) may replace an
event's attendee list. Everyone else adds guests through
invite_guests(src/domain/mutations/invite.rs); a guest'supdate_eventattendees are routed there and removals are refused. Google refuses new attendees inattendeesOmittedmode (omittedAttendeesSpecified), so the invite writes the whole list Google returned plus the new guests, and a guest is refused (guest_list_hidden) while the organizer hides the guest list, since their copy lacks the guests it would drop. Microsoft Graph has no attendee-side write either: an Outlook organizer adds guests with the same full-list write (email_api_client'soutlook/calendar/invite.rs), and an Outlook guest may only answer (guests_cannot_invite). An Outlook organizer may not answer: Graph fixes the organizer's response, soViewerCapabilities::rsvpis false and the adapter refuses an answer withNotAttendee. - A guest without
edit_detailsmay change only what Google keeps on each guest's copy (reminders, availability) and add guests where allowed:update_eventdrops details the patch repeats at their stored value (get_event_details, the series or the addressed occurrence) and refuses any other detail change withGuestsCannotModifybefore inviting anyone. Someone neither organizing nor invited is left to their calendar access. - Only the organizer of a Google copy sets the guest policy
(
src/domain/mutations/guest_policy.rs): drafts and patches carry it as Google's three switches, a policy equal to the stored one (or Google's defaults on create) is dropped, a change from anyone else isNotOrganizer, one on Outlook, which has no such switches, isProviderRejected, and one scoped to a single occurrence or on a new out-of-office event isInvalidInput.ViewerCapabilities::set_guest_policyis therefore Google-only, andorganizeis the organizer signal clients read instead. - The organizer's own copy decides the guest policy of every Macro-held copy
of a Google meeting (
src/outbound/pg/guest_policy.rs). Google takes 4 to 12 seconds to carry an organizer's change to its guests' copies, and a guest invite in that window gets a 200 while Google drops the guest and mails nobody. The organizer's copy is the Google source on the calendar Google names as the organizer (the address for a primary calendar, the calendar id for a secondary one) that its inbox can write: the copyorganizer_copy_calendar_idroutes organizer writes through. Every upsert reads that source's policy and writes it to each entity of the meeting with that organizer (the organizer's own, when its canonical copy is the primary-calendar invitation, included) and to every other Google source's projection, across users, so a guest-side write or an invitation read-back echoing Google's stale switches cannot reopen inviting. Copies pair bycalendar_meeting_uidand organizer; Outlook copies and snapshots take no part. The aligned copies' inboxes get change-log entries and refresh nudges (CalendarEventWriteOutcome::aligned_copies). An organizer whose calendar no Macro inbox writes still reaches guests only through Google's sync. - Sharing an event into a channel writes an
entity_accessrow on the sharer's copy. Thecalendar_event_entity_access_cleanuptrigger deletes it with the event row, which covers every way a copy goes away: a delete through Macro, a sync tombstone or removal, a disabled calendar, and theemail_linkscascade when the inbox is removed. A cancelled, private or confidential row keeps its grants, since readers skip them and the row can come back. Removing one source, or cancelling one occurrence, leaves the row. - A channel-shared event reaches a member's calendar as a snapshot, not a
seat:
copy_shared_event(src/domain/mutations/copy.rs) imports it under the meeting's iCalendar UID with no join link, behind the sameevent_exportvisibility query as the .ics route. Google imports only for the organizer or an attendee (participantIsNeitherOrganizerNorAttendee, mapped tocopy_refused), so the body keeps the real organizer and lists the target calendar, accepted, as the only guest, plus the privatemacroSnapshotextended property. Sync stores it asis_snapshot, which grants no capability and makes RSVPs and invites fail withsnapshot, since neither would reach the meeting. An invitation to the same meeting later lands on the snapshot's Google event (same UID, marker kept), soimport::is_snapshotcounts a marked copy as a snapshot only while it holds what the import wrote: the calendar as its only attendee, answered. Another attendee (a Google meeting with guests lists its organizer) or the calendar's row back atneedsActionmakes it the owner's seat, and the Postgres upsert keeps a source stored as a seat from turning back after they answer. Its owner changes its details only as a guest without modify rights would (reminders and availability), and may delete it. The mutation target reads the flag from the addressed copy's projection, since a snapshot can share its entity with the real meeting on another calendar of the same inbox. Google only: never import over a UID the calendar already holds, since an import updates that event in place and would strip an unsynced invitation's guests. The agent adds a copy withAddSharedCalendarEvent(src/inbound/toolset/add_shared_calendar_event.rs) only while theENABLE_CALENDAR_ADD_SHARED_EVENTdeployment switch is on (off unless set, like the card'senable-calendar-add-shared-event); without acalendarIdit takes the card's only target calendar or asks which one. An event file forwarded by email takes the same import throughCalendarSnapshotImporter::import_snapshot, fed anEventSnapshotthatcrates/email'sinvitation_importbuilds from the email's saved snapshot. Only the channel-share path strips the Macro call (content_without_macro_call, behindEventSnapshot::without_macro_call); a forwarded file keeps the join link it carries. The other direction, a guest forwarding their copy of an event, renders it throughCalendarEventForwardSource::event_forward, which also names the inbox holding that copy (meeting_copies), and isNonefor a channel share or a delegated inbox's copy;crates/email'sevent_forwardsends it. The copy decides the kind (ForwardedCopy::outside_organizer, read byforwarded_copyfrom every source of the copy): Google's private copy (privateCopyin the stored raw payload, which Google sets on every invitation from another calendar system) that is not a snapshot, whose UID Google did not mint (…@google.com), and that names its organizer becomes aMETHOD:REQUESTinvitation naming only the recipients, answered to that organizer, as Google's own Add guests sends there. Anything else, a Google organizer who turned inviting off above all, keeps theMETHOD:PUBLISHfile naming no attendees, so a recipient can only add it to their calendar and nothing reaches the organizer; missing evidence falls back to it. One renderer serves every use:render_event_icstakes anIcsPurpose, and onlyForwardkeeps the Macro call and adds the copy's conference link (JoinLink), whichShare(the .ics download) and channel shares never carry. - Asking to join a channel-shared event (
src/domain/join_requests.rs) is a Macro-stored request, not anentity_accessrow: the grant is a provider guest write. Eligibility is the invite path's owncopy_capabilitieson the sharer's copy, so a request that can be made is one the sharer can accept, and accepting callsinvite_guestsas the sharer (src/domain/mutations/join.rs). A declined request stands: asking again is refused withDeclined(409request_declined) and never notifies the sharer twice. While the requester's request is pending or accepted,copy_shared_eventrefuses withJoinRequestOpen: the answer is an invitation under the meeting's UID, which a snapshot imported meanwhile would take in. A declined requester may still add a copy. Nothing in the domain retires the sharer's notification: opening the event marks it seen, a trigger oncalendar_event_join_requestsrunningdelete_answered_join_request_notificationdeletes it when anyone answers the request, a second there runningdelete_removed_join_request_notificationdeletes it with the request row, which the requester's account deletion cascades away, and two triggers oncalendar_eventsrunningdelete_calendar_event_join_request_notificationsdelete it with the event row, or when the row turnscancelled(Outlook can keep a cancelled meeting). That covers the ways a copy goes away listed for channel grants above, and each delete reaches open clients throughtrg_notify_user_notification_deletes. An event can hold several open requests, so the triggers on the request row match therequestIdin the notification's metadata, not the event alone. The notifier only queues, so a backlog can deliver a notification after that cleanup; anotificationinsert trigger skips it while the event is gone or cancelled or the request is no longer pending, locking the event and then the request to decide in order with a change in flight. Deleting an event reaches both delete cleanups in one transaction, and whichever runs first leaves nothing for the other. Both lock onlynotificationrows, once the delete holds its row, so neither changes that order. The cancelled row keeps its requests, as it keeps its grants, and a cancelled occurrence changes neither. An answer that changes the request reaches open clients throughCalendarRefreshNotifier, after it is stored (an acceptance's invite nudges before that, too early to carry it):calendar_changedfor the owner and delegates of the sharer's inbox, whoserefresh_calendarrefetches open request lists, andjoin_request_answeredfor the requester, who views the event through the share, so that signal names the event and never the sharer's inbox. A list reader may hold no notification, so the delete above is not that signal. An answer to a request no longer pending returns it unchanged and stays quiet; the client reads a status other than its decision as already answered. Only an acceptance whose invitation is being written overrules a decline (resolve_join_request), and it returnsaccepted. A new request reaches open lists the same way:request_to_joinsendscalendar_changedfor the inbox of the sharer's copy once the row is stored, and only when this ask created it, so a repeat or a refused ask stays quiet. Each inbox holds its own entity, so however many of its calendars hold the event there is one list and one nudge, and another inbox's copy has its own list. The signal names that inbox, so it goes only to the list's readers; the requester is never one, since a reader's own view of the event isOwnCopy, which refuses the ask. The web also refetches the list when the sharer's notification lands, but that is not the signal: it reaches no delegate, a muted category never sends it, and the notifier only queues.document_storage_servicehosts the ask, so it has its ownCalendarRefreshNotifier(src/outbound/calendar_refresh.rs). - Calendar mentions reach the agent as document mentions (
blockNamecalendar), butReadContentandReadMetadataneed document access, which a channel-shared event never grants. The agent reads a mentioned event withReadCalendarEvent(src/inbound/toolset/read_calendar_event.rs), which goes throughmention_previews: the hover card's visibility and fields. A preview that falls back to a channel share loses its Macro call there, in the repository and before the description cap, since the join line closes the description. Whoever resolves to their own copy keeps it: the card's Join button reads the link from the preview. Only the generated Macro call goes; join text a provider wrote into the body, as a Teams invitation's, stays, as it does in a snapshot. Search rows apply the same rule, but a row stays on the hit instead of resolving to the viewer's copy, so there a snapshot does not count as holding the meeting. - Google names the calendar an event was made on as its organizer, so an
event on a secondary calendar has that calendar's id
(
…@group.calendar.google.com) asorganizer_email; Google'sorganizer.selfis not stored. An inbox organizes an event when the organizer is its address or a calendar it can write (OwnedInbox::organizes, fed byowned_inboxes'writable_calendar_ids), as Google allows, and the mention preview'sinbox_organizesandmeeting_copiesapply the same rule in SQL. When such an event also lists the inbox's address, Google invites its primary calendar too, and both copies share one entity whose canonical copy is that invitation. Changes only the organizer may make (details, guests, guest policy, deleting) go through the copy on the organizer's calendar (CalendarEventMutationTarget::organizer_copy_calendar_id,src/domain/mutations/organizer_copy.rs), then the addressed copy is read back (CalendarMutationProvider::refresh_event); reminders, availability and answers stay on the addressed copy, written before the organizer's copy. Google carries the change to the invitation 15 to 30 seconds later, so the read-back is usually stale: the response takes the meeting from the organizer copy's echo, and the Postgres upsert lets a user edit through the organizer's copy write the meeting's title, description, location and visibility (stamped incalendar_events.content_updated_at) and its whole schedule, guests included. The canonical copy retakes that content only once it is at least as fresh, and until thenfetch_source_contentsserves every older copy with it, since the web shows a copy's own title. Only a user edit starts this; a sync of the organizer's copy leaves content to the canonical copy as before. A new event lists the inbox as an accepted guest on its primary calendar and on Outlook, but on another Google calendar only when it has other guests, as Google's own client does, so a solo event is one block. viewer_canis viewer-relative, like an attendee'sis_self: resolve it withActorInboxes::mark_eventand the copy's source link wherever a read path marks the viewer, and never store it. Calendar caches refresh only the events the change log lists, so a change to how capabilities are resolved leaves cached events with the old ones until each changes; ship it with a migration that logs an upsert for every event it affects, as20261026184741_log_events_organized_by_a_writable_calendar.sqldoes for events a writable calendar organizes. Each connected inbox gets its own copy (entity) of an event, written through that inbox's grant, so the viewer organizes or attends a copy only as its inbox: another of their inboxes on the same event lends it nothing, and only that inbox's row isis_self. Mutations act asCalendarEventMutationTarget::copy_inbox, and so does an RSVP without aresponding_email. A delegate owns no copy inbox and gets nothing beyond the no-attendees rule.guest_policyis stored on the entity row (the canonical copy's values) and in each source's projection, omitted there while it holds Google's default. Event responses always carry both;StoredSourceProjectionstrips them so unchanged events keep comparing equal. Since one meeting on two inboxes is two entities, the agent tools label every event they return with its calendar's name, itsinboxand the user'smyRolethere (ToolEventRole::of), so the agent can ask or pick by inbox. Their descriptions set the rule: reminders and an answer may go to one copy if the reply names its inbox (an answer asks first when the user is a guest through several inboxes); a change whose effect differs by copy (details, guests, permissions, deleting) goes to the only copy allowed to make it, with the reason, or the agent asks, and guests are added from the copy the user organizes. The agent must never choose between the user's inboxes itself, whatever they look like: the SDK's CalendarNamespace overview, the delete and update docs and the DeleteCalendarEvent and UpdateCalendarEvent descriptions state the ask rule first.domain::copies::check_copyenforces it: such a change on a meeting the user holds through several of their own inboxes (meeting_copies) is refused, listing each copy and ending with the question to ask word for word, untilinboxnames the addressed copy's inbox. The route cannot tell an inbox the user chose from one the agent picked, so the wording is the only guard against a guess. UpdateCalendarEvent and DeleteCalendarEvent check every call; the update, invite-guests and delete routes check agent runs and any request naminginboxthroughCalendarCopyConfirmation, answering 409copy_choice_required. An agent run (macro_authorization::is_agent_run) is a token withagent_id(in-app code mode) or a request carryingx-macro-code-execution, whichcode_execution's bootstrap sets on every code-mode program's SDK requests, public MCP clients' included. Code-mode agents never see the calendar tools (agent_code_mode::covered_by_code_sdk), so the routes and the SDK docs are what reach them; the web, which opens one copy, sends noinboxand is not checked.- The create route refuses an agent run (403
confirmation_required): a program creates through a session review (CreateCalendarEvent) or the harness'sPOST /cognition/calendar/events/create-confirmed(CreateConfirmedCalendarEvent, the SDK'scalendar.createConfirmed), never an event the user has not seen. - No provider field says whose calendar it is. An inbox syncs every calendar
its account can see under its own address, and Google gives
accessRoleownerto anyone with manage rights, on a colleague's primary calendar too; Outlook stores onlycanEdit;is_primaryis false on a person's own other calendars.VisibleCalendar::contributes_to_availabilityis the nearest signal: the user's setting, by default the primaries of inboxes they own. With meetings they attend, it is their own schedule for agents as forTeamSourceOccurrence::is_personally_busy.viewer_can.organizestays a capability, since writing a calendar lets the user act as its organizer, soEventRole::ofand the SDK'seventRolecount it only on such a calendar, andReadCalendarEventreports anything else ason_visible_calendar. Microsoft Graph names the mailbox owner as organizer on every event of a read-only calendar such as Outlook's holidays, and the normalizer turns that into an own attendee row, so both role readers give no role (notguest) for that row on a read-only event. Gate it onis_read_only, never on availability: the copy rules read the role of the copy the user organizes, which may be off availability. The entity carries its canonical copy's flag, and a writable copy outranks a read-only one, so a meeting the user organizes keeps its role when a read-only calendar shows it too. The calendar's name is what tells an agent whose it is: Google names a person's primary calendar after them or their address.domain::labelsis the one place these rules live: the agent tools readCalendarLabelsandEventRole::offrom it, and search rows, which agents read as often as occurrences, get the same answer throughCalendarEventLabelReader, which labels every hit (EventLabels::of) from one read of the requester's calendars and inboxes. Search reaches it as a trait object the host injects, so it needs no outbound code from this crate.off_schedule_summaryis the plain sentence for an event that is not the user's:ReadCalendarEventandNameSearchboth give it, because models follow it more reliably than the fields behind it. - A series Google split off another without moving it in time has the id
<parent>_R<first start>, a UID of its own and the parent'screated; a split that moved it gets an unrelated id. A change to a_Rseries' recurrence answers with a new event, new id and UID atsequence+ 1, and leaves the old id, and every later_Rslice of that parent, a cancelled tombstone Google refuses to patch (badRequest). The entity follows the UID, so the echo lands on a new entity:delete_copyretires the old id's source in the same request, or the old entity keeps every occurrence until the tombstone syncs, andtruncate_recurring_eventreads a tombstone as gone, so a delete from a copy or later slice that has not synced yet retires it too. - Copies of one meeting pair by
calendar_meeting_uid(ical_uid), not the raw UID: Exchange gives a meeting it imports from an invitation its own UID that wraps the original aftervCal-Uid, and the SQL function unwraps it, so an Outlook copy of a Google meeting pairs with its Google copies inmeeting_copies, the mention preview,event_export, the channel-shared search scope and email invitation matching (pg/invitations.rs), where an Outlook inbox's invitation card resolves to that inbox's own copy and answers as it. - Preserve the conservative OOO refresh hint on write outcomes and sync reports;
its contract is in team sharing.
Retirements carry it per event (
RetiredCalendarEvent::team_ooo_changed): only removing a source whose typedevent_typeis out of office raises it, since every sync of a removed meeting's attendees reaches their teammates' calendars and the hint blanks their overlay. - The Outlook sync (
src/domain/outlook.rs) refreshes a page's events one at a time, first pending id first, and retries that id after any error, so one error blocks the calendar. An event the adapter cannot normalize is not an error: it comes back asOutlookEventRefresh::Unreadablewith the Graph property it rejected, and the sync skips it, as Google never shows an event it cannot normalize. The event is absent: a copy stored before is retired (OutlookCalendarProgress::Unreadable), since without the calendar error Google shows beside its old copy a stale copy would look current, but its page membership stays so later tombstones resolve. The round still finishes as a clean sync. The warningskipping an Outlook event Macro cannot readand thecalendar.outlook_syncspan carrycalendar_id,provider_event_idandrejected_field. A series imports without an occurrence the adapter cannot read (OutlookEventRefresh::Refreshed'sskipped), warningskipping an Outlook occurrence Macro cannot readwith itsoccurrence_id, and the span addsskipped_occurrences. A secondary calendar has no v1.0 delta, so each of its rounds lists and reads every event again. A delta round lists only changes, so it also reads again the members with no stored copy that an olderREADER_REVISIONread (stamped incalendar_outlook_members.reader_revision, NULL from builds before it; a member found with a stored copy is stamped instead): a parser fix brings skipped events back without anyone touching them, and a skip costs no read until the event changes or the revision rises. Discovery does not fail on a mailbox time zone Macro cannot map to IANA either:OutlookDiscoverystores the account's calendars with notime_zone, which every reader treats as unknown, as it does a Google calendar's zone it cannot read (reminders and automatic declines anchor all-day dates at UTC, team availability reports the zone missing). The warningignoring an Outlook mailbox time zone Macro cannot mapand the span carryunmapped_time_zone. - A calendar's sync error reaches calendar caches only as an
UpsertCalendarchange-log entry, since they read the calendar list once and then follow the log. Google and Outlook log one when the shown error (visible_calendar_sync_error_tx, pastCALENDAR_SYNC_FAILURE_BADGE_THRESHOLDfailures) appears or is reworded (failure_changes_sync_error_badge) and when the round that clears it commits, never on a routine round (Outlook polls every two minutes). Neither nudges open clients for it, so a tab sees it on its next delta. Outlook logged none before November 2026;20261105002046_log_outlook_calendars_for_their_sync_error.sqllogs every visible Outlook calendar once so caches that missed a change refetch it. - A sync of a
ready, already synced account staysready, on Google as on Outlook, including after a re-grant that kept calendar access, whose sync tokens survive. Any other state is catching up and marks itsyncing: a first import, a retry, or a return fromdisabledorreauth_required. The web'sSyncing your calendar…banner and its 5 second poll read that state. - The team out-of-office overlay (
src/outbound/pg_team/ooo.rs) starts from the viewer's teammates and reaches sources throughcalendar_event_sources_out_of_office_idxon the source's typedevent_type. Filtering on the payload'seventTypealone makes Postgres unpack every source on every primary calendar in the tenant (about 1.8 s per call in production before October 2026).
Related
- Rules:
.agents/rules/rust/architecture.md,.agents/rules/rust/db.md