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
fix(calendar): say whose calendar a search row is on (#9264)
gbirman0d5faa192dcc
diff --git a/.sqlx/query-6cb8618f8f79bc91a9b93ebcff8ed02a8ee1edb43db4117d2ee7e199745c5197.json b/.sqlx/query-6cb8618f8f79bc91a9b93ebcff8ed02a8ee1edb43db4117d2ee7e199745c5197.jsonnew file mode 100644index 0000000000..689c852f4a--- /dev/null+++ b/.sqlx/query-6cb8618f8f79bc91a9b93ebcff8ed02a8ee1edb43db4117d2ee7e199745c5197.json@@ -0,0 +1,70 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n event.id,\n event.source_link_id,\n event.status,\n event.organizer_email,\n event.is_read_only,\n event.is_snapshot,\n event.guests_can_modify,\n event.guests_can_invite_others,\n event.guests_can_see_other_guests\n FROM calendar_events event\n WHERE event.id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "source_link_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "organizer_email",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "is_read_only",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "is_snapshot",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "guests_can_modify",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,+ "name": "guests_can_invite_others",+ "type_info": "Bool"+ },+ {+ "ordinal": 8,+ "name": "guests_can_see_other_guests",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "6cb8618f8f79bc91a9b93ebcff8ed02a8ee1edb43db4117d2ee7e199745c5197"+}diff --git a/apps/docs/AI/mcp/tools/name-search.mdx b/apps/docs/AI/mcp/tools/name-search.mdxindex 27ab5c5379..e1f44bb340 100644--- a/apps/docs/AI/mcp/tools/name-search.mdx+++ b/apps/docs/AI/mcp/tools/name-search.mdx@@ -2,12 +2,13 @@title: NameSearchdescription: >-Search items by their name or title: document name, email subject, agent- session title, channel name, project name, or call-record name.+ session title, channel name, project name, call-record name, or calendar event+ title.---# NameSearch-Search items by their name or title: document name, email subject, agent session title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as \{label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).+Search items by their name or title: document name, email subject, agent session title, channel name, project name, call-record name, or calendar event title. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as \{label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist). A calendar event result is one copy of the event on a calendar the user can see, not all of them theirs: calendarName names that calendar, contributesToAvailability says whether it is on the user's schedule, and role says whether they organize it or are a guest. A result without contributesToAvailability carries none of this, as on an event shared with them, so say you cannot tell rather than infer anything from the missing fields. Otherwise only role says the user organizes an event: organizer is whoever the provider names, which on a read-only calendar can be the user's own mailbox, so without a role tell them they do not organize it. Say "your calendar" only when contributesToAvailability is true or there is a role. Any other result is what that calendar shows, not where the user is or what they are doing, even when they ask about "my" event: never call it their appointment, trip or meeting. Say "[email protected]'s calendar has..." when calendarName shows whose it is; if it does not, say you cannot tell rather than guess.## Parametersdiff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex ed1031caab..954db90225 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -1458,6 +1458,7 @@ export const SearchToolResponse = z.object({})).optional(),+ summary: z.union([z.string(), z.null()]).optional(),}).and(z.any().superRefine((x, ctx) => {@@ -1902,6 +1903,39 @@ export const SearchToolResponse = z.object({z.null(),]).optional(),+ calendarName: z.union([z.string(), z.null()]).optional(),+ contributesToAvailability: z+ .union([z.boolean(), z.null()])+ .optional(),+ inbox: z.union([z.string(), z.null()]).optional(),+ role: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('organizer'),+ z.literal('guest'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error+ ? [...errors, result.error]+ : errors)(schema.safeParse(x)),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message:+ 'Invalid input: Should pass single schema',+ });+ }+ }),+ z.null(),+ ])+ .optional(),description: z.union([z.string(), z.null()]).optional(),}),z.null(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex ccd8b9cce9..6c49076229 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -285,6 +285,11 @@ export type TaggedSessionAwareSearchResult = {* Tags on this item visible to the user.*/tags?: AppliedTag[];+ /**+ * For a calendar event on a calendar outside the user's schedule that+ * they neither organize nor attend: says so in plain words.+ */+ summary?: string | null;} & TaggedSessionAwareSearchResult1;export type TaggedSessionAwareSearchResult1 =| (DocumentSearchResponseItemWithMetadata & {@@ -370,6 +375,10 @@ export type CalendarEventSearchTime =endDate: string;kind: 'allDay';};+/**+ * What the user is on one copy of an event, through the inbox holding it.+ */+export type CalendarEventSearchRole = 'organizer' | 'guest';/*** Side of a folded conversation.*/@@ -6829,9 +6838,33 @@ export interface CalendarEventMetadata {*/isReadOnly: boolean;/**- * The event's organizer (creator), when the source names one.+ * The organizer the provider names, when it names one.*/organizer?: CalendarEventOrganizer | null;+ /**+ * Display name of the calendar holding this copy. Absent on an event+ * shared with the user, which is on none of their calendars.+ */+ calendarName?: string | null;+ /**+ * Whether a calendar holding this copy is on the user's schedule. The+ * user can see calendars that are not theirs, such as a colleague's: a+ * row without this, and that they do not attend, says what that calendar+ * shows, not where the user is.+ */+ contributesToAvailability?: boolean | null;+ /**+ * The connected inbox syncing that calendar. It stays the user's own+ * address on a colleague's calendar, so it never says whose calendar it+ * is.+ */+ inbox?: string | null;+ /**+ * Whether the user organizes this copy or is a guest on it. Absent when+ * they are neither, when they can only write that calendar, or when a+ * read-only calendar names them organizer.+ */+ role?: CalendarEventSearchRole | null;/*** Free-text description, when the event carries one. May contain HTML from* the source; clients render a plain-text preview.@@ -6855,8 +6888,10 @@ export interface CalendarEventSearchOccurrence {time: CalendarEventSearchTime;}/**- * The event's organizer — its creator, in Google's model. Either field can be- * absent when the source does not name it.+ * The organizer the provider names on the event. Either field can be absent+ * when the source does not name it. On a read-only Outlook calendar, such as+ * its holidays, Microsoft names the mailbox owner on every event, so this+ * does not say the user organized anything: `role` does.*/export interface CalendarEventOrganizer {/**@@ -12767,7 +12802,7 @@ export interface MuteNotificationsResponse {snoozeUntil?: string | null;}/**- * Search items by their name or title: document name, email subject, agent session title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).+ * Search items by their name or title: document name, email subject, agent session title, channel name, project name, call-record name, or calendar event title. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist). A calendar event result is one copy of the event on a calendar the user can see, not all of them theirs: calendarName names that calendar, contributesToAvailability says whether it is on the user's schedule, and role says whether they organize it or are a guest. A result without contributesToAvailability carries none of this, as on an event shared with them, so say you cannot tell rather than infer anything from the missing fields. Otherwise only role says the user organizes an event: organizer is whoever the provider names, which on a read-only calendar can be the user's own mailbox, so without a role tell them they do not organize it. Say "your calendar" only when contributesToAvailability is true or there is a role. Any other result is what that calendar shows, not where the user is or what they are doing, even when they ask about "my" event: never call it their appointment, trip or meeting. Say "[email protected]'s calendar has..." when calendarName shows whose it is; if it does not, say you cannot tell rather than guess.*/export interface NameSearch {/**diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadata.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadata.tsindex f77ddd0250..0391644a74 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadata.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadata.ts@@ -4,10 +4,14 @@* search_service* OpenAPI spec version: 0.1.0*/+import type { CalendarEventMetadataCalendarName } from './calendarEventMetadataCalendarName';import type { CalendarEventMetadataConferenceUrl } from './calendarEventMetadataConferenceUrl';+import type { CalendarEventMetadataContributesToAvailability } from './calendarEventMetadataContributesToAvailability';import type { CalendarEventMetadataDescription } from './calendarEventMetadataDescription';+import type { CalendarEventMetadataInbox } from './calendarEventMetadataInbox';import type { CalendarEventMetadataOccurrence } from './calendarEventMetadataOccurrence';import type { CalendarEventMetadataOrganizer } from './calendarEventMetadataOrganizer';+import type { CalendarEventMetadataRole } from './calendarEventMetadataRole';import type { CalendarEventSearchTime } from './calendarEventSearchTime';/**@@ -18,12 +22,24 @@ should display depends on when the query ran, so it is resolved hererather than indexed.*/export interface CalendarEventMetadata {+ /** Display name of the calendar holding this copy. Absent on an event+shared with the user, which is on none of their calendars. */+ calendarName?: CalendarEventMetadataCalendarName;/** Direct conference join URL when known. */conferenceUrl?: CalendarEventMetadataConferenceUrl;+ /** Whether a calendar holding this copy is on the user's schedule. The+user can see calendars that are not theirs, such as a colleague's: a+row without this, and that they do not attend, says what that calendar+shows, not where the user is. */+ contributesToAvailability?: CalendarEventMetadataContributesToAvailability;createdAt: string;/** Free-text description, when the event carries one. May contain HTML fromthe source; clients render a plain-text preview. */description?: CalendarEventMetadataDescription;+ /** The connected inbox syncing that calendar. It stays the user's own+address on a colleague's calendar, so it never says whose calendar it+is. */+ inbox?: CalendarEventMetadataInbox;/** Whether the canonical source prohibits mutation. */isReadOnly: boolean;/** Whether the series carries a recurrence rule. Lets a row render a@@ -31,6 +47,7 @@ recurring badge without parsing the rules. */isRecurring: boolean;occurrence?: CalendarEventMetadataOccurrence;organizer?: CalendarEventMetadataOrganizer;+ role?: CalendarEventMetadataRole;/** Canonical status (`confirmed`, `tentative`, `cancelled`). */status: string;/** The series' own span. */diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataCalendarName.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataCalendarName.tsnew file mode 100644index 0000000000..093e771494--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataCalendarName.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name of the calendar holding this copy. Absent on an event+shared with the user, which is on none of their calendars.+ */+export type CalendarEventMetadataCalendarName = string | null;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataContributesToAvailability.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataContributesToAvailability.tsnew file mode 100644index 0000000000..7da70b9be8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataContributesToAvailability.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether a calendar holding this copy is on the user's schedule. The+user can see calendars that are not theirs, such as a colleague's: a+row without this, and that they do not attend, says what that calendar+shows, not where the user is.+ */+export type CalendarEventMetadataContributesToAvailability = boolean | null;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataInbox.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataInbox.tsnew file mode 100644index 0000000000..d221c22222--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataInbox.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The connected inbox syncing that calendar. It stays the user's own+address on a colleague's calendar, so it never says whose calendar it+is.+ */+export type CalendarEventMetadataInbox = string | null;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataRole.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataRole.tsnew file mode 100644index 0000000000..7ec87eeccd--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventMetadataRole.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */+import type { CalendarEventSearchRole } from './calendarEventSearchRole';++export type CalendarEventMetadataRole = null | CalendarEventSearchRole;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventOrganizer.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventOrganizer.tsindex 3f841c195c..83a8067f93 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventOrganizer.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventOrganizer.ts@@ -8,8 +8,10 @@ import type { CalendarEventOrganizerEmail } from './calendarEventOrganizerEmail'import type { CalendarEventOrganizerName } from './calendarEventOrganizerName';/**- * The event's organizer — its creator, in Google's model. Either field can be-absent when the source does not name it.+ * The organizer the provider names on the event. Either field can be absent+when the source does not name it. On a read-only Outlook calendar, such as+its holidays, Microsoft names the mailbox owner on every event, so this+does not say the user organized anything: `role` does.*/export interface CalendarEventOrganizer {/** Organizer email address, when known. */diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventSearchRole.ts b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventSearchRole.tsnew file mode 100644index 0000000000..16464cf100--- /dev/null+++ b/apps/web/src/lib/service-clients/service-search/generated/models/calendarEventSearchRole.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * What the user is on one copy of an event, through the inbox holding it.+ */+export type CalendarEventSearchRole =+ (typeof CalendarEventSearchRole)[keyof typeof CalendarEventSearchRole];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const CalendarEventSearchRole = {+ organizer: 'organizer',+ guest: 'guest',+} as const;diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts b/apps/web/src/lib/service-clients/service-search/generated/models/index.tsindex bb9b1a2e86..7e424c689b 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/index.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/index.ts@@ -15,10 +15,14 @@ export * from './calendarEventFilters';export * from './calendarEventFiltersEndsAfter';export * from './calendarEventFiltersStartsBefore';export * from './calendarEventMetadata';+export * from './calendarEventMetadataCalendarName';export * from './calendarEventMetadataConferenceUrl';+export * from './calendarEventMetadataContributesToAvailability';export * from './calendarEventMetadataDescription';+export * from './calendarEventMetadataInbox';export * from './calendarEventMetadataOccurrence';export * from './calendarEventMetadataOrganizer';+export * from './calendarEventMetadataRole';export * from './calendarEventOrganizer';export * from './calendarEventOrganizerEmail';export * from './calendarEventOrganizerName';@@ -30,6 +34,7 @@ export * from './calendarEventSearchResponseItemWithMetadataAllOfMetadata';export * from './calendarEventSearchResponseItemWithMetadataAllOfProperties';export * from './calendarEventSearchResult';export * from './calendarEventSearchResultScore';+export * from './calendarEventSearchRole';export * from './calendarEventSearchScope';export * from './calendarEventSearchTime';export * from './calendarEventSearchTimeOneOf';diff --git a/apps/web/src/lib/service-clients/service-search/openapi.json b/apps/web/src/lib/service-clients/service-search/openapi.jsonindex b770b97847..b1c5c04691 100644--- a/apps/web/src/lib/service-clients/service-search/openapi.json+++ b/apps/web/src/lib/service-clients/service-search/openapi.json@@ -335,10 +335,18 @@"isReadOnly"],"properties": {+ "calendarName": {+ "type": ["string", "null"],+ "description": "Display name of the calendar holding this copy. Absent on an event\nshared with the user, which is on none of their calendars."+ },"conferenceUrl": {"type": ["string", "null"],"description": "Direct conference join URL when known."},+ "contributesToAvailability": {+ "type": ["boolean", "null"],+ "description": "Whether a calendar holding this copy is on the user's schedule. The\nuser can see calendars that are not theirs, such as a colleague's: a\nrow without this, and that they do not attend, says what that calendar\nshows, not where the user is."+ },"createdAt": {"type": "string","format": "date-time"@@ -347,6 +355,10 @@"type": ["string", "null"],"description": "Free-text description, when the event carries one. May contain HTML from\nthe source; clients render a plain-text preview."},+ "inbox": {+ "type": ["string", "null"],+ "description": "The connected inbox syncing that calendar. It stays the user's own\naddress on a colleague's calendar, so it never says whose calendar it\nis."+ },"isReadOnly": {"type": "boolean","description": "Whether the canonical source prohibits mutation."@@ -373,7 +385,18 @@},{"$ref": "#/components/schemas/CalendarEventOrganizer",- "description": "The event's organizer (creator), when the source names one."+ "description": "The organizer the provider names, when it names one."+ }+ ]+ },+ "role": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CalendarEventSearchRole",+ "description": "Whether the user organizes this copy or is a guest on it. Absent when\nthey are neither, when they can only write that calendar, or when a\nread-only calendar names them organizer."}]},@@ -393,7 +416,7 @@},"CalendarEventOrganizer": {"type": "object",- "description": "The event's organizer — its creator, in Google's model. Either field can be\nabsent when the source does not name it.",+ "description": "The organizer the provider names on the event. Either field can be absent\nwhen the source does not name it. On a read-only Outlook calendar, such as\nits holidays, Microsoft names the mailbox owner on every event, so this\ndoes not say the user organized anything: `role` does.","properties": {"email": {"type": ["string", "null"],@@ -504,6 +527,11 @@}}},+ "CalendarEventSearchRole": {+ "type": "string",+ "description": "What the user is on one copy of an event, through the inbox holding it.",+ "enum": ["organizer", "guest"]+ },"CalendarEventSearchScope": {"type": "string","description": "Which calendar events a unified search covers.\n\nSharing an event with a channel lets its members see the sharer's copy,\nwhich is on none of their own calendars, so the default scope never finds\nit. Shared events are a separate scope rather than part of the default, so\na caller can list them after the caller's own events without reordering\nthose.",diff --git a/crates/ai_tools/src/search/search_service/name.rs b/crates/ai_tools/src/search/search_service/name.rsindex 7eac82a066..5b3cf95f92 100644--- a/crates/ai_tools/src/search/search_service/name.rs+++ b/crates/ai_tools/src/search/search_service/name.rs@@ -18,7 +18,7 @@ use serde::Deserialize;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their name or title: document name, email subject, agent session title, channel name, project name, or call-record name. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist).",+ description = "Search items by their name or title: document name, email subject, agent session title, channel name, project name, call-record name, or calendar event title. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed title/name. Use this for targeted name/title lookup, not for activity-summary questions like \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; those should start with ListEntities using time/type/channel filters. For emails, whitespace-separated terms are ANDed and each is a prefix match against the subject. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the title, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion. Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches (NameSearch for the person, ContentSearch for the topic) rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, projects, and call records include the tags visible to the user as {label, scope} pairs; to restrict a search to tagged items, pass the tag labels in the tags argument (ListTags shows which tags exist). A calendar event result is one copy of the event on a calendar the user can see, not all of them theirs: calendarName names that calendar, contributesToAvailability says whether it is on the user's schedule, and role says whether they organize it or are a guest. A result without contributesToAvailability carries none of this, as on an event shared with them, so say you cannot tell rather than infer anything from the missing fields. Otherwise only role says the user organizes an event: organizer is whoever the provider names, which on a read-only calendar can be the user's own mailbox, so without a role tell them they do not organize it. Say \"your calendar\" only when contributesToAvailability is true or there is a role. Any other result is what that calendar shows, not where the user is or what they are doing, even when they ask about \"my\" event: never call it their appointment, trip or meeting. Say \"[email protected]'s calendar has...\" when calendarName shows whose it is; if it does not, say you cannot tell rather than guess.",title = "NameSearch")]pub struct NameSearch {diff --git a/crates/ai_tools/src/search/search_service/types.rs b/crates/ai_tools/src/search/search_service/types.rsindex b6b69a0292..1901486013 100644--- a/crates/ai_tools/src/search/search_service/types.rs+++ b/crates/ai_tools/src/search/search_service/types.rs@@ -1,4 +1,5 @@use ai_toolset::{ToolCallError, ToolResult};+use calendar_events::domain::labels::off_schedule_summary;use item_filters::TagFilterMode;use models_properties::DataType;use models_properties::service::property_value::PropertyValue;@@ -117,6 +118,10 @@ pub struct TaggedSessionAwareSearchResult {/// Tags on this item visible to the user.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub tags: Vec<AppliedTag>,+ /// For a calendar event on a calendar outside the user's schedule that+ /// they neither organize nor attend: says so in plain words.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub summary: Option<String>,}#[derive(Serialize, Deserialize, Debug, JsonSchema)]@@ -214,14 +219,27 @@ pub(super) async fn annotate_result_tags(}props.retain(|p| p.definition.data_type != DataType::Tag);}+ let summary = calendar_event_summary(&item);Some(TaggedSessionAwareSearchResult {item: SessionAwareSearchResult::from_unified(item)?,tags,+ summary,})}).collect())}+/// The sentence for a result known to be off the user's schedule. Missing+/// labels say nothing about whose calendar it is, so they get none.+fn calendar_event_summary(item: &UnifiedSearchResponseItem) -> Option<String> {+ let UnifiedSearchResponseItem::CalendarEvent(event) = item else {+ return None;+ };+ let metadata = event.metadata.as_ref()?;+ (metadata.contributes_to_availability == Some(false) && metadata.role.is_none())+ .then(|| off_schedule_summary(&event.extra.name, metadata.calendar_name.as_deref()))+}+async fn fetch_caller_tag_sets(context: &SearchToolContext,user_id: &str,diff --git a/crates/ai_tools/src/search/search_service/types/test.rs b/crates/ai_tools/src/search/search_service/types/test.rsindex d6080e7b8f..81ad098613 100644--- a/crates/ai_tools/src/search/search_service/types/test.rs+++ b/crates/ai_tools/src/search/search_service/types/test.rs@@ -1,4 +1,8 @@use super::*;+use models_search::calendar_event::{+ CalendarEventMetadata, CalendarEventSearchResponseItem,+ CalendarEventSearchResponseItemWithMetadata, CalendarEventSearchRole, CalendarEventSearchTime,+};#[test]fn searches_include_sessions_by_default_and_never_include_legacy_chats() {@@ -19,3 +23,102 @@ fn searches_include_sessions_by_default_and_never_include_legacy_chats() {);assert!(serde_json::from_str::<SearchEntityType>("\"chats\"").is_err());}++fn calendar_hit(+ contributes_to_availability: Option<bool>,+ role: Option<CalendarEventSearchRole>,+) -> UnifiedSearchResponseItem {+ let at = chrono::DateTime::UNIX_EPOCH;+ UnifiedSearchResponseItem::CalendarEvent(CalendarEventSearchResponseItemWithMetadata {+ metadata: Some(CalendarEventMetadata {+ created_at: at,+ updated_at: at,+ status: "confirmed".to_string(),+ time: CalendarEventSearchTime::Timed {+ starts_at: at,+ ends_at: at,+ time_zone: None,+ },+ is_recurring: false,+ occurrence: None,+ conference_url: None,+ is_read_only: false,+ organizer: None,+ calendar_name: contributes_to_availability.map(|_| "[email protected]".to_string()),+ contributes_to_availability,+ inbox: None,+ role,+ description: None,+ }),+ properties: None,+ extra: CalendarEventSearchResponseItem {+ id: uuid::Uuid::nil(),+ name: "Dentist".to_string(),+ owner_id: "macro|[email protected]".to_string(),+ updated_at: at,+ created_at: at,+ calendar_event_search_results: Vec::new(),+ },+ })+}++/// Models answered "your appointment" from the row's fields and never from+/// this sentence, so a result that is not the user's has to carry it.+#[test]+fn a_result_off_the_schedule_says_so_in_plain_words() {+ let summary = calendar_event_summary(&calendar_hit(Some(false), None)).expect("a summary");+ assert!(+ summary.starts_with("Dentist is on [email protected],"),+ "{summary}"+ );+ assert!(summary.contains("not part of their schedule"), "{summary}");+}++#[test]+fn a_result_that_is_the_users_needs_no_summary() {+ assert_eq!(+ calendar_event_summary(&calendar_hit(Some(true), None)),+ None+ );+ for role in [+ CalendarEventSearchRole::Organizer,+ CalendarEventSearchRole::Guest,+ ] {+ assert_eq!(+ calendar_event_summary(&calendar_hit(Some(false), Some(role))),+ None,+ "they attend it wherever the copy sits"+ );+ }+}++/// A label read can fail, and a channel share is on none of the user's+/// calendars: neither may read as someone else's calendar.+#[test]+fn missing_labels_are_not_read_as_a_negative() {+ assert_eq!(calendar_event_summary(&calendar_hit(None, None)), None);+}++#[test]+fn the_summary_sits_beside_the_result_and_stays_off_when_absent() {+ let item = SessionAwareSearchResult::from_unified(calendar_hit(Some(false), None))+ .expect("a calendar result");+ let row = serde_json::to_value(TaggedSessionAwareSearchResult {+ item,+ tags: Vec::new(),+ summary: Some("Dentist is on a calendar.".to_string()),+ })+ .expect("serializes");+ assert_eq!(row["summary"], "Dentist is on a calendar.");+ assert_eq!(row["type"], "calendarEvent");++ let item = SessionAwareSearchResult::from_unified(calendar_hit(Some(true), None))+ .expect("a calendar result");+ let row = serde_json::to_value(TaggedSessionAwareSearchResult {+ item,+ tags: Vec::new(),+ summary: None,+ })+ .expect("serializes");+ assert!(row.get("summary").is_none());+}diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 95bd9163ed..b454f14634 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -313,7 +313,7 @@ reminder dispatch, team availability, and provider/Postgres persistence.With meetings they attend, it is their own schedule for agents as for`TeamSourceOccurrence::is_personally_busy`. `viewer_can.organize` stays acapability, since writing a calendar lets the user act as its organizer, so- `ToolEventRole::of` and the SDK's `eventRole` count it only on such a+ `EventRole::of` and the SDK's `eventRole` count it only on such acalendar, and `ReadCalendarEvent` reports anything else as`on_visible_calendar`. Microsoft Graph names the mailbox owner as organizeron every event of a read-only calendar such as Outlook's holidays, and the@@ -324,7 +324,16 @@ reminder dispatch, team availability, and provider/Postgres persistence.its canonical copy's flag, and a writable copy outranks a read-only one, soa meeting the user organizes keeps its role when a read-only calendar showsit 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.+ a person's primary calendar after them or their address. `domain::labels` is+ the one place these rules live: the agent tools read `CalendarLabels` and+ `EventRole::of` from it, and search rows, which agents read as often as+ occurrences, get the same answer through `CalendarEventLabelReader`, 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_summary` is the+ plain sentence for an event that is not the user's: `ReadCalendarEvent` and+ `NameSearch` both give it, because models follow it more reliably than the+ fields behind it.- Copies of one meeting pair by `calendar_meeting_uid(ical_uid)`, not the rawUID: Exchange gives a meeting it imports from an invitation its own UID thatwraps the original after `vCal-Uid`, and the SQL function unwraps it, so andiff --git a/crates/calendar_events/src/domain/capabilities.rs b/crates/calendar_events/src/domain/capabilities.rsindex 5c38d299fb..577d106762 100644--- a/crates/calendar_events/src/domain/capabilities.rs+++ b/crates/calendar_events/src/domain/capabilities.rs@@ -126,10 +126,8 @@ impl ViewerCapabilities {/// needs the inbox's own attendee row, since that is the row the answer/// is written to.pub fn for_event(event: &CalendarEvent, inbox: Option<&OwnedInbox>) -> Self {- if event.status == EventStatus::Cancelled {- return Self::NONE;- }- Self::for_access(+ Self::for_copy(+ event.status,EventAccess {is_read_only: event.is_read_only,organizer_email: event.organizer_email.as_deref(),@@ -141,6 +139,19 @@ impl ViewerCapabilities {)}+ /// Resolve what the owner of `inbox` may do with a copy of an event in+ /// `status`; see [`Self::for_event`].+ pub fn for_copy(+ status: EventStatus,+ access: EventAccess<'_>,+ inbox: Option<&OwnedInbox>,+ ) -> Self {+ if status == EventStatus::Cancelled {+ return Self::NONE;+ }+ Self::for_access(access, inbox)+ }+/// Resolve what the owner of `inbox` may do with a live copy of an/// event; see [`Self::for_event`].pub fn for_access(access: EventAccess<'_>, inbox: Option<&OwnedInbox>) -> Self {diff --git a/crates/calendar_events/src/domain/labels.rs b/crates/calendar_events/src/domain/labels.rsnew file mode 100644index 0000000000..81f11a0209--- /dev/null+++ b/crates/calendar_events/src/domain/labels.rs@@ -0,0 +1,223 @@+//! What says whose calendar an event is on, and what the user is there.+//!+//! Every reader that shows an event to an agent labels it through this module,+//! so a search row and an occurrence of one event cannot disagree.++use std::collections::HashMap;++use uuid::Uuid;++use super::{+ capabilities::{EventAccess, GuestPolicy, ViewerCapabilities},+ models::{ActorInboxes, CalendarAttendee, CalendarEvent, EventStatus, VisibleCalendar},+ ports::CalendarMutationService,+};++/// What the user is on one copy of an event, through the inbox holding it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum EventRole {+ /// The inbox organizes the event, or the event has no guests and is the+ /// user's own.+ Organizer,+ /// The inbox is invited to the event.+ Guest,+}++impl EventRole {+ /// The role of the copy's inbox, read the way clients read it: only the+ /// copy's own inbox row is `is_self`. That row marked organizer counts+ /// only on a copy the user can change, since Microsoft Graph names the+ /// mailbox owner as organizer on every event of a read-only calendar.+ /// `organize` says they may act as organizer, which writing someone+ /// else's calendar grants too, so it counts only on a calendar of their+ /// own schedule with no other organizer listed.+ pub fn of(+ attendees: &[CalendarAttendee],+ is_read_only: bool,+ viewer_can: ViewerCapabilities,+ on_schedule: Option<bool>,+ ) -> Option<Self> {+ let own_row = attendees.iter().find(|attendee| attendee.is_self);+ if own_row.is_some_and(|attendee| attendee.is_organizer) {+ return (!is_read_only).then_some(Self::Organizer);+ }+ let other_organizer = attendees.iter().any(|attendee| attendee.is_organizer);+ if viewer_can.organize && !other_organizer && on_schedule == Some(true) {+ return Some(Self::Organizer);+ }+ own_row.map(|_| Self::Guest)+ }+}++/// The calendars the user can see, to name the calendar and inbox each+/// event copy belongs to.+#[derive(Default)]+pub struct CalendarLabels {+ by_calendar: HashMap<Uuid, VisibleCalendar>,+ inbox_by_link: HashMap<Uuid, String>,+}++impl CalendarLabels {+ /// Load the requester's visible calendars. Labels only describe a result,+ /// so a failure leaves them out rather than failing a call whose change+ /// may already have reached the provider.+ pub async fn load<M: CalendarMutationService>(mutations: &M, requester_id: &str) -> Self {+ let Ok(calendars) = mutations+ .list_visible_calendars(requester_id)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "failed to load calendar names for a tool result");+ })+ else {+ return Self::default();+ };+ Self::from_calendars(calendars)+ }++ /// Labels from calendars the tool already listed.+ pub fn from_calendars(calendars: Vec<VisibleCalendar>) -> Self {+ let inbox_by_link = calendars+ .iter()+ .map(|calendar| (calendar.email_link_id, calendar.email_address.clone()))+ .collect();+ let by_calendar = calendars+ .into_iter()+ .map(|calendar| (calendar.id, calendar))+ .collect();+ Self {+ by_calendar,+ inbox_by_link,+ }+ }++ /// Display name of a calendar the user can see.+ pub fn calendar_name(&self, calendar_id: Option<Uuid>) -> Option<String> {+ calendar_id+ .and_then(|id| self.by_calendar.get(&id))+ .map(|calendar| calendar.name.clone())+ }++ /// Whether any of these calendars counts toward the user's busy time,+ /// when one is known. Availability counts each copy of an event, so one+ /// copy on the user's schedule is enough.+ pub fn on_schedule(&self, calendar_ids: impl IntoIterator<Item = Uuid>) -> Option<bool> {+ calendar_ids+ .into_iter()+ .filter_map(|id| self.by_calendar.get(&id))+ .map(|calendar| calendar.contributes_to_availability)+ .reduce(|left, right| left || right)+ }++ /// Whether a calendar holding this event is on the user's schedule.+ pub fn event_on_schedule(&self, event: &CalendarEvent) -> Option<bool> {+ let copies = event.sources.iter().map(|copy| copy.calendar_id);+ self.on_schedule(event.calendar_id.into_iter().chain(copies))+ }++ /// The inbox holding a copy: its calendar's inbox, else the inbox whose+ /// grant backs it.+ pub fn inbox(&self, calendar_id: Option<Uuid>, link_id: Option<Uuid>) -> Option<String> {+ calendar_id+ .and_then(|id| self.by_calendar.get(&id))+ .map(|calendar| calendar.email_address.clone())+ .or_else(|| link_id.and_then(|id| self.inbox_by_link.get(&id)).cloned())+ }++ /// The user's role on an event already marked for them.+ pub fn role(&self, event: &CalendarEvent) -> Option<EventRole> {+ EventRole::of(+ &event.attendees,+ event.is_read_only,+ event.viewer_can,+ self.event_on_schedule(event),+ )+ }+}++/// Says in plain words that an event is not the user's. Models follow this+/// sentence more reliably than the fields behind it, so every agent surface+/// showing such an event gives it.+pub fn off_schedule_summary(title: &str, calendar_name: Option<&str>) -> String {+ format!(+ "{title} is on {}, which the user can see but which is not part of their schedule and \+ may be someone else's.",+ calendar_name.unwrap_or("a calendar"),+ )+}++/// One copy of an event, as much of it as labelling reads.+#[derive(Debug, Clone)]+pub struct EventCopy {+ /// The event.+ pub event_id: Uuid,+ /// The inbox the copy syncs through.+ pub link_id: Uuid,+ /// Event status.+ pub status: EventStatus,+ /// The organizer's email.+ pub organizer_email: Option<String>,+ /// Whether the copy's calendar prohibits editing it.+ pub is_read_only: bool,+ /// Whether the copy is a snapshot of a shared meeting.+ pub is_snapshot: bool,+ /// What the organizer lets guests do.+ pub guest_policy: GuestPolicy,+ /// The stored guest list.+ pub attendees: Vec<CalendarAttendee>,+ /// The calendars holding the copy, the one its event reports first.+ pub calendar_ids: Vec<Uuid>,+}++/// How one event reads for the requester, to say whose calendar it is on.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct EventLabels {+ /// Display name of the calendar, when it is one the user can see.+ pub calendar_name: Option<String>,+ /// Whether a calendar holding the event is on the user's schedule, when+ /// one is known.+ pub contributes_to_availability: Option<bool>,+ /// The connected inbox syncing the calendar. It stays the user's own+ /// address on a colleague's calendar, so it never says whose it is.+ pub inbox: Option<String>,+ /// What the user is on this copy, if anything.+ pub role: Option<EventRole>,+}++impl EventLabels {+ /// Label a copy for the requester `viewer` describes, the way+ /// [`ActorInboxes::mark_event`] and [`CalendarLabels::role`] read a loaded+ /// event. Stored `is_self` flags belong to the inbox that synced the copy,+ /// so a requester with no inbox of their own has no role on any of them.+ pub fn of(+ mut copy: EventCopy,+ viewer: Option<&ActorInboxes>,+ calendars: &CalendarLabels,+ ) -> Self {+ let calendar_id = copy.calendar_ids.first().copied();+ let on_schedule = calendars.on_schedule(copy.calendar_ids.iter().copied());+ let role = viewer.and_then(|viewer| {+ viewer.mark_attendees(&mut copy.attendees, copy.link_id);+ let viewer_can = ViewerCapabilities::for_copy(+ copy.status,+ EventAccess {+ is_read_only: copy.is_read_only,+ organizer_email: copy.organizer_email.as_deref(),+ attendees: ©.attendees,+ guest_policy: copy.guest_policy,+ is_snapshot: copy.is_snapshot,+ },+ viewer.inbox(copy.link_id),+ );+ EventRole::of(©.attendees, copy.is_read_only, viewer_can, on_schedule)+ });+ Self {+ calendar_name: calendars.calendar_name(calendar_id),+ contributes_to_availability: on_schedule,+ inbox: calendars.inbox(calendar_id, None),+ role,+ }+ }+}++#[cfg(test)]+mod test;diff --git a/crates/calendar_events/src/domain/labels/test.rs b/crates/calendar_events/src/domain/labels/test.rsnew file mode 100644index 0000000000..d56688e737--- /dev/null+++ b/crates/calendar_events/src/domain/labels/test.rs@@ -0,0 +1,223 @@+use super::*;+use crate::domain::models::{+ AttendeeResponseStatus, CalendarCapabilities, CalendarProvider, OwnedInbox,+};++const INBOX: &str = "[email protected]";+const COLLEAGUE: &str = "[email protected]";+const LINK: Uuid = Uuid::from_u128(1);+const OWN: Uuid = Uuid::from_u128(10);+const COLLEAGUES: Uuid = Uuid::from_u128(11);+const HOLIDAYS: Uuid = Uuid::from_u128(12);++fn calendar(id: Uuid, name: &str, on_schedule: bool) -> VisibleCalendar {+ VisibleCalendar {+ provider: CalendarProvider::Google,+ capabilities: CalendarCapabilities::google(),+ id,+ email_link_id: LINK,+ email_address: INBOX.to_string(),+ name: name.to_string(),+ color: None,+ is_primary: id == OWN,+ is_writable: id != HOLIDAYS,+ is_subscription: false,+ contributes_to_availability: on_schedule,+ sync_error: None,+ default_reminders: Vec::new(),+ }+}++fn calendars() -> CalendarLabels {+ CalendarLabels::from_calendars(vec![+ calendar(OWN, INBOX, true),+ calendar(COLLEAGUES, COLLEAGUE, false),+ calendar(HOLIDAYS, "United States holidays", false),+ ])+}++/// The owner of `INBOX`, who can write the colleague's calendar as an inbox+/// with manage rights there can.+fn viewer() -> ActorInboxes {+ ActorInboxes::from_owned(vec![OwnedInbox {+ link_id: LINK,+ email: INBOX.to_string(),+ provider: CalendarProvider::Google,+ writable_calendar_ids: vec![INBOX.to_string(), COLLEAGUE.to_string()],+ }])+ .expect("one inbox")+}++/// A guest row with the `is_self` Google sync stores for the inbox it synced+/// through, which says nothing about whoever reads the row later.+fn attendee(email: &str, is_organizer: bool) -> CalendarAttendee {+ CalendarAttendee {+ email: email.to_string(),+ display_name: None,+ response_status: AttendeeResponseStatus::Accepted,+ is_organizer,+ is_optional: false,+ is_self: true,+ comment: None,+ }+}++fn copy(calendar_id: Uuid, organizer: &str, attendees: Vec<CalendarAttendee>) -> EventCopy {+ EventCopy {+ event_id: Uuid::from_u128(7),+ link_id: LINK,+ status: EventStatus::Confirmed,+ organizer_email: Some(organizer.to_string()),+ is_read_only: false,+ is_snapshot: false,+ guest_policy: GuestPolicy::default(),+ attendees,+ calendar_ids: vec![calendar_id],+ }+}++#[test]+fn a_colleagues_calendar_says_so_and_gives_no_role() {+ let solo = EventLabels::of(+ copy(COLLEAGUES, COLLEAGUE, Vec::new()),+ Some(&viewer()),+ &calendars(),+ );+ assert_eq!(+ solo,+ EventLabels {+ calendar_name: Some(COLLEAGUE.to_string()),+ contributes_to_availability: Some(false),+ inbox: Some(INBOX.to_string()),+ role: None,+ },+ "writing their calendar makes the user neither organizer nor guest"+ );++ let meeting = copy(COLLEAGUES, COLLEAGUE, vec![attendee(COLLEAGUE, true)]);+ assert_eq!(+ EventLabels::of(meeting, Some(&viewer()), &calendars()).role,+ None,+ "their meeting, seen on their calendar"+ );+}++/// Microsoft Graph names the mailbox owner as organizer on every event of a+/// read-only calendar such as Outlook's holidays.+#[test]+fn a_read_only_calendar_naming_the_user_gives_no_role() {+ let holiday = EventCopy {+ is_read_only: true,+ ..copy(HOLIDAYS, INBOX, vec![attendee(INBOX, true)])+ };+ assert_eq!(+ EventLabels::of(holiday, Some(&viewer()), &calendars()),+ EventLabels {+ calendar_name: Some("United States holidays".to_string()),+ contributes_to_availability: Some(false),+ inbox: Some(INBOX.to_string()),+ role: None,+ },+ );+}++#[test]+fn a_real_organizer_and_guest_keep_their_roles() {+ let organized = copy(+ OWN,+ INBOX,+ vec![attendee(INBOX, true), attendee(COLLEAGUE, false)],+ );+ assert_eq!(+ EventLabels::of(organized, Some(&viewer()), &calendars()).role,+ Some(EventRole::Organizer)+ );++ let invited = copy(+ OWN,+ COLLEAGUE,+ vec![attendee(COLLEAGUE, true), attendee(INBOX, false)],+ );+ assert_eq!(+ EventLabels::of(invited, Some(&viewer()), &calendars()).role,+ Some(EventRole::Guest)+ );++ assert_eq!(+ EventLabels::of(copy(OWN, INBOX, Vec::new()), Some(&viewer()), &calendars()).role,+ Some(EventRole::Organizer),+ "an own event without guests"+ );+}++/// The copy rules add guests from the copy the user organizes, so that copy+/// keeps its role off availability, as it does for the calendar tools.+#[test]+fn an_organizer_row_counts_off_availability() {+ let off = CalendarLabels::from_calendars(vec![calendar(OWN, INBOX, false)]);+ let organized = copy(OWN, INBOX, vec![attendee(INBOX, true)]);+ let labels = EventLabels::of(organized, Some(&viewer()), &off);+ assert_eq!(labels.contributes_to_availability, Some(false));+ assert_eq!(labels.role, Some(EventRole::Organizer));+}++#[test]+fn one_copy_on_the_schedule_is_enough() {+ let both = EventCopy {+ calendar_ids: vec![COLLEAGUES, OWN],+ ..copy(COLLEAGUES, COLLEAGUE, Vec::new())+ };+ let labels = EventLabels::of(both, Some(&viewer()), &calendars());+ assert_eq!(labels.contributes_to_availability, Some(true));+ assert_eq!(+ labels.calendar_name.as_deref(),+ Some(COLLEAGUE),+ "the row names the copy its event reports first"+ );+}++/// A channel share is someone else's copy on none of the reader's calendars,+/// so nothing about it may read as theirs.+#[test]+fn a_copy_on_none_of_their_calendars_says_nothing() {+ let shared = EventCopy {+ link_id: Uuid::from_u128(2),+ ..copy(+ Uuid::from_u128(99),+ COLLEAGUE,+ vec![attendee(COLLEAGUE, true)],+ )+ };+ assert_eq!(+ EventLabels::of(shared.clone(), Some(&viewer()), &calendars()),+ EventLabels::default()+ );+ assert_eq!(+ EventLabels::of(shared, None, &calendars()),+ EventLabels::default(),+ "the sharer's stored row is not the reader's, with or without an inbox"+ );+}++#[test]+fn a_cancelled_copy_gives_no_organizer_capability() {+ let cancelled = EventCopy {+ status: EventStatus::Cancelled,+ ..copy(OWN, INBOX, Vec::new())+ };+ assert_eq!(+ EventLabels::of(cancelled, Some(&viewer()), &calendars()).role,+ None+ );+}++#[test]+fn a_requester_with_no_inbox_of_their_own_gets_no_role() {+ let labels = EventLabels::of(+ copy(OWN, INBOX, vec![attendee(INBOX, true)]),+ None,+ &calendars(),+ );+ assert_eq!(labels.calendar_name.as_deref(), Some(INBOX));+ assert_eq!(labels.role, None);+}diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rsindex f30f2502d0..8a92e4fe7e 100644--- a/crates/calendar_events/src/domain/mod.rs+++ b/crates/calendar_events/src/domain/mod.rs@@ -17,6 +17,8 @@ pub mod events;pub mod ics;/// Asking to join a calendar event shared with a channel.pub mod join_requests;+/// What says whose calendar an event is on, and what the user is there.+pub mod labels;/// Macro meeting links carried by calendar events.pub mod meeting_links;/// Domain models.diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rsindex 56d0717cb9..3dd631a2dd 100644--- a/crates/calendar_events/src/domain/mutations/test.rs+++ b/crates/calendar_events/src/domain/mutations/test.rs@@ -595,6 +595,13 @@ impl CalendarRepository for FakeRepo {Ok(None)}+ async fn event_copies(+ &self,+ _event_ids: &[Uuid],+ ) -> Result<Vec<crate::domain::labels::EventCopy>, rootcause::Report> {+ Ok(Vec::new())+ }+async fn owned_inboxes(&self,_requester_id: &str,diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rsindex 858dfd8127..7d91f4fbe9 100644--- a/crates/calendar_events/src/domain/ports.rs+++ b/crates/calendar_events/src/domain/ports.rs@@ -1,8 +1,10 @@//! Ports implemented by calendar adapters.+use std::collections::HashMap;use std::future::Future;use chrono::{DateTime, Utc};+use futures::future::BoxFuture;use rootcause::Report;use uuid::Uuid;@@ -12,6 +14,7 @@ use super::ics::{IcsParticipant,};use super::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};+use super::labels::{EventCopy, EventLabels};use super::meeting_links::{CreateEventWithMacroCallError, MeetingLink, MeetingLinkError, MeetingLinkRequest,};@@ -436,6 +439,20 @@ pub trait CalendarCopyConfirmation: Send + Sync + 'static {) -> impl Future<Output = Result<Option<CopyRefusal>, CalendarMutationError>> + Send;}+/// Inbound service port labelling events for a reader outside the calendar,+/// such as search. Those readers hold it as a trait object, so it boxes its+/// future.+pub trait CalendarEventLabelReader: Send + Sync + 'static {+ /// How each of `event_ids` reads for the requester. A caller resolves who+ /// may see them first; an event that is on none of the requester's+ /// calendars comes back with nothing to say.+ fn event_labels<'a>(+ &'a self,+ requester_id: &'a str,+ event_ids: &'a [Uuid],+ ) -> BoxFuture<'a, Result<HashMap<Uuid, EventLabels>, Report>>;+}+/// Inbound service port for querying calendar occurrence projections.pub trait CalendarOccurrenceService: Send + Sync + 'static {/// Return occurrences visible to a requester in a bounded viewport.@@ -859,6 +876,13 @@ pub trait CalendarRepository: Send + Sync + 'static {requester_id: &str,) -> impl Future<Output = Result<Option<String>, Report>> + Send;+ /// The copies `event_ids` name, whoever asks: a caller resolves who may+ /// see them first. An id with no event is absent.+ fn event_copies(+ &self,+ event_ids: &[Uuid],+ ) -> impl Future<Output = Result<Vec<EventCopy>, Report>> + Send;+/// Every connected inbox the requester owns/// (`email_links.macro_id = requester`). Raw and unnormalized;/// [`ActorInboxes::from_owned`] is the single normalization point.diff --git a/crates/calendar_events/src/domain/service.rs b/crates/calendar_events/src/domain/service.rsindex e65606e36f..b73c00fb66 100644--- a/crates/calendar_events/src/domain/service.rs+++ b/crates/calendar_events/src/domain/service.rs@@ -1,7 +1,9 @@//! Calendar business policy.+use std::collections::HashMap;+use chrono::Utc;-use futures::future::{Either, select};+use futures::future::{BoxFuture, Either, select};use rootcause::Report;use uuid::Uuid;@@ -13,6 +15,7 @@ use super::{CalendarEventExportAccess, CalendarEventForward, CalendarEventForwardKind,CalendarEventIcs, IcsParticipant, IcsPurpose, render_event_ics,},+ labels::{CalendarLabels, EventLabels},models::{ActorInboxes, AppliedGoogleGrant, CalendarBackfillClaim,CalendarBackfillFailureDisposition, CalendarBackfillFailureOutcome, CalendarBackfillJobKey,@@ -21,10 +24,10 @@ use super::{},ports::{CalendarBackfillRepository, CalendarEventChange, CalendarEventForwardSource,- CalendarEventWrite, CalendarEventWriteOutcome, CalendarOccurrenceService,- CalendarProviderError, CalendarProviderErrorKind, CalendarReauthNotifier,- CalendarRepository, GoogleCalendarProvider, GoogleCalendarSyncRepository,- GoogleEventSyncContext, RetiredCalendarEvent,+ CalendarEventLabelReader, CalendarEventWrite, CalendarEventWriteOutcome,+ CalendarOccurrenceService, CalendarProviderError, CalendarProviderErrorKind,+ CalendarReauthNotifier, CalendarRepository, GoogleCalendarProvider,+ GoogleCalendarSyncRepository, GoogleEventSyncContext, RetiredCalendarEvent,},};@@ -122,6 +125,40 @@ whereOk(rows)}+ /// Label events for a reader outside the calendar: one read of the+ /// requester's calendars and inboxes, whatever the number of events.+ #[tracing::instrument(+ name = "calendar.event_labels",+ skip(self, requester_id, event_ids),+ fields(event_count = event_ids.len()),+ err+ )]+ pub async fn event_labels(+ &self,+ requester_id: &str,+ event_ids: &[Uuid],+ ) -> Result<HashMap<Uuid, EventLabels>, Report> {+ if event_ids.is_empty() {+ return Ok(HashMap::new());+ }+ // One read at a time: search runs this on every keystroke with calendar+ // hits, and a burst of searches must not fan out across the read pool.+ let copies = self.repository.event_copies(event_ids).await?;+ let calendars = CalendarLabels::from_calendars(+ self.repository.list_visible_calendars(requester_id).await?,+ );+ let viewer = ActorInboxes::from_owned(self.repository.owned_inboxes(requester_id).await?);+ Ok(copies+ .into_iter()+ .map(|copy| {+ (+ copy.event_id,+ EventLabels::of(copy, viewer.as_ref(), &calendars),+ )+ })+ .collect())+ }+/// Query teammates' out-of-office occurrences in a bounded viewport.////// Busy-only sharers' occurrences carry no title; only explicit detail@@ -340,6 +377,19 @@ where}}+impl<R> CalendarEventLabelReader for CalendarService<R>+where+ R: CalendarRepository,+{+ fn event_labels<'a>(+ &'a self,+ requester_id: &'a str,+ event_ids: &'a [Uuid],+ ) -> BoxFuture<'a, Result<HashMap<Uuid, EventLabels>, Report>> {+ Box::pin(CalendarService::event_labels(self, requester_id, event_ids))+ }+}+impl<R> CalendarOccurrenceService for CalendarService<R>whereR: CalendarRepository,diff --git a/crates/calendar_events/src/domain/service/test.rs b/crates/calendar_events/src/domain/service/test.rsindex b3de729c20..e5ffeb8f71 100644--- a/crates/calendar_events/src/domain/service/test.rs+++ b/crates/calendar_events/src/domain/service/test.rs@@ -241,6 +241,13 @@ impl CalendarRepository for FakeRepo {Ok(None)}+ async fn event_copies(+ &self,+ _event_ids: &[Uuid],+ ) -> Result<Vec<crate::domain::labels::EventCopy>, Report> {+ Ok(Vec::new())+ }+async fn owned_inboxes(&self,_requester_id: &str,diff --git a/crates/calendar_events/src/inbound/toolset.rs b/crates/calendar_events/src/inbound/toolset.rsindex d735214296..ac14b56df1 100644--- a/crates/calendar_events/src/inbound/toolset.rs+++ b/crates/calendar_events/src/inbound/toolset.rs@@ -17,7 +17,6 @@ mod update_calendar_event;#[cfg(test)]mod test;-use std::collections::HashMap;use std::sync::Arc;use ai_toolset::{AsyncToolCollection, ToolCallError};@@ -30,10 +29,11 @@ use uuid::Uuid;use crate::domain::{copies::{CopyChange, check_copy},+ labels::{CalendarLabels, EventRole},meeting_links::{CreateEventWithMacroCallError, EventWithMacroCall, MeetingLinkError},models::{CalendarAttendeeInput, CalendarEvent, EventReminderOverride, EventReminders, EventTime,- OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, VisibleCalendar,+ OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,},ports::{CalendarMutationError, CalendarMutationService, CalendarOccurrenceService,@@ -419,100 +419,12 @@ pub enum ToolEventRole {}impl ToolEventRole {- /// The role of the copy's inbox, read the way clients read it: only the- /// copy's own inbox row is `is_self`. That row marked organizer counts- /// only on a copy the user can change, since Microsoft Graph names the- /// mailbox owner as organizer on every event of a read-only calendar.- /// `organize` says they may act as organizer, which writing someone- /// else's calendar grants too, so it counts only on a calendar of their- /// own schedule with no other organizer listed.+ /// The rule [`CalendarLabels::role`] applies to every reader of an event.fn of(event: &CalendarEvent, labels: &CalendarLabels) -> Option<Self> {- let own_row = event.attendees.iter().find(|attendee| attendee.is_self);- if own_row.is_some_and(|attendee| attendee.is_organizer) {- return (!event.is_read_only).then_some(Self::Organizer);- }- let other_organizer = event.attendees.iter().any(|attendee| attendee.is_organizer);- if event.viewer_can.organize- && !other_organizer- && labels.event_on_schedule(event) == Some(true)- {- return Some(Self::Organizer);- }- own_row.map(|_| Self::Guest)- }-}--/// The calendars the user can see, to name the calendar and inbox each-/// event copy belongs to.-#[derive(Default)]-struct CalendarLabels {- by_calendar: HashMap<Uuid, VisibleCalendar>,- inbox_by_link: HashMap<Uuid, String>,-}--impl CalendarLabels {- /// Load the requester's visible calendars. Labels only describe a result,- /// so a failure leaves them out rather than failing a call whose change- /// may already have reached the provider.- async fn load<M: CalendarMutationService>(mutations: &M, requester_id: &str) -> Self {- let Ok(calendars) = mutations- .list_visible_calendars(requester_id)- .await- .inspect_err(|error| {- tracing::warn!(error = ?error, "failed to load calendar names for a tool result");- })- else {- return Self::default();- };- Self::from_calendars(calendars)- }-- /// Labels from calendars the tool already listed.- fn from_calendars(calendars: Vec<VisibleCalendar>) -> Self {- let inbox_by_link = calendars- .iter()- .map(|calendar| (calendar.email_link_id, calendar.email_address.clone()))- .collect();- let by_calendar = calendars- .into_iter()- .map(|calendar| (calendar.id, calendar))- .collect();- Self {- by_calendar,- inbox_by_link,- }- }-- fn calendar_name(&self, calendar_id: Option<Uuid>) -> Option<String> {- calendar_id- .and_then(|id| self.by_calendar.get(&id))- .map(|calendar| calendar.name.clone())- }-- /// Whether any of these calendars counts toward the user's busy time,- /// when one is known. Availability counts each copy of an event, so one- /// copy on the user's schedule is enough.- fn on_schedule(&self, calendar_ids: impl IntoIterator<Item = Uuid>) -> Option<bool> {- calendar_ids- .into_iter()- .filter_map(|id| self.by_calendar.get(&id))- .map(|calendar| calendar.contributes_to_availability)- .reduce(|left, right| left || right)- }-- /// Whether a calendar holding this event is on the user's schedule.- fn event_on_schedule(&self, event: &CalendarEvent) -> Option<bool> {- let copies = event.sources.iter().map(|copy| copy.calendar_id);- self.on_schedule(event.calendar_id.into_iter().chain(copies))- }-- /// The inbox holding a copy: its calendar's inbox, else the inbox whose- /// grant backs it.- fn inbox(&self, calendar_id: Option<Uuid>, link_id: Option<Uuid>) -> Option<String> {- calendar_id- .and_then(|id| self.by_calendar.get(&id))- .map(|calendar| calendar.email_address.clone())- .or_else(|| link_id.and_then(|id| self.inbox_by_link.get(&id)).cloned())+ labels.role(event).map(|role| match role {+ EventRole::Organizer => Self::Organizer,+ EventRole::Guest => Self::Guest,+ })}}diff --git a/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs b/crates/calendar_events/src/inbound/toolset/read_calendar_event.rsindex 40422a0bc5..326b351020 100644--- a/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs+++ b/crates/calendar_events/src/inbound/toolset/read_calendar_event.rs@@ -14,6 +14,7 @@ use uuid::Uuid;use super::{CalendarLabels, CalendarToolContext, description_preview, time_fields};use crate::domain::{join_requests::CalendarJoinRequestStatus,+ labels::off_schedule_summary,models::{CalendarMentionEvent, CalendarMentionPreview, CalendarMentionRequestItem,CalendarMentionViewerCopy,@@ -124,12 +125,9 @@ impl ReadCalendarEventResponse {"{} is on a calendar the user can see; whether it is theirs could not be checked.",event.title),- CalendarEventAccess::OnVisibleCalendar => format!(- "{} is on {}, which the user can see but which is not part of their schedule and \- may be someone else's.",- event.title,- calendar_name.as_deref().unwrap_or("a calendar"),- ),+ CalendarEventAccess::OnVisibleCalendar => {+ off_schedule_summary(&event.title, calendar_name.as_deref())+ }CalendarEventAccess::Invited => {format!("The user is invited to {}; it is on their calendar.",diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rsindex c1903cf248..20c760746d 100644--- a/crates/calendar_events/src/outbound/pg.rs+++ b/crates/calendar_events/src/outbound/pg.rs@@ -25,6 +25,7 @@ use uuid::Uuid;use crate::domain::{changes::CalendarChangeOp,ics::{CalendarEventExport, content_without_macro_call},+ labels::EventCopy,models::{ActorInboxes, AlignedGuestCopy, AppliedGoogleGrant, AttendeeResponseStatus,CALENDAR_SYNC_FAILURE_BADGE_THRESHOLD, CalendarAttendee, CalendarBackfillClaim,@@ -2716,6 +2717,55 @@ impl CalendarRepository for PgCalendarRepository {Ok(rows.into_iter().map(visible_calendar).collect())}+ #[tracing::instrument(skip(self, event_ids), fields(event_count = event_ids.len()), err)]+ async fn event_copies(&self, event_ids: &[Uuid]) -> Result<Vec<EventCopy>, Report> {+ let rows = sqlx::query!(+ r#"+ SELECT+ event.id,+ event.source_link_id,+ event.status,+ event.organizer_email,+ event.is_read_only,+ event.is_snapshot,+ event.guests_can_modify,+ event.guests_can_invite_others,+ event.guests_can_see_other_guests+ FROM calendar_events event+ WHERE event.id = ANY($1)+ "#,+ event_ids,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(report)?;+ let mut attendees = fetch_attendees(&self.pool, event_ids).await?;+ let mut source_contents = fetch_source_contents(&self.pool, event_ids).await?;+ Ok(rows+ .into_iter()+ .map(|row| EventCopy {+ event_id: row.id,+ link_id: row.source_link_id,+ status: event_status(&row.status),+ organizer_email: row.organizer_email,+ is_read_only: row.is_read_only,+ is_snapshot: row.is_snapshot,+ guest_policy: GuestPolicy {+ can_modify: row.guests_can_modify,+ can_invite_others: row.guests_can_invite_others,+ can_see_other_guests: row.guests_can_see_other_guests,+ },+ attendees: attendees.remove(&row.id).unwrap_or_default(),+ calendar_ids: source_contents+ .remove(&row.id)+ .unwrap_or_default()+ .into_iter()+ .map(|source| source.calendar_id)+ .collect(),+ })+ .collect())+ }+#[tracing::instrument(skip(self, requester_id), err)]async fn owned_inboxes(&self, requester_id: &str) -> Result<Vec<OwnedInbox>, Report> {sqlx::query!(diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rsindex 4a818d1b84..7896187e02 100644--- a/crates/calendar_events/src/outbound/pg/test.rs+++ b/crates/calendar_events/src/outbound/pg/test.rs@@ -7258,6 +7258,7 @@ async fn retiring_an_unrelated_copy_keeps_a_fresher_schedule_written_through_anomod changes;mod channel_grants;mod details;+mod event_labels;mod export;mod guest_policy;mod invitations;diff --git a/crates/calendar_events/src/outbound/pg/test/event_labels.rs b/crates/calendar_events/src/outbound/pg/test/event_labels.rsnew file mode 100644index 0000000000..1e91c4caab--- /dev/null+++ b/crates/calendar_events/src/outbound/pg/test/event_labels.rs@@ -0,0 +1,246 @@+//! The labels a search row carries, read from stored rows: a search hit has+//! no event loaded, so these reach the rule through `event_copies`.+use super::meeting_copies::link_email;+use super::*;+use crate::domain::labels::{EventLabels, EventRole};+use crate::domain::service::CalendarService;++const OWNER: &str = "macro|[email protected]";+const COLLEAGUE: &str = "[email protected]";++fn calendar(provider_calendar_id: &str, name: &str, access_role: &str) -> ProviderCalendar {+ ProviderCalendar {+ provider_calendar_id: provider_calendar_id.to_string(),+ name: name.to_string(),+ description: None,+ time_zone: Some("UTC".to_string()),+ color: None,+ access_role: Some(access_role.to_string()),+ is_primary: false,+ is_selected: true,+ default_reminders: Vec::new(),+ }+}++/// A guest row with the `is_self` Google sync stores for the inbox it synced+/// through.+fn own_row(email: &str, is_organizer: bool) -> CalendarAttendee {+ CalendarAttendee {+ email: email.to_string(),+ display_name: None,+ response_status: AttendeeResponseStatus::Accepted,+ is_organizer,+ is_optional: false,+ is_self: true,+ comment: None,+ }+}++fn copy(+ link_id: Uuid,+ provider: (Uuid, Uuid),+ title: &str,+ organizer: &str,+ attendees: Vec<CalendarAttendee>,+ is_read_only: bool,+) -> CalendarEventUpsert {+ let mut upsert = timed_upsert(+ OWNER,+ link_id,+ provider,+ &format!("{title}@example.com"),+ title,+ 1,+ );+ upsert.event.organizer_email = Some(organizer.to_string());+ upsert.event.attendees = attendees;+ upsert.event.is_read_only = is_read_only;+ upsert+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn labels_say_whose_calendar_each_stored_event_is_on(pool: PgPool) {+ let link_id = insert_link(&pool, OWNER).await;+ let inbox = link_email(&pool, link_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary) = provider_ids(&repo, link_id).await;+ let colleagues = repo+ .upsert_calendar_fixture(account_id, calendar(COLLEAGUE, COLLEAGUE, "owner"))+ .await+ .unwrap();+ let holidays = repo+ .upsert_calendar_fixture(+ account_id,+ calendar("[email protected]", "United States holidays", "reader"),+ )+ .await+ .unwrap();++ let dentist = copy(+ link_id,+ (account_id, colleagues),+ "Dentist",+ COLLEAGUE,+ Vec::new(),+ false,+ );+ let holiday = copy(+ link_id,+ (account_id, holidays),+ "Thanksgiving Day",+ &inbox,+ vec![own_row(&inbox, true)],+ true,+ );+ let organized = copy(+ link_id,+ (account_id, primary),+ "Planning",+ &inbox,+ vec![own_row(&inbox, true), own_row(COLLEAGUE, false)],+ false,+ );+ let invited = copy(+ link_id,+ (account_id, primary),+ "Review",+ COLLEAGUE,+ vec![own_row(COLLEAGUE, true), own_row(&inbox, false)],+ false,+ );+ let ids = [+ dentist.event.id,+ holiday.event.id,+ organized.event.id,+ invited.event.id,+ ];+ for upsert in [dentist, holiday, organized, invited] {+ repo.upsert_event_fixture(upsert).await.unwrap();+ }++ let labels = CalendarService::new(repo)+ .event_labels(OWNER, &ids)+ .await+ .unwrap();++ assert_eq!(+ labels[&ids[0]],+ EventLabels {+ calendar_name: Some(COLLEAGUE.to_string()),+ contributes_to_availability: Some(false),+ inbox: Some(inbox.clone()),+ role: None,+ },+ "a colleague's calendar held through the user's inbox with manage rights"+ );+ assert_eq!(+ labels[&ids[1]],+ EventLabels {+ calendar_name: Some("United States holidays".to_string()),+ contributes_to_availability: Some(false),+ inbox: Some(inbox.clone()),+ role: None,+ },+ "a read-only calendar naming the mailbox as organizer"+ );+ assert_eq!(+ labels[&ids[2]],+ EventLabels {+ calendar_name: Some("Primary".to_string()),+ contributes_to_availability: Some(true),+ inbox: Some(inbox.clone()),+ role: Some(EventRole::Organizer),+ }+ );+ assert_eq!(labels[&ids[3]].role, Some(EventRole::Guest));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_availability_setting_decides_the_schedule_label(pool: PgPool) {+ insert_user(&pool, OWNER).await;+ let link_id = insert_link(&pool, OWNER).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, _) = provider_ids(&repo, link_id).await;+ let team = repo+ .upsert_calendar_fixture(account_id, calendar("[email protected]", "Team", "owner"))+ .await+ .unwrap();+ let entry = copy(+ link_id,+ (account_id, team),+ "Offsite",+ "[email protected]",+ Vec::new(),+ false,+ );+ let id = entry.event.id;+ repo.upsert_event_fixture(entry).await.unwrap();+ let service = CalendarService::new(repo);++ let by_default = service.event_labels(OWNER, &[id]).await.unwrap();+ assert_eq!(by_default[&id].contributes_to_availability, Some(false));+ assert_eq!(by_default[&id].role, None);++ sqlx::query!(+ r#"+ INSERT INTO calendar_availability_preferences (user_id, calendar_id, contributes_to_availability)+ VALUES ($1, $2, true)+ "#,+ OWNER,+ team,+ )+ .execute(&pool)+ .await+ .unwrap();++ let on_schedule = service.event_labels(OWNER, &[id]).await.unwrap();+ assert_eq!(on_schedule[&id].contributes_to_availability, Some(true));+ assert_eq!(+ on_schedule[&id].role,+ Some(EventRole::Organizer),+ "a calendar of their own schedule that they can write, as the tools read it"+ );+}++/// A hit the requester reads through a channel is someone else's copy.+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn another_users_copy_says_nothing_about_the_requester(pool: PgPool) {+ let sharer = "macro|[email protected]";+ let sharer_link = insert_link(&pool, sharer).await;+ insert_link(&pool, OWNER).await;+ let inbox = link_email(&pool, sharer_link).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let provider = provider_ids(&repo, sharer_link).await;+ let shared = copy(+ sharer_link,+ provider,+ "Shared",+ &inbox,+ vec![own_row(&inbox, true)],+ false,+ );+ let id = shared.event.id;+ repo.upsert_event_fixture(shared).await.unwrap();++ let labels = CalendarService::new(repo)+ .event_labels(OWNER, &[id, Uuid::now_v7()])+ .await+ .unwrap();++ assert_eq!(labels.len(), 1, "an id with no event is absent");+ assert_eq!(labels[&id], EventLabels::default());++ let stored_is_self = sqlx::query_scalar!(+ r#"SELECT is_self AS "is_self!" FROM calendar_event_attendees WHERE event_id = $1"#,+ id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(stored_is_self, "the row the requester must not inherit");+ let no_inbox = CalendarService::new(PgCalendarRepository::new(pool.clone()))+ .event_labels("macro|[email protected]", &[id])+ .await+ .unwrap();+ assert_eq!(no_inbox[&id], EventLabels::default());+}diff --git a/crates/models_search/src/calendar_event.rs b/crates/models_search/src/calendar_event.rsindex 91a2da38ec..66db94ae94 100644--- a/crates/models_search/src/calendar_event.rs+++ b/crates/models_search/src/calendar_event.rs@@ -94,8 +94,10 @@ pub struct CalendarEventSearchOccurrence {pub time: CalendarEventSearchTime,}-/// The event's organizer — its creator, in Google's model. Either field can be-/// absent when the source does not name it.+/// The organizer the provider names on the event. Either field can be absent+/// when the source does not name it. On a read-only Outlook calendar, such as+/// its holidays, Microsoft names the mailbox owner on every event, so this+/// does not say the user organized anything: `role` does.#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]#[serde(rename_all = "camelCase")]pub struct CalendarEventOrganizer {@@ -107,6 +109,18 @@ pub struct CalendarEventOrganizer {pub email: Option<String>,}+/// What the user is on one copy of an event, through the inbox holding it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum CalendarEventSearchRole {+ /// The inbox organizes the event, or the event has no guests and is the+ /// user's own. Writing someone else's calendar is not this, nor is a+ /// read-only calendar naming them organizer.+ Organizer,+ /// The inbox is invited to the event.+ Guest,+}+/// A single response item, part of the CalendarEventSearchResponse object#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]pub struct CalendarEventSearchResponseItem {@@ -147,9 +161,29 @@ pub struct CalendarEventMetadata {pub conference_url: Option<String>,/// Whether the canonical source prohibits mutation.pub is_read_only: bool,- /// The event's organizer (creator), when the source names one.+ /// The organizer the provider names, when it names one.#[serde(skip_serializing_if = "Option::is_none")]pub organizer: Option<CalendarEventOrganizer>,+ /// Display name of the calendar holding this copy. Absent on an event+ /// shared with the user, which is on none of their calendars.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub calendar_name: Option<String>,+ /// Whether a calendar holding this copy is on the user's schedule. The+ /// user can see calendars that are not theirs, such as a colleague's: a+ /// row without this, and that they do not attend, says what that calendar+ /// shows, not where the user is.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub contributes_to_availability: Option<bool>,+ /// The connected inbox syncing that calendar. It stays the user's own+ /// address on a colleague's calendar, so it never says whose calendar it+ /// is.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub inbox: Option<String>,+ /// Whether the user organizes this copy or is a guest on it. Absent when+ /// they are neither, when they can only write that calendar, or when a+ /// read-only calendar names them organizer.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub role: Option<CalendarEventSearchRole>,/// Free-text description, when the event carries one. May contain HTML from/// the source; clients render a plain-text preview.#[serde(skip_serializing_if = "Option::is_none")]diff --git a/crates/search_service/AGENTS.md b/crates/search_service/AGENTS.mdindex 0550172c7b..fb4fea7bc8 100644--- a/crates/search_service/AGENTS.md+++ b/crates/search_service/AGENTS.md@@ -33,7 +33,7 @@ per-entity-type search plus a unified search across them — mounted into- Depends on: `opensearch_client`, `models_opensearch`, `macro_db_client`,`entity_access`, `properties`, `crm`, `item_filters`, `calendar_events`- (domain only, no features, for its Macro call rule).+ (domain only, no features, for its Macro call rule and label port).- Used by: `document_storage_service` (mounts `search_router`); calledthrough `search_service_client`.@@ -71,6 +71,21 @@ per-entity-type search plus a unified search across them — mounted intonamed in the `own` scope reaches a share as well. The index stores titles,never the description or location, so hits and highlights cannot carry thelink.+- Agents answer calendar questions from search as often as from+ `occurrences()`, and the `own` scope matches by inbox link, so an event on a+ colleague's calendar comes back under the user's own address. Enrichment+ therefore labels each row with what an occurrence says (`calendarName`,+ `contributesToAvailability`, `inbox`, `role`) through `calendar_events`'+ `CalendarEventLabelReader`: one read per search, never per row, and a failed+ read leaves the labels off rather than failing the search, and missing labels+ mean unknown, never "not theirs". `organizer` stays the provider's raw value,+ which web rows show even where a read-only calendar names the user's own+ mailbox: `NameSearch`'s description is what tells a model that only `role`+ says they organize it. Fields alone did not stop models calling a colleague's+ event "your appointment"; `ai_tools` adds `calendar_events`'+ `off_schedule_summary` to such a result, and that sentence did. Measure a+ change to any of these with the default model on rows that are really in the+ index, and a user whose memory does not describe the behavior under test.## Relateddiff --git a/crates/search_service/src/api/context.rs b/crates/search_service/src/api/context.rsindex 1c187f5b66..091a800170 100644--- a/crates/search_service/src/api/context.rs+++ b/crates/search_service/src/api/context.rs@@ -1,5 +1,6 @@use agent_session::domain::search::AgentSessionSearchMetadataService;use axum::extract::FromRef;+use calendar_events::domain::ports::CalendarEventLabelReader;use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;use macro_authorization::{@@ -36,6 +37,9 @@ pub struct SearchHandlerState {/// gating here covers every caller of the search API at once, the AI/// search tools included.pub calendar_search_enabled: bool,+ /// Says whose calendar each event hit is on and what the caller is there,+ /// by the rule every calendar reader shares.+ pub calendar_event_labels: Arc<dyn CalendarEventLabelReader>,}impl SearchHandlerState {diff --git a/crates/search_service/src/api/search/calendar_event.rs b/crates/search_service/src/api/search/calendar_event.rsindex a22f7d5a74..ecf0b862e5 100644--- a/crates/search_service/src/api/search/calendar_event.rs+++ b/crates/search_service/src/api/search/calendar_event.rs@@ -1,5 +1,6 @@use crate::api::search::simple::SearchError;use calendar_events::domain::ics::content_without_macro_call;+use calendar_events::domain::labels::{EventLabels, EventRole};use indexmap::IndexMap;use macro_db_client::calendar_event::get_events_for_search::{CalendarEventSearchInfo, get_calendar_events_for_search,@@ -9,7 +10,7 @@ use models_properties::{EntityReference, EntityType};use models_search::calendar_event::{CalendarEventMetadata, CalendarEventOrganizer, CalendarEventSearchOccurrence,CalendarEventSearchResponseItem, CalendarEventSearchResponseItemWithMetadata,- CalendarEventSearchResult, CalendarEventSearchTime,+ CalendarEventSearchResult, CalendarEventSearchRole, CalendarEventSearchTime,};use models_soup::SoupProperty;use sqlx::types::Uuid;@@ -48,6 +49,16 @@ pub(in crate::api::search) async fn enrich_calendar_events(events.values().filter(|event| !event.holds_meeting).count(),);+ // Labels only describe a row, so a failure leaves them out rather than+ // failing the search.+ let visible_ids: Vec<Uuid> = events.keys().copied().collect();+ let labels = ctx+ .calendar_event_labels+ .event_labels(user_id, &visible_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to label calendar event hits"))+ .unwrap_or_default();+// Fetch event properties (e.g. tags) so rows can render and re-check// them, mirroring the projects enrichment.let entity_refs: Vec<EntityReference> = event_ids@@ -80,7 +91,12 @@ pub(in crate::api::search) async fn enrich_calendar_events(}).collect();- Ok(construct_search_result(results, events, properties_map))+ Ok(construct_search_result(+ results,+ events,+ labels,+ properties_map,+ ))}/// Read a timed or all-day span out of the four nullable columns the@@ -145,9 +161,17 @@ fn to_description(info: &CalendarEventSearchInfo) -> Option<String> {description}+fn to_role(role: EventRole) -> CalendarEventSearchRole {+ match role {+ EventRole::Organizer => CalendarEventSearchRole::Organizer,+ EventRole::Guest => CalendarEventSearchRole::Guest,+ }+}+pub fn construct_search_result(search_results: Vec<opensearch_client::search::model::SearchHit>,events: HashMap<Uuid, CalendarEventSearchInfo>,+ mut labels: HashMap<Uuid, EventLabels>,mut properties_map: HashMap<String, Vec<SoupProperty>>,) -> Vec<CalendarEventSearchResponseItemWithMetadata> {// construct entity hit map of id -> vec<hits> using IndexMap to preserve@@ -180,6 +204,7 @@ pub fn construct_search_result(info.end_date,info.time_zone.clone(),)?;+ let labels = labels.remove(&entity_id).unwrap_or_default();Some(CalendarEventSearchResponseItemWithMetadata {metadata: Some(CalendarEventMetadata {created_at: info.created_at,@@ -191,6 +216,10 @@ pub fn construct_search_result(conference_url: info.conference_url.clone(),is_read_only: info.is_read_only,organizer: to_organizer(info),+ calendar_name: labels.calendar_name,+ contributes_to_availability: labels.contributes_to_availability,+ inbox: labels.inbox,+ role: labels.role.map(to_role),description: to_description(info),}),properties: properties_mapdiff --git a/crates/search_service/src/api/search/calendar_event/test.rs b/crates/search_service/src/api/search/calendar_event/test.rsindex 0714e79d23..0ed30c33c4 100644--- a/crates/search_service/src/api/search/calendar_event/test.rs+++ b/crates/search_service/src/api/search/calendar_event/test.rs@@ -1,4 +1,5 @@use super::*;+use calendar_events::domain::labels::{EventLabels, EventRole};use calendar_events::domain::meeting_links::attach_macro_call;use chrono::{NaiveDate, TimeZone, Utc};use opensearch_client::search::model::{Highlight, SearchHit};@@ -50,8 +51,12 @@ fn returned_description(description: &str, holds_meeting: bool) -> Option<Stringlet mut info = timed_series(id);info.description = Some(description.to_string());info.holds_meeting = holds_meeting;- let results =- construct_search_result(vec![hit(id)], HashMap::from([(id, info)]), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::new(),+ HashMap::new(),+ );results.into_iter().next()@@ -59,6 +64,106 @@ fn returned_description(description: &str, holds_meeting: bool) -> Option<String.and_then(|metadata| metadata.description)}+/// The metadata of a row for `info` under `labels`.+fn labelled_row(mut info: CalendarEventSearchInfo, labels: EventLabels) -> CalendarEventMetadata {+ let id = Uuid::new_v4();+ info.id = id;+ construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::from([(id, labels)]),+ HashMap::new(),+ )+ .into_iter()+ .next()+ .and_then(|row| row.metadata)+ .expect("a row")+}++/// An event on a colleague's calendar comes back on the user's own inbox, so+/// only the row's labels keep it from reading as the user's.+#[test]+fn a_row_on_a_colleagues_calendar_says_whose_it_is() {+ let metadata = labelled_row(+ timed_series(Uuid::nil()),+ EventLabels {+ calendar_name: Some("[email protected]".to_string()),+ contributes_to_availability: Some(false),+ inbox: Some("[email protected]".to_string()),+ role: None,+ },+ );+ assert_eq!(+ metadata.calendar_name.as_deref(),+ Some("[email protected]")+ );+ assert_eq!(metadata.contributes_to_availability, Some(false));+ assert_eq!(metadata.inbox.as_deref(), Some("[email protected]"));+ assert_eq!(metadata.role, None);+}++#[test]+fn a_real_organizer_and_guest_keep_their_role_on_the_row() {+ for (role, wire) in [+ (EventRole::Organizer, CalendarEventSearchRole::Organizer),+ (EventRole::Guest, CalendarEventSearchRole::Guest),+ ] {+ let metadata = labelled_row(+ timed_series(Uuid::nil()),+ EventLabels {+ role: Some(role),+ ..EventLabels::default()+ },+ );+ assert_eq!(metadata.role, Some(wire));+ }+}++/// A row whose labels failed to load still reaches the caller, without any.+#[test]+fn a_row_without_labels_says_nothing_about_the_calendar() {+ let id = Uuid::new_v4();+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, timed_series(id))]),+ HashMap::new(),+ HashMap::new(),+ );+ let metadata = results[0].metadata.as_ref().expect("metadata");+ assert_eq!(metadata.calendar_name, None);+ assert_eq!(metadata.contributes_to_availability, None);+ assert_eq!(metadata.role, None);+}++/// Absent labels stay off the wire, like the row's other optional fields, and+/// a row names the field the way an occurrence does.+#[test]+fn labels_serialize_under_the_occurrence_names() {+ let metadata = labelled_row(+ timed_series(Uuid::nil()),+ EventLabels {+ calendar_name: Some("Team".to_string()),+ contributes_to_availability: Some(false),+ inbox: Some("[email protected]".to_string()),+ role: Some(EventRole::Guest),+ },+ );+ let row = serde_json::to_value(&metadata).expect("serializes");+ assert_eq!(row["calendarName"], "Team");+ assert_eq!(row["contributesToAvailability"], false);+ assert_eq!(row["inbox"], "[email protected]");+ assert_eq!(row["role"], "guest");++ let bare = serde_json::to_value(labelled_row(+ timed_series(Uuid::nil()),+ EventLabels::default(),+ ))+ .expect("serializes");+ for field in ["calendarName", "contributesToAvailability", "inbox", "role"] {+ assert!(bare.get(field).is_none(), "{field} stays off the wire");+ }+}+#[test]fn a_channel_member_reads_the_description_without_the_macro_call() {let (stored, _) = attach_macro_call(Some("Quarterly planning"), None, CALL_URL);@@ -109,8 +214,12 @@ fn resolved_occurrence_rides_on_the_row() {info.occurrence_starts_at = Some(Utc.with_ymd_and_hms(2026, 8, 25, 10, 0, 0).unwrap());info.occurrence_ends_at = Some(Utc.with_ymd_and_hms(2026, 8, 25, 10, 15, 0).unwrap());- let results =- construct_search_result(vec![hit(id)], HashMap::from([(id, info)]), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::new(),+ HashMap::new(),+ );assert_eq!(results.len(), 1);let metadata = results[0].metadata.as_ref().expect("metadata");@@ -147,6 +256,7 @@ fn series_with_no_materialized_occurrence_keeps_its_row() {vec![hit(id)],HashMap::from([(id, timed_series(id))]),HashMap::new(),+ HashMap::new(),);assert_eq!(results.len(), 1);@@ -170,8 +280,12 @@ fn all_day_series_reads_the_date_pair() {info.start_date = Some(NaiveDate::from_ymd_opt(2026, 8, 25).unwrap());info.end_date = Some(NaiveDate::from_ymd_opt(2026, 8, 26).unwrap());- let results =- construct_search_result(vec![hit(id)], HashMap::from([(id, info)]), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::new(),+ HashMap::new(),+ );let metadata = results[0].metadata.as_ref().expect("metadata");match &metadata.time {@@ -191,7 +305,12 @@ fn hit_the_caller_cannot_see_is_dropped() {// The visibility query is the authority: an id absent from its result set// is one the caller lost access to since it was indexed.let id = Uuid::new_v4();- let results = construct_search_result(vec![hit(id)], HashMap::new(), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::new(),+ HashMap::new(),+ HashMap::new(),+ );assert!(results.is_empty(),"a hit with no visible row must not reach the response"@@ -205,8 +324,12 @@ fn unreadable_span_is_dropped_rather_than_dated_wrong() {info.starts_at = None;info.ends_at = None;// Neither leg of the time-shape constraint is satisfied.- let results =- construct_search_result(vec![hit(id)], HashMap::from([(id, info)]), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::new(),+ HashMap::new(),+ );assert!(results.is_empty());}@@ -217,6 +340,7 @@ fn multiple_hits_for_one_event_collapse_into_one_row() {vec![hit(id), hit(id)],HashMap::from([(id, timed_series(id))]),HashMap::new(),+ HashMap::new(),);assert_eq!(results.len(), 1, "one row per event entity");assert_eq!(@@ -233,6 +357,7 @@ fn organizer_rides_on_the_row_when_named() {vec![hit(id)],HashMap::from([(id, timed_series(id))]),HashMap::new(),+ HashMap::new(),);let organizer = results[0].metadata@@ -251,8 +376,12 @@ fn organizer_absent_when_source_names_neither() {let mut info = timed_series(id);info.organizer_email = None;info.organizer_name = None;- let results =- construct_search_result(vec![hit(id)], HashMap::from([(id, info)]), HashMap::new());+ let results = construct_search_result(+ vec![hit(id)],+ HashMap::from([(id, info)]),+ HashMap::new(),+ HashMap::new(),+ );assert!(results[0].metadatadiff --git a/packages/sdk-docs/reference/generated/search/types.gen/README.md b/packages/sdk-docs/reference/generated/search/types.gen/README.mdindex 2ee899a7c2..6a977c2a14 100644--- a/packages/sdk-docs/reference/generated/search/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/search/types.gen/README.md@@ -13,6 +13,7 @@- [CalendarEventSearchResponseItem](type-aliases/CalendarEventSearchResponseItem.md)- [CalendarEventSearchResponseItemWithMetadata](type-aliases/CalendarEventSearchResponseItemWithMetadata.md)- [CalendarEventSearchResult](type-aliases/CalendarEventSearchResult.md)+- [CalendarEventSearchRole](type-aliases/CalendarEventSearchRole.md)- [CalendarEventSearchScope](type-aliases/CalendarEventSearchScope.md)- [CalendarEventSearchTime](type-aliases/CalendarEventSearchTime.md)- [CallFilters](type-aliases/CallFilters.md)diff --git a/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventMetadata.md b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventMetadata.mdindex 887fca1210..9ba7186037 100644--- a/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventMetadata.md+++ b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventMetadata.md@@ -1,6 +1,6 @@# Type Alias: CalendarEventMetadata-> **CalendarEventMetadata** = \{ `conferenceUrl?`: `string` \| `null`; `createdAt`: `string`; `description?`: `string` \| `null`; `isReadOnly`: `boolean`; `isRecurring`: `boolean`; `occurrence?`: `null` \| [`CalendarEventSearchOccurrence`](CalendarEventSearchOccurrence.md); `organizer?`: `null` \| [`CalendarEventOrganizer`](CalendarEventOrganizer.md); `status`: `string`; `time`: [`CalendarEventSearchTime`](CalendarEventSearchTime.md); `updatedAt`: `string`; \}+> **CalendarEventMetadata** = \{ `calendarName?`: `string` \| `null`; `conferenceUrl?`: `string` \| `null`; `contributesToAvailability?`: `boolean` \| `null`; `createdAt`: `string`; `description?`: `string` \| `null`; `inbox?`: `string` \| `null`; `isReadOnly`: `boolean`; `isRecurring`: `boolean`; `occurrence?`: `null` \| [`CalendarEventSearchOccurrence`](CalendarEventSearchOccurrence.md); `organizer?`: `null` \| [`CalendarEventOrganizer`](CalendarEventOrganizer.md); `role?`: `null` \| [`CalendarEventSearchRole`](CalendarEventSearchRole.md); `status`: `string`; `time`: [`CalendarEventSearchTime`](CalendarEventSearchTime.md); `updatedAt`: `string`; \}Metadata for a calendar event fetched from the database.@@ -12,13 +12,17 @@ rather than indexed.| Property | Type | Description || ------ | ------ | ------ |+| <a id="property-calendarname"></a> `calendarName?` | `string` \| `null` | Display name of the calendar holding this copy. Absent on an event shared with the user, which is on none of their calendars. || <a id="property-conferenceurl"></a> `conferenceUrl?` | `string` \| `null` | Direct conference join URL when known. |+| <a id="property-contributestoavailability"></a> `contributesToAvailability?` | `boolean` \| `null` | Whether a calendar holding this copy is on the user's schedule. The user can see calendars that are not theirs, such as a colleague's: a row without this, and that they do not attend, says what that calendar shows, not where the user is. || <a id="property-createdat"></a> `createdAt` | `string` | - || <a id="property-description"></a> `description?` | `string` \| `null` | Free-text description, when the event carries one. May contain HTML from the source; clients render a plain-text preview. |+| <a id="property-inbox"></a> `inbox?` | `string` \| `null` | The connected inbox syncing that calendar. It stays the user's own address on a colleague's calendar, so it never says whose calendar it is. || <a id="property-isreadonly"></a> `isReadOnly` | `boolean` | Whether the canonical source prohibits mutation. || <a id="property-isrecurring"></a> `isRecurring` | `boolean` | Whether the series carries a recurrence rule. Lets a row render a recurring badge without parsing the rules. || <a id="property-occurrence"></a> `occurrence?` | `null` \| [`CalendarEventSearchOccurrence`](CalendarEventSearchOccurrence.md) | - || <a id="property-organizer"></a> `organizer?` | `null` \| [`CalendarEventOrganizer`](CalendarEventOrganizer.md) | - |+| <a id="property-role"></a> `role?` | `null` \| [`CalendarEventSearchRole`](CalendarEventSearchRole.md) | - || <a id="property-status"></a> `status` | `string` | Canonical status (`confirmed`, `tentative`, `cancelled`). || <a id="property-time"></a> `time` | [`CalendarEventSearchTime`](CalendarEventSearchTime.md) | The series' own span. || <a id="property-updatedat"></a> `updatedAt` | `string` | - |diff --git a/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventOrganizer.md b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventOrganizer.mdindex a7840a0b35..00be2b4770 100644--- a/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventOrganizer.md+++ b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventOrganizer.md@@ -2,8 +2,10 @@> **CalendarEventOrganizer** = \{ `email?`: `string` \| `null`; `name?`: `string` \| `null`; \}-The event's organizer — its creator, in Google's model. Either field can be-absent when the source does not name it.+The organizer the provider names on the event. Either field can be absent+when the source does not name it. On a read-only Outlook calendar, such as+its holidays, Microsoft names the mailbox owner on every event, so this+does not say the user organized anything: `role` does.## Propertiesdiff --git a/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventSearchRole.md b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventSearchRole.mdnew file mode 100644index 0000000000..8836f64649--- /dev/null+++ b/packages/sdk-docs/reference/generated/search/types.gen/type-aliases/CalendarEventSearchRole.md@@ -0,0 +1,5 @@+# Type Alias: CalendarEventSearchRole++> **CalendarEventSearchRole** = `"organizer"` \| `"guest"`++What the user is on one copy of an event, through the inbox holding it.diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.mdindex a21dd000fe..ba984062c1 100644--- a/packages/sdk/AGENTS.md+++ b/packages/sdk/AGENTS.md@@ -72,7 +72,7 @@ the existing gateway prefixes.only on such a calendar, since writing someone's calendar grants it too. Anown attendee row marked organizer counts only on a copy the user can change(`isReadOnly` false): Outlook names the mailbox owner as organizer on every- event of a read-only calendar. `eventRole` and `ToolEventRole::of` must stay+ event of a read-only calendar. `eventRole` and `EventRole::of` must stayin step.- Calendar notes accept a document handle and the occurrence returned by calendarreads. `CalendarNote` owns optional team sharing and unlinking; clearing its teamdiff --git a/packages/sdk/generated/search/index.ts b/packages/sdk/generated/search/index.tsindex e73c82c9c6..377ea7bfa5 100644--- a/packages/sdk/generated/search/index.ts+++ b/packages/sdk/generated/search/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AgentSessionAuthor, AgentSessionFilters, AgentSessionSearchResponseItem, AgentSessionSearchResult, CalendarEventFilters, CalendarEventMetadata, CalendarEventOrganizer, CalendarEventSearchOccurrence, CalendarEventSearchResponseItem, CalendarEventSearchResponseItemWithMetadata, CalendarEventSearchResult, CalendarEventSearchScope, CalendarEventSearchTime, CallFilters, CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata, CallRecordSearchResult, CallStatus, ChannelFilters, ChannelMessageSearchResponseItem, ChannelMetadata, ChannelNameSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult, ChannelSortTimestamp, ChannelThreadFilters, ChatFilters, ChatMessageSearchResult, ChatMetadata, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem, ChatSearchResponseItemWithMetadata, ClientOptions, CrmCompanyFilters, CrmCompanySearchDomain, CrmCompanySearchResponseItem, DataType, DateRange, DocumentFilters, DocumentMetadata, DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult, DocumentSubType, EmailFilters, EmailSearchParticipant, EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem, EmailSearchResponseItemWithMetadata, EmailSearchResult, EmptyResponse, EntityFilters, EntityReference, EntityType, ErrorResponse, FileType, ForeignEntityFilters, Highlight, InitiativeFilters, MatchType, NotificationFilters, NotificationState, ProjectFilters, ProjectMetadata, ProjectSearchMetadata, ProjectSearchRequest, ProjectSearchResponseItem, ProjectSearchResponseItemWithMetadata, ProjectSearchResult, PropertyDefinition, PropertyFilter, PropertyOwner, PropertyValue, SearchGotoAgentSession, SearchGotoCallRecord, SearchGotoChannel, SearchGotoChat, SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHighlight, SearchOn, SearchResponse, SharedEmailFilter, SimpleCalendarEventSearchResponseBaseItemHumanReadableTimestamp, SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp, SimpleChannelSearchReponseBaseItem, SimpleChannelSearchReponseBaseItemHumanReadableTimestamp, SimpleChannelSearchResponse, SimpleChatSearchResponse, SimpleChatSearchResponseBaseItem, SimpleChatSearchResponseBaseItemHumanReadableTimestamp, SimpleDocumentSearchResponse, SimpleDocumentSearchResponseBaseItem, SimpleDocumentSearchResponseBaseItemHumanReadableTimestamp, SimpleEmailSearchResponse, SimpleEmailSearchResponseBaseItem, SimpleEmailSearchResponseBaseItemHumanReadableTimestamp, SimpleProjectSearchResponse, SimpleProjectSearchResponseBaseItem, SimpleProjectSearchResponseBaseItemHumanReadableTimestamp, SimpleSearchResponse, SimpleSearchResponseItem, SimpleUnifiedSearchBaseResponse, SimpleUnifiedSearchData, SimpleUnifiedSearchError, SimpleUnifiedSearchErrors, SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseBaseItem, SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp, SimpleUnifiedSearchResponses, SoupProperty, TagFilterMode, TaskFilters, UnifiedSearchData, UnifiedSearchError, UnifiedSearchErrors, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponse2, UnifiedSearchResponseItem, UnifiedSearchResponses } from './types.gen';+export type { AgentSessionAuthor, AgentSessionFilters, AgentSessionSearchResponseItem, AgentSessionSearchResult, CalendarEventFilters, CalendarEventMetadata, CalendarEventOrganizer, CalendarEventSearchOccurrence, CalendarEventSearchResponseItem, CalendarEventSearchResponseItemWithMetadata, CalendarEventSearchResult, CalendarEventSearchRole, CalendarEventSearchScope, CalendarEventSearchTime, CallFilters, CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata, CallRecordSearchResult, CallStatus, ChannelFilters, ChannelMessageSearchResponseItem, ChannelMetadata, ChannelNameSearchResponseItem, ChannelSearchRequest, ChannelSearchResponse, ChannelSearchResponseItem, ChannelSearchResponseItemWithMetadata, ChannelSearchResult, ChannelSortTimestamp, ChannelThreadFilters, ChatFilters, ChatMessageSearchResult, ChatMetadata, ChatSearchRequest, ChatSearchResponse, ChatSearchResponseItem, ChatSearchResponseItemWithMetadata, ClientOptions, CrmCompanyFilters, CrmCompanySearchDomain, CrmCompanySearchResponseItem, DataType, DateRange, DocumentFilters, DocumentMetadata, DocumentSearchRequest, DocumentSearchResponse, DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult, DocumentSubType, EmailFilters, EmailSearchParticipant, EmailSearchRequest, EmailSearchResponse, EmailSearchResponseItem, EmailSearchResponseItemWithMetadata, EmailSearchResult, EmptyResponse, EntityFilters, EntityReference, EntityType, ErrorResponse, FileType, ForeignEntityFilters, Highlight, InitiativeFilters, MatchType, NotificationFilters, NotificationState, ProjectFilters, ProjectMetadata, ProjectSearchMetadata, ProjectSearchRequest, ProjectSearchResponseItem, ProjectSearchResponseItemWithMetadata, ProjectSearchResult, PropertyDefinition, PropertyFilter, PropertyOwner, PropertyValue, SearchGotoAgentSession, SearchGotoCallRecord, SearchGotoChannel, SearchGotoChat, SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHighlight, SearchOn, SearchResponse, SharedEmailFilter, SimpleCalendarEventSearchResponseBaseItemHumanReadableTimestamp, SimpleCallRecordSearchResponseBaseItemHumanReadableTimestamp, SimpleChannelSearchReponseBaseItem, SimpleChannelSearchReponseBaseItemHumanReadableTimestamp, SimpleChannelSearchResponse, SimpleChatSearchResponse, SimpleChatSearchResponseBaseItem, SimpleChatSearchResponseBaseItemHumanReadableTimestamp, SimpleDocumentSearchResponse, SimpleDocumentSearchResponseBaseItem, SimpleDocumentSearchResponseBaseItemHumanReadableTimestamp, SimpleEmailSearchResponse, SimpleEmailSearchResponseBaseItem, SimpleEmailSearchResponseBaseItemHumanReadableTimestamp, SimpleProjectSearchResponse, SimpleProjectSearchResponseBaseItem, SimpleProjectSearchResponseBaseItemHumanReadableTimestamp, SimpleSearchResponse, SimpleSearchResponseItem, SimpleUnifiedSearchBaseResponse, SimpleUnifiedSearchData, SimpleUnifiedSearchError, SimpleUnifiedSearchErrors, SimpleUnifiedSearchResponse, SimpleUnifiedSearchResponseBaseItem, SimpleUnifiedSearchResponseBaseItemHumanReadableTimestamp, SimpleUnifiedSearchResponses, SoupProperty, TagFilterMode, TaskFilters, UnifiedSearchData, UnifiedSearchError, UnifiedSearchErrors, UnifiedSearchRequest, UnifiedSearchResponse, UnifiedSearchResponse2, UnifiedSearchResponseItem, UnifiedSearchResponses } from './types.gen';diff --git a/packages/sdk/generated/search/types.gen.ts b/packages/sdk/generated/search/types.gen.tsindex 5866fdf337..cb295b3e0d 100644--- a/packages/sdk/generated/search/types.gen.ts+++ b/packages/sdk/generated/search/types.gen.ts@@ -118,16 +118,34 @@ export type CalendarEventFilters = {* rather than indexed.*/export type CalendarEventMetadata = {+ /**+ * Display name of the calendar holding this copy. Absent on an event+ * shared with the user, which is on none of their calendars.+ */+ calendarName?: string | null;/*** Direct conference join URL when known.*/conferenceUrl?: string | null;+ /**+ * Whether a calendar holding this copy is on the user's schedule. The+ * user can see calendars that are not theirs, such as a colleague's: a+ * row without this, and that they do not attend, says what that calendar+ * shows, not where the user is.+ */+ contributesToAvailability?: boolean | null;createdAt: string;/*** Free-text description, when the event carries one. May contain HTML from* the source; clients render a plain-text preview.*/description?: string | null;+ /**+ * The connected inbox syncing that calendar. It stays the user's own+ * address on a colleague's calendar, so it never says whose calendar it+ * is.+ */+ inbox?: string | null;/*** Whether the canonical source prohibits mutation.*/@@ -139,6 +157,7 @@ export type CalendarEventMetadata = {isRecurring: boolean;occurrence?: null | CalendarEventSearchOccurrence;organizer?: null | CalendarEventOrganizer;+ role?: null | CalendarEventSearchRole;/*** Canonical status (`confirmed`, `tentative`, `cancelled`).*/@@ -151,8 +170,10 @@ export type CalendarEventMetadata = {};/**- * The event's organizer — its creator, in Google's model. Either field can be- * absent when the source does not name it.+ * The organizer the provider names on the event. Either field can be absent+ * when the source does not name it. On a read-only Outlook calendar, such as+ * its holidays, Microsoft names the mailbox owner on every event, so this+ * does not say the user organized anything: `role` does.*/export type CalendarEventOrganizer = {/**@@ -219,6 +240,11 @@ export type CalendarEventSearchResult = {score?: number | null;};+/**+ * What the user is on one copy of an event, through the inbox holding it.+ */+export type CalendarEventSearchRole = 'organizer' | 'guest';+/*** Which calendar events a unified search covers.*diff --git a/packages/sdk/specs/search.json b/packages/sdk/specs/search.jsonindex b770b97847..b1c5c04691 100644--- a/packages/sdk/specs/search.json+++ b/packages/sdk/specs/search.json@@ -335,10 +335,18 @@"isReadOnly"],"properties": {+ "calendarName": {+ "type": ["string", "null"],+ "description": "Display name of the calendar holding this copy. Absent on an event\nshared with the user, which is on none of their calendars."+ },"conferenceUrl": {"type": ["string", "null"],"description": "Direct conference join URL when known."},+ "contributesToAvailability": {+ "type": ["boolean", "null"],+ "description": "Whether a calendar holding this copy is on the user's schedule. The\nuser can see calendars that are not theirs, such as a colleague's: a\nrow without this, and that they do not attend, says what that calendar\nshows, not where the user is."+ },"createdAt": {"type": "string","format": "date-time"@@ -347,6 +355,10 @@"type": ["string", "null"],"description": "Free-text description, when the event carries one. May contain HTML from\nthe source; clients render a plain-text preview."},+ "inbox": {+ "type": ["string", "null"],+ "description": "The connected inbox syncing that calendar. It stays the user's own\naddress on a colleague's calendar, so it never says whose calendar it\nis."+ },"isReadOnly": {"type": "boolean","description": "Whether the canonical source prohibits mutation."@@ -373,7 +385,18 @@},{"$ref": "#/components/schemas/CalendarEventOrganizer",- "description": "The event's organizer (creator), when the source names one."+ "description": "The organizer the provider names, when it names one."+ }+ ]+ },+ "role": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CalendarEventSearchRole",+ "description": "Whether the user organizes this copy or is a guest on it. Absent when\nthey are neither, when they can only write that calendar, or when a\nread-only calendar names them organizer."}]},@@ -393,7 +416,7 @@},"CalendarEventOrganizer": {"type": "object",- "description": "The event's organizer — its creator, in Google's model. Either field can be\nabsent when the source does not name it.",+ "description": "The organizer the provider names on the event. Either field can be absent\nwhen the source does not name it. On a read-only Outlook calendar, such as\nits holidays, Microsoft names the mailbox owner on every event, so this\ndoes not say the user organized anything: `role` does.","properties": {"email": {"type": ["string", "null"],@@ -504,6 +527,11 @@}}},+ "CalendarEventSearchRole": {+ "type": "string",+ "description": "What the user is on one copy of an event, through the inbox holding it.",+ "enum": ["organizer", "guest"]+ },"CalendarEventSearchScope": {"type": "string","description": "Which calendar events a unified search covers.\n\nSharing an event with a channel lets its members see the sharer's copy,\nwhich is on none of their own calendars, so the default scope never finds\nit. Shared events are a separate scope rather than part of the default, so\na caller can list them after the caller's own events without reordering\nthose.",diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 4c688847fa..d192df0594 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -13,7 +13,8 @@ use cal::{outbound::analytics_client::AnalyticsClientSink,};use calendar_events::{- domain::service::CalendarService, inbound::axum_router::CalendarRouterState,+ domain::{ports::CalendarEventLabelReader, service::CalendarService},+ inbound::axum_router::CalendarRouterState,outbound::pg::PgCalendarRepository,};use call::{@@ -1039,6 +1040,9 @@ impl From<&ApiContext> for SearchHandlerState {))as Arc<dyn AgentSessionSearchMetadataService>,calendar_search_enabled: ctx.config.calendar_search_enabled,+ calendar_event_labels: Arc::new(CalendarService::new(PgCalendarRepository::new(+ ctx.readonly_db.0.clone(),+ ))) as Arc<dyn CalendarEventLabelReader>,}}}