Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(tags): surface tags in AI tools + ListTags tool (#4626)
gbirman0426132467af
diff --git a/js/app/packages/core/component/AI/component/tool/ListTags.tsx b/js/app/packages/core/component/AI/component/tool/ListTags.tsxnew file mode 100644index 0000000000..48fac8d13e--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/ListTags.tsx@@ -0,0 +1,71 @@+import Tag from '@phosphor-icons/core/regular/tag.svg';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import { createSignal, For } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type ListTagsSet = NamedTool<'ListTags', 'response'>['data']['tagSets'][number];++const ListTagsToolResponse = (props: { tagSets: ListTagsSet[] }) => (+ <Tool.List>+ <For each={props.tagSets}>+ {(set) => (+ <For each={set.tags}>+ {(tag) => (+ <Tool.ListItem icon={<Tag class="size-4" />}>+ <div class="flex min-w-0 flex-1 items-center justify-between gap-2">+ <span class="truncate text-xs text-ink">{tag.label}</span>+ <span class="shrink-0 text-2xs text-ink-muted">+ {set.scope}+ </span>+ </div>+ </Tool.ListItem>+ )}+ </For>+ )}+ </For>+ </Tool.List>+);++const handler = createToolRenderer({+ name: 'ListTags',+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const tagSets = () => ctx.response?.data.tagSets ?? [];+ const tagCount = () =>+ tagSets().reduce((count, set) => count + set.tags.length, 0);+ const hasResults = () => tagCount() > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (tagCount() === 0) return 'No Tags';+ if (tagCount() === 1) return '1 tag';+ return `${tagCount()} tags`;+ };++ return (+ <BaseTool+ icon={Tag}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <ListTagsToolResponse tagSets={tagSets()} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">List available tags</span>+ <Tool.ResultToggle+ expanded={isExpanded()}+ onToggle={() => setIsExpanded((expanded) => !expanded)}+ showToggle={hasResults()}+ status={statusText()}+ />+ </div>+ </BaseTool>+ );+ },+});++export const listTagsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex f42344d6b0..f7872e6380 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -14,6 +14,7 @@ import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';import { listInboxesHandler } from './ListInboxes';import { listLabelsHandler } from './ListLabels';+import { listTagsHandler } from './ListTags';import { listTeamMembersHandler } from './ListTeamMembers';import { loadToolsHandler } from './LoadTools';import {@@ -63,6 +64,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ListInboxes: listInboxesHandler,ListLabels: listLabelsHandler,ListNotifications: listNotificationsHandler,+ ListTags: listTagsHandler,ListTeamMembers: listTeamMembersHandler,LoadTools: loadToolsHandler,MarkNotificationsDone: markNotificationsDoneHandler,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex a9227114aa..da96c47cc7 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -109,376 +109,473 @@ export const ContentSearch = z.object({).optional(),query: z.string(),+ tags: z+ .union([+ z.array(+ z.object({+ label: z.string(),+ scope: z.union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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(),+ ]),+ })+ ),+ z.null(),+ ])+ .optional(),});export const SearchToolResponse = z.object({results: z.array(- z.any().superRefine((x, ctx) => {- const schemas = [- z.intersection(- z.object({- document_id: z.string().uuid(),- document_name: z.string(),- document_search_results: z.array(- z.object({- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- node_id: z.union([z.string(), z.null()]).optional(),- raw_content: z.union([z.string(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- })- ),- file_type: z.union([z.string(), z.null()]).optional(),- id: z.string().uuid(),- metadata: z- .union([- z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- sub_type: z- .union([- z.any().superRefine((x, ctx) => {- const schemas = [z.literal('task'), z.literal('snippet')];- 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(),- }),- z.object({ type: z.literal('document') })- ),- z.intersection(- z.object({- chat_id: z.string().uuid(),- chat_search_results: z.array(+ z+ .object({+ tags: z+ .array(+ z.object({+ label: z.string(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ })+ )+ .optional(),+ })+ .and(+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.intersection(z.object({- chat_message_id: z- .union([z.string().uuid(), z.null()])+ document_id: z.string().uuid(),+ document_name: z.string(),+ document_search_results: z.array(+ z.object({+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ node_id: z.union([z.string(), z.null()]).optional(),+ raw_content: z.union([z.string(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ file_type: z.union([z.string(), z.null()]).optional(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ project_id: z.union([z.string(), z.null()]).optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ }),+ z.null(),+ ]).optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- role: z.union([z.string(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- })+ name: z.string(),+ owner_id: z.string(),+ sub_type: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('task'), z.literal('snippet')];+ 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(),+ }),+ z.object({ type: z.literal('document') })),- id: z.string().uuid(),- metadata: z- .union([- z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- user_id: z.string(),- }),- z.object({ type: z.literal('chat') })- ),- z.intersection(- z.object({- created_at: z.string().datetime({ offset: true }),- email_message_search_results: z.array(+ z.intersection(z.object({- bcc: z.array(z.string()),- cc: z.array(z.string()),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- labels: z.array(z.string()),- message_id: z.union([z.string().uuid(), z.null()]).optional(),- pretty_sender: z.string(),- recipients: z.array(z.string()),- score: z.union([z.number(), z.null()]).optional(),- sender: z.string(),- sent_at: z- .union([z.string().datetime({ offset: true }), z.null()])+ chat_id: z.string().uuid(),+ chat_search_results: z.array(+ z.object({+ chat_message_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ role: z.union([z.string(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ project_id: z.union([z.string(), z.null()]).optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ }),+ z.null(),+ ]).optional(),- })+ name: z.string(),+ owner_id: z.string(),+ user_id: z.string(),+ }),+ z.object({ type: z.literal('chat') })),- id: z.string().uuid(),- inbox_visible: z.boolean(),- is_draft: z.boolean(),- is_important: z.boolean(),- is_read: z.boolean(),- link_id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- owner_id: z.string(),- participants: z.array(+ z.intersection(z.object({- email: z.string(),+ created_at: z.string().datetime({ offset: true }),+ email_message_search_results: z.array(+ z.object({+ bcc: z.array(z.string()),+ cc: z.array(z.string()),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ labels: z.array(z.string()),+ message_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ pretty_sender: z.string(),+ recipients: z.array(z.string()),+ score: z.union([z.number(), z.null()]).optional(),+ sender: z.string(),+ sent_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ })+ ),+ id: z.string().uuid(),+ inbox_visible: z.boolean(),+ is_draft: z.boolean(),+ is_important: z.boolean(),+ is_read: z.boolean(),+ link_id: z.string().uuid(),name: z.union([z.string(), z.null()]).optional(),- })- ),- snippet: z.union([z.string(), z.null()]).optional(),- subject: z.union([z.string(), z.null()]).optional(),- thread_id: z.string().uuid(),- updated_at: z.string().datetime({ offset: true }),- user_id: z.string(),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.object({ type: z.literal('email') })- ),- z.intersection(- z.object({- channel_id: z.string().uuid(),- channel_message_search_results: z.array(- z.object({- created_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- message_id: z.union([z.string().uuid(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- sender_id: z.union([z.string(), z.null()]).optional(),- thread_id: z.union([z.string().uuid(), z.null()]).optional(),- updated_at: z+ owner_id: z.string(),+ participants: z.array(+ z.object({+ email: z.string(),+ name: z.union([z.string(), z.null()]).optional(),+ })+ ),+ snippet: z.union([z.string(), z.null()]).optional(),+ subject: z.union([z.string(), z.null()]).optional(),+ thread_id: z.string().uuid(),+ updated_at: z.string().datetime({ offset: true }),+ user_id: z.string(),+ viewed_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- })+ }),+ z.object({ type: z.literal('email') })),- channel_type: z.string(),- id: z.string().uuid(),- metadata: z- .union([- z.object({- created_at: z.string().datetime({ offset: true }),- interacted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.null(),- ])- .optional(),- owner_id: z.union([z.string(), z.null()]).optional(),- }),- z.object({ type: z.literal('channel') })- ),- z.intersection(- z.object({- created_at: z.string().datetime({ offset: true }),- id: z.string().uuid(),- metadata: z- .union([- z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- parent_project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- project_search_results: z.array(+ z.intersection(z.object({- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- score: z.union([z.number(), z.null()]).optional(),- })+ channel_id: z.string().uuid(),+ channel_message_search_results: z.array(+ z.object({+ created_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ deleted_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ message_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ score: z.union([z.number(), z.null()]).optional(),+ sender_id: z.union([z.string(), z.null()]).optional(),+ thread_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ updated_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ })+ ),+ channel_type: z.string(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ interacted_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ owner_id: z.union([z.string(), z.null()]).optional(),+ }),+ z.object({ type: z.literal('channel') })),- updated_at: z.string().datetime({ offset: true }),- }),- z.object({ type: z.literal('project') })- ),- z.intersection(- z.object({- call_id: z.string().uuid(),- call_search_results: z.array(+ z.intersection(z.object({- ended_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- score: z.union([z.number(), z.null()]).optional(),- sequence_num: z.union([z.number().int(), z.null()]).optional(),- speaker_id: z.union([z.string(), z.null()]).optional(),- started_at: z- .union([z.string().datetime({ offset: true }), z.null()])+ created_at: z.string().datetime({ offset: true }),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ parent_project_id: z+ .union([z.string(), z.null()])+ .optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([+ z.string().datetime({ offset: true }),+ z.null(),+ ])+ .optional(),+ }),+ z.null(),+ ]).optional(),- transcript_id: z- .union([z.string().uuid(), z.null()])+ name: z.string(),+ owner_id: z.string(),+ project_search_results: z.array(+ z.object({+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ updated_at: z.string().datetime({ offset: true }),+ }),+ z.object({ type: z.literal('project') })+ ),+ z.intersection(+ z.object({+ call_id: z.string().uuid(),+ call_search_results: z.array(+ z.object({+ ended_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ score: z.union([z.number(), z.null()]).optional(),+ sequence_num: z+ .union([z.number().int(), z.null()])+ .optional(),+ speaker_id: z.union([z.string(), z.null()]).optional(),+ started_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ transcript_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ })+ ),+ channel_id: z.string().uuid(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ attended: z.boolean(),+ channel_name: z.union([z.string(), z.null()]).optional(),+ created_by: z.string(),+ duration_ms: z.number().int(),+ ended_at: z.string().datetime({ offset: true }),+ started_at: z.string().datetime({ offset: true }),+ status: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('ATTENDED'),+ z.literal('MISSED'),+ z.literal('UNATTENDED'),+ ];+ 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',+ });+ }+ }),+ updated_at: z.string().datetime({ offset: true }),+ }),+ z.null(),+ ]).optional(),- })+ name: z.union([z.string(), z.null()]).optional(),+ owner_id: z.string(),+ participant_ids: z.array(z.string()),+ }),+ z.object({ type: z.literal('call') })),- channel_id: z.string().uuid(),- id: z.string().uuid(),- metadata: z- .union([- z.object({- attended: z.boolean(),- channel_name: z.union([z.string(), z.null()]).optional(),- created_by: z.string(),- duration_ms: z.number().int(),- ended_at: z.string().datetime({ offset: true }),- started_at: z.string().datetime({ offset: true }),- status: z.any().superRefine((x, ctx) => {- const schemas = [- z.literal('ATTENDED'),- z.literal('MISSED'),- z.literal('UNATTENDED'),- ];- 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',- });- }- }),- updated_at: z.string().datetime({ offset: true }),- }),- z.null(),- ])- .optional(),- name: z.union([z.string(), z.null()]).optional(),- owner_id: z.string(),- participant_ids: z.array(z.string()),- }),- z.object({ type: z.literal('call') })- ),- z.intersection(- z.object({- createdAt: z.string().datetime({ offset: true }),- description: z.union([z.string(), z.null()]).optional(),- domains: z.array(+ z.intersection(z.object({- companyId: z.string().uuid(),createdAt: z.string().datetime({ offset: true }),- domain: z.string(),+ description: z.union([z.string(), z.null()]).optional(),+ domains: z.array(+ z.object({+ companyId: z.string().uuid(),+ createdAt: z.string().datetime({ offset: true }),+ domain: z.string(),+ id: z.string().uuid(),+ })+ ),+ hidden: z.boolean(),id: z.string().uuid(),- })+ name: z.union([z.string(), z.null()]).optional(),+ nameHighlighted: z.union([z.string(), z.null()]).optional(),+ teamId: z.string().uuid(),+ updatedAt: z.string().datetime({ offset: true }),+ }),+ z.object({ type: z.literal('company') })),- hidden: z.boolean(),- id: z.string().uuid(),- name: z.union([z.string(), z.null()]).optional(),- nameHighlighted: z.union([z.string(), z.null()]).optional(),- teamId: z.string().uuid(),- updatedAt: z.string().datetime({ offset: true }),- }),- z.object({ type: z.literal('company') })- ),- ];- 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',- });- }- })+ ];+ 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',+ });+ }+ })+ )),});@@ -568,6 +665,7 @@ export const GetEntityPropertiesResponse = z.object({properties: z.array(z.object({currentValue: z.any().optional(),+ currentValueLabels: z.union([z.array(z.string()), z.null()]).optional(),dataType: z.string(),displayName: z.string(),isMultiSelect: z.boolean(),@@ -580,6 +678,30 @@ export const GetEntityPropertiesResponse = z.object({})),propertyDefinitionId: z.string().uuid(),+ scope: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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(),})),summary: z.string(),@@ -758,6 +880,38 @@ export const ListEntities = z.object({}}).optional(),+ tags: z+ .union([+ z.array(+ z.object({+ label: z.string(),+ scope: z.union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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(),+ ]),+ })+ ),+ z.null(),+ ])+ .optional(),});export const ListEntitiesResponse = z.object({@@ -767,21 +921,117 @@ export const ListEntitiesResponse = z.object({z.object({id: z.string().uuid(),name: z.string(),+ tags: z.array(+ z.object({+ label: z.string(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ })+ ),type: z.literal('document'),}),z.object({id: z.string().uuid(),name: z.string(),+ tags: z.array(+ z.object({+ label: z.string(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ })+ ),type: z.literal('aiChat'),}),z.object({id: z.string().uuid(),name: z.string(),+ tags: z.array(+ z.object({+ label: z.string(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ })+ ),type: z.literal('project'),}),z.object({id: z.string().uuid(),subject: z.union([z.string(), z.null()]).optional(),+ tags: z.array(+ z.object({+ label: z.string(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ })+ ),type: z.literal('email'),}),z.object({@@ -914,6 +1164,42 @@ export const ListNotificationsResponse = z.object({),});+export const ListTags = z.record(z.any());++export const ListTagsResponse = z.object({+ summary: z.string(),+ tagSets: z.array(+ z.object({+ propertyDefinitionId: z.string().uuid(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ tags: z.array(+ z.object({+ color: z.union([z.string(), z.null()]).optional(),+ id: z.string().uuid(),+ label: z.string(),+ })+ ),+ })+ ),+});+export const ListTeamMembers = z.record(z.any());export const ListTeamMembersResponse = z.object({@@ -980,6 +1266,38 @@ export const NameSearch = z.object({).optional(),name: z.string(),+ tags: z+ .union([+ z.array(+ z.object({+ label: z.string(),+ scope: z.union([+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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(),+ ]),+ })+ ),+ z.null(),+ ])+ .optional(),});export const ReadCallRecord = z.object({ callId: z.string().uuid() });@@ -2168,6 +2486,7 @@ export const UserToolResponse = z.any().superRefine((x, ctx) => {});export const SetEntityProperty = z.object({+ add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),boolean_value: z.union([z.boolean(), z.null()]).default(null),date_value: z.union([z.string().datetime({ offset: true }), z.null()])@@ -2227,6 +2546,9 @@ export const SetEntityProperty = z.object({option_id: z.union([z.string().uuid(), z.null()]).default(null),option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),property_definition_id: z.string().uuid(),+ remove_option_ids: z+ .union([z.array(z.string().uuid()), z.null()])+ .default(null),string_value: z.union([z.string(), z.null()]).default(null),});diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 680074939e..e470fc5632 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -52,6 +52,7 @@ type ToolParserMap = {call: types.ListNotifications;response: types.ListNotificationsResponse;};+ ListTags: { call: types.ListTags; response: types.ListTagsResponse };ListTeamMembers: {call: types.ListTeamMembers;response: types.ListTeamMembersResponse;@@ -174,6 +175,7 @@ const toolParserMap = {call: schemas.ListNotifications,response: schemas.ListNotificationsResponse,},+ ListTags: { call: schemas.ListTags, response: schemas.ListTagsResponse },ListTeamMembers: {call: schemas.ListTeamMembers,response: schemas.ListTeamMembersResponse,@@ -304,6 +306,7 @@ type ToolDataMap = {call: types.ListNotifications;response: types.ListNotificationsResponse;};+ ListTags: { call: types.ListTags; response: types.ListTagsResponse };ListTeamMembers: {call: types.ListTeamMembers;response: types.ListTeamMembersResponse;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 110faa17cb..71f7d48bab 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -12,6 +12,10 @@* Ordered from least to most access top -> bottom*/export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';+/**+ * Which tag set a tag belongs to, relative to the caller.+ */+export type TagScope = 'personal' | 'team';/*** Content of a bash code execution response - either a result or an error*/@@ -150,6 +154,10 @@ export type EntityItem =* Document name.*/name: string;+ /**+ * Tags on the document visible to the user.+ */+ tags: AppliedTag[];type: 'document';}| {@@ -161,6 +169,10 @@ export type EntityItem =* Chat name.*/name: string;+ /**+ * Tags on the chat visible to the user.+ */+ tags: AppliedTag[];type: 'aiChat';}| {@@ -172,6 +184,10 @@ export type EntityItem =* Project name.*/name: string;+ /**+ * Tags on the project visible to the user.+ */+ tags: AppliedTag[];type: 'project';}| {@@ -183,6 +199,10 @@ export type EntityItem =* Email subject, when present.*/subject?: string | null;+ /**+ * Tags on the thread visible to the user.+ */+ tags: AppliedTag[];type: 'email';}| {@@ -321,7 +341,16 @@ export type SearchResult = {type: 'web_search_result';url: string;};-export type UnifiedSearchResponseItem =+/**+ * A search result annotated with the caller-visible tags on the item.+ */+export type TaggedSearchResult = {+ /**+ * Tags on this item visible to the user.+ */+ tags?: AppliedTag[];+} & TaggedSearchResult1;+export type TaggedSearchResult1 =| (DocumentSearchResponseItemWithMetadata & {type: 'document';})@@ -431,6 +460,16 @@ export type WebFetchErrorCode =*/export type WebSearchContent = SearchResult[] | WebSearchToolError;+/**+ * A tag applied to an item, resolved to its human-readable label.+ */+export interface AppliedTag {+ /**+ * The tag's label.+ */+ label: string;+ scope: TagScope;+}/*** Execute a bash command in a sandboxed environment using Claude's built-in code execution tool.*/@@ -975,7 +1014,7 @@ export interface CompanyPropertyOption {id: string;}/**- * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content 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. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts 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 content, 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 (e.g. an exact word, identifier, or full email address). 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 rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.+ * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content 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. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts 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 content, 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 (e.g. an exact word, identifier, or full email address). 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 rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, and projects 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).*/export interface ContentSearch {/**@@ -991,6 +1030,23 @@ export interface ContentSearch {* The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token (or full email address) matching instead of prefix.*/query: string;+ /**+ * Restrict results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.+ */+ tags?: TagFilter[] | null;+}+/**+ * A tag selector in a tool request, matched by label against the caller's tag sets.+ */+export interface TagFilter {+ /**+ * The tag label to match, case-insensitive.+ */+ label: string;+ /**+ * Restrict the label match to "personal" or "team". Omit to match both scopes.+ */+ scope?: TagScope | null;}export interface ConversationRecord {chat_id: string;@@ -1406,7 +1462,7 @@ export interface GetCompanyResponse {summary: string;}/**- * Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties.+ * Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Select and tag values also come back resolved as human-readable labels in currentValueLabels. Tags are properties with dataType "tag"; only tags visible to the user (their own and their team's) are returned. Use ListTags to see every tag available to the user, and SetEntityProperty with the tag definition id and add_option_ids/remove_option_ids to apply or remove tags. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties.*/export interface GetEntityProperties {/**@@ -1439,7 +1495,12 @@ export interface ToolPropertyItem {[k: string]: unknown;};/**- * The data type (boolean, date, number, string, select_number, select_string, entity, link).+ * The current value's option ids resolved to human-readable labels, for+ * select and tag properties with a value set.+ */+ currentValueLabels?: string[] | null;+ /**+ * The data type (boolean, date, number, string, select_number, select_string, tag, entity, link).*/dataType: string;/**@@ -1462,6 +1523,10 @@ export interface ToolPropertyItem {* The property definition ID. Use this when calling SetEntityProperty.*/propertyDefinitionId: string;+ /**+ * For tag properties, whether this is the user's personal set or a team set.+ */+ scope?: TagScope | null;}/*** A property option in the tool response.@@ -1634,7 +1699,7 @@ export interface ListCompaniesResponse {summary: string;}/**- * Browse the user's Macro workspace to see recent items they have access to. Returns Macro documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. Start here for activity-summary questions such as "what happened today", "what's going on", "catch me up", or "what happened in standup today"; apply precise time, type, channel, or mailbox filters when the user gives that scope. For Macro task requests such as "list my tasks", "tasks assigned to me", or "tasks I completed yesterday", prefer this tool over external task trackers such as Linear unless the user explicitly asks for Linear. Macro tasks are document items with df subtype {"l":{"dst":"task"}} and includeTypes ["document"]. Filter task Status and Assignees through propf using entity_type TASK: Status property 00000001-0000-0000-0000-000000000002, Completed option 00000001-0000-0000-0002-000000000004, Assignees property 00000001-0000-0000-0000-000000000001. The current user's assignee entity id is their Macro user id, usually macro|<their email address from context>. For "completed yesterday", combine status Completed, assigned-to-me, and a df updatedAt yesterday window with ua gte/lt ISO timestamps. For finding specific items by name or content, use the search tool instead.+ * Browse the user's Macro workspace to see recent items they have access to. Returns Macro documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. Start here for activity-summary questions such as "what happened today", "what's going on", "catch me up", or "what happened in standup today"; apply precise time, type, channel, or mailbox filters when the user gives that scope. For Macro task requests such as "list my tasks", "tasks assigned to me", or "tasks I completed yesterday", prefer this tool over external task trackers such as Linear unless the user explicitly asks for Linear. Macro tasks are document items with df subtype {"l":{"dst":"task"}} and includeTypes ["document"]. Filter task Status and Assignees through propf using entity_type TASK: Status property 00000001-0000-0000-0000-000000000002, Completed option 00000001-0000-0000-0002-000000000004, Assignees property 00000001-0000-0000-0000-000000000001. The current user's assignee entity id is their Macro user id, usually macro|<their email address from context>. For "completed yesterday", combine status Completed, assigned-to-me, and a df updatedAt yesterday window with ua gte/lt ISO timestamps. Returned documents, AI chats, projects, and emails include the tags visible to the user as {label, scope} pairs. To filter by tag (e.g. "my items tagged bug-report"), pass the tag labels in the tags argument — ListTags shows which tags exist. For finding specific items by name or content, use the search tool instead.*/export interface ListEntities {/**@@ -1714,6 +1779,10 @@ export interface ListEntities {[k: string]: unknown;};sortBy?: SortBy;+ /**+ * Filter results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, tasks, projects, emails, AI chats) can match a tag filter. Prefer this over hand-building a propf filter for tags.+ */+ tags?: TagFilter[] | null;}/*** Response returned by the list entities AI tool.@@ -1919,6 +1988,55 @@ export interface NotificationItem {*/senderId?: string | null;}+/**+ * List the tags available to the user: their personal tag set plus their team's set when they belong to a team. Each tag has a human-readable label, an option id, and optionally a color. Refer to tags by label when talking to the user. To filter items by tag, pass the labels to the tags argument of ListEntities, ContentSearch, or NameSearch. To apply or remove a tag on an entity, call SetEntityProperty with the set's propertyDefinitionId and the tag's option id in add_option_ids or remove_option_ids — never rewrite the full value to add or remove one tag. Call this before tag operations when you don't already know the user's tags.+ */+export type ListTags = {};+/**+ * Response from [`ListTags`].+ */+export interface ListTagsResponse {+ /**+ * Human-readable summary.+ */+ summary: string;+ /**+ * The tag sets available to the caller.+ */+ tagSets: ToolTagSet[];+}+/**+ * One tag set available to the caller.+ */+export interface ToolTagSet {+ /**+ * The tag property definition id. Use it as propertyDefinitionId when+ * calling SetEntityProperty to apply or remove one of this set's tags.+ */+ propertyDefinitionId: string;+ scope: TagScope;+ /**+ * The tags in this set.+ */+ tags: ToolTag[];+}+/**+ * A single tag in a tag set.+ */+export interface ToolTag {+ /**+ * The tag's display color, when set.+ */+ color?: string | null;+ /**+ * The tag's option id. Use it with SetEntityProperty to apply or remove the tag.+ */+ id: string;+ /**+ * The tag's human-readable label.+ */+ label: string;+}/*** List the current members and pending invites for the authenticated user's team. Requires the caller to be a team member. The returned roles (owner/admin/member) are app permission levels only, not job titles — they say nothing about the org chart. Never infer that someone is a founder, an executive, or the company's owner from their workspace role.*/@@ -2037,7 +2155,7 @@ export interface MarkNotificationsSeen {notificationIds: string[];}/**- * Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. 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.+ * Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. 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, AI chats, and projects 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).*/export interface NameSearch {/**@@ -2053,6 +2171,10 @@ export interface NameSearch {* The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a multi-word phrase in double quotes to match it as one phrase. Use matchType 'exact' for whole-token matching instead of prefix.*/name: string;+ /**+ * Restrict results to items carrying at least one of the given tags (OR semantics). Each entry names a tag by its label, matched case-insensitively against the user's own tags; only set scope ("personal" or "team") when the user distinguishes between their personal and team tags. An unknown label fails with the list of available tags — call ListTags first when unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can match, so channels and call records are dropped while a tag filter is active.+ */+ tags?: TagFilter[] | null;}/*** Metadata for a project fetched from the database@@ -2844,7 +2966,7 @@ export interface RenameDocumentResponse {success: boolean;}export interface SearchToolResponse {- results: UnifiedSearchResponseItem[];+ results: TaggedSearchResult[];}/*** Find tools from connected integrations (e.g. Slack, Gmail, Linear, GitHub) by keyword. The top matches are loaded automatically: call them by exact name on your next step. Matches past the auto-load cap come back under `additional_matches` and need `LoadTools` first. Searching is cheap, so cast a wide net.@@ -2949,6 +3071,8 @@ export interface SendEmail {/*** Set or update a property value on an entity (document, task, project, etc.). Provide the property_definition_id and exactly one value field matching the property's data type.*+ * For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.+ ** Tasks always have these system properties (use these property_definition_id values directly):* - Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'.* - Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005).@@ -2967,6 +3091,10 @@ export interface SendEmail {* For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options.*/export interface SetEntityProperty {+ /**+ * For multi-select properties (including tags): add these options to the current value atomically without touching other options. Cannot be combined with other value fields.+ */+ add_option_ids?: string[] | null;/*** For boolean properties.*/@@ -3005,13 +3133,17 @@ export interface SetEntityProperty {*/option_id?: string | null;/**- * For multi-select properties. The option UUIDs from available options.+ * For multi-select properties. Replaces the entire value with these option UUIDs — prefer add_option_ids / remove_option_ids for adding or removing specific options.*/option_ids?: string[] | null;/*** The property definition ID. Get this from GetEntityProperties results.*/property_definition_id: string;+ /**+ * For multi-select properties (including tags): remove these options from the current value atomically without touching other options. Removing an absent option is a no-op. Cannot be combined with other value fields.+ */+ remove_option_ids?: string[] | null;/*** For string properties.*/diff --git a/rust/cloud-storage/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.json b/rust/cloud-storage/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.jsonnew file mode 100644index 0000000000..9b50011e48--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354.json@@ -0,0 +1,169 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n pd.id,\n pd.team_id,\n pd.user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at,\n pd.updated_at,\n pd.is_system,\n po.id as \"option_id?\",\n po.display_order as \"option_display_order?\",\n po.number_value as option_number_value,\n po.string_value as option_string_value,\n po.color as option_color,\n po.created_at as \"option_created_at?\",\n po.updated_at as \"option_updated_at?\"\n FROM property_definitions pd\n LEFT JOIN property_options po ON pd.id = po.property_definition_id\n WHERE\n pd.data_type = $2\n AND (\n pd.user_id = $1\n OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $1)\n )\n ORDER BY pd.user_id NULLS LAST, po.display_order, LOWER(po.string_value)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "display_name",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "data_type: DataType",+ "type_info": {+ "Custom": {+ "name": "property_data_type",+ "kind": {+ "Enum": [+ "BOOLEAN",+ "DATE",+ "NUMBER",+ "STRING",+ "SELECT_NUMBER",+ "SELECT_STRING",+ "ENTITY",+ "LINK",+ "TAG"+ ]+ }+ }+ }+ },+ {+ "ordinal": 5,+ "name": "is_multi_select",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "specific_entity_type: Option<EntityType>",+ "type_info": {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ }+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "is_system",+ "type_info": "Bool"+ },+ {+ "ordinal": 10,+ "name": "option_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 11,+ "name": "option_display_order?",+ "type_info": "Int4"+ },+ {+ "ordinal": 12,+ "name": "option_number_value",+ "type_info": "Float8"+ },+ {+ "ordinal": 13,+ "name": "option_string_value",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "option_color",+ "type_info": "Text"+ },+ {+ "ordinal": 15,+ "name": "option_created_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "option_updated_at?",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "property_data_type",+ "kind": {+ "Enum": [+ "BOOLEAN",+ "DATE",+ "NUMBER",+ "STRING",+ "SELECT_NUMBER",+ "SELECT_STRING",+ "ENTITY",+ "LINK",+ "TAG"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ false,+ false,+ false,+ false,+ false,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "7d08bfd9600cf2460a1ee8769d415d3963907a083ffe68ef8eaf679e898ca354"+}diff --git a/rust/cloud-storage/.sqlx/query-8d5ffbdd5be9b1031c7da47bc2d4bcbee35802a575387ef081a09031b42f7de9.json b/rust/cloud-storage/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.jsonsimilarity index 55%rename from rust/cloud-storage/.sqlx/query-8d5ffbdd5be9b1031c7da47bc2d4bcbee35802a575387ef081a09031b42f7de9.jsonrename to rust/cloud-storage/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.jsonindex 7fe732d356..0f8c6f84b5 100644--- a/rust/cloud-storage/.sqlx/query-8d5ffbdd5be9b1031c7da47bc2d4bcbee35802a575387ef081a09031b42f7de9.json+++ b/rust/cloud-storage/.sqlx/query-f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n ep.property_definition_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.is_system,\n ep.values as \"values: serde_json::Value\"\n FROM entity_properties ep\n INNER JOIN property_definitions pd ON pd.id = ep.property_definition_id\n WHERE ep.entity_id = $1\n AND ep.entity_type = $2\n ORDER BY LOWER(pd.display_name)\n ",+ "query": "\n SELECT\n ep.property_definition_id,\n pd.team_id,\n pd.user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.is_system,\n ep.values as \"values: serde_json::Value\"\n FROM entity_properties ep\n INNER JOIN property_definitions pd ON pd.id = ep.property_definition_id\n WHERE ep.entity_id = $1\n AND ep.entity_type = $2\n AND (\n pd.data_type <> $4\n OR pd.user_id = $3\n OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $3)\n )\n ORDER BY LOWER(pd.display_name)\n ","describe": {"columns": [{@@ -10,11 +10,21 @@},{"ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,"name": "display_name","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 4,"name": "data_type: DataType","type_info": {"Custom": {@@ -36,17 +46,17 @@}},{- "ordinal": 3,+ "ordinal": 5,"name": "is_multi_select","type_info": "Bool"},{- "ordinal": 4,+ "ordinal": 6,"name": "is_system","type_info": "Bool"},{- "ordinal": 5,+ "ordinal": 7,"name": "values: serde_json::Value","type_info": "Jsonb"}@@ -70,11 +80,32 @@]}}+ },+ "Text",+ {+ "Custom": {+ "name": "property_data_type",+ "kind": {+ "Enum": [+ "BOOLEAN",+ "DATE",+ "NUMBER",+ "STRING",+ "SELECT_NUMBER",+ "SELECT_STRING",+ "ENTITY",+ "LINK",+ "TAG"+ ]+ }+ }}]},"nullable": [false,+ true,+ true,false,false,false,@@ -82,5 +113,5 @@true]},- "hash": "8d5ffbdd5be9b1031c7da47bc2d4bcbee35802a575387ef081a09031b42f7de9"+ "hash": "f54491fb1559e95fd91f725c67f260e2057b1bf4679801f170bcf8f891027282"}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 6ec35a6032..8467f3c360 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -215,6 +215,7 @@ dependencies = ["models_permissions","models_properties","models_search",+ "models_soup","non_empty","notification","prompt",@@ -8694,6 +8695,7 @@ version = "0.1.0"dependencies = ["chrono","document_sub_type",+ "schemars 1.2.1","serde","serde_json","serde_with",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 0f97ae5709..22c7d77c47 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -55,6 +55,7 @@ notification = { path = "../notification", features = ["ai_tool"] }prompt = { path = "../prompt" }models_properties = { path = "../models_properties" }models_search = { path = "../models_search" }+models_soup = { path = "../models_soup" }rand.workspace = truereqwest.workspace = truereadonly_pool = { path = "../readonly_pool" }diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 9de16b33c2..1e93cce969 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -1,10 +1,13 @@use super::context::SearchToolContext;-use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse};+use super::types::{+ PAGE_SIZE, SearchMatchType, SearchToolResponse, annotate_result_tags, resolve_tag_filters,+};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};use macro_user_id::user_id::MacroUserIdStr;+use models_properties::service::tag_sets::TagFilter;use models_search::unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};@@ -14,7 +17,7 @@ use serde::Deserialize;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content 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. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts 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 content, 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 (e.g. an exact word, identifier, or full email address). 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 rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",+ description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content 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. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts 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 content, 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 (e.g. an exact word, identifier, or full email address). 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 rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type. Results for documents, emails, AI chats, and projects 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).",title = "ContentSearch")]pub struct ContentSearch {@@ -40,6 +43,16 @@ pub struct ContentSearch {)]#[serde(default)]pub inbox: Option<String>,++ #[schemars(description = "\+Restrict results to items carrying at least one of the given tags (OR semantics). Each entry \+names a tag by its label, matched case-insensitively against the user's own tags; only set \+scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \+tags. An unknown label fails with the list of available tags — call ListTags first when \+unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can \+match, so channels and call records are dropped while a tag filter is active.")]+ #[serde(default)]+ pub tags: Option<Vec<TagFilter>>,}#[async_trait]@@ -87,8 +100,22 @@ impl AsyncTool<SearchToolContext> for ContentSearch {)?;email_filters.link_ids = vec![link.id.to_string()];}+ let mut tag_sets = None;+ let mut tag_option_ids = Vec::new();+ if let Some(filters) = self.tags.as_deref().filter(|t| !t.is_empty()) {+ let (sets, option_ids) = resolve_tag_filters(+ &search_context,+ (*request_context.user_id).as_ref(),+ filters,+ )+ .await?;+ tag_sets = Some(sets);+ tag_option_ids = option_ids;+ }+let base_filters = EntityFilters {email_filters,+ tag_option_ids,..Default::default()};let search_request = UnifiedSearchRequest {@@ -121,6 +148,14 @@ impl AsyncTool<SearchToolContext> for ContentSearch {results.retain(|item| item.entity_id() != self_chat_id);}+ let results = annotate_result_tags(+ &search_context,+ (*request_context.user_id).as_ref(),+ results,+ tag_sets,+ )+ .await?;+Ok(SearchToolResponse { results })}}diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/context.rs b/rust/cloud-storage/ai_tools/src/search/search_service/context.rsindex 264e8a0409..c2b02fa36b 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/context.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/context.rs@@ -1,4 +1,4 @@-use crate::tool_context::{ToolEmailService, ToolServiceContext};+use crate::tool_context::{ToolEmailService, ToolPropertiesService, ToolServiceContext};use ai_usage::AiFeature;use axum::extract::FromRef;use search_service_client::SearchServiceClient;@@ -17,6 +17,8 @@ pub struct SearchToolContext {/// Email service used to resolve an `inbox` selector to a link id when a/// search is scoped to a single inbox.pub email_service: Arc<ToolEmailService>,+ /// Properties service used to resolve tag labels for filters and results.+ pub properties_service: Arc<ToolPropertiesService>,/// Entity id of the chat this request belongs to, when the request is an/// interactive chat session. `None` for every other feature, in which case/// nothing is excluded.@@ -35,6 +37,7 @@ impl FromRef<ToolServiceContext> for SearchToolContext {SearchToolContext {search_client: ctx.search_service_client.clone(),email_service: ctx.email_service.clone(),+ properties_service: ctx.properties_tool_context.service.clone(),self_chat_id,}}diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex cfc1ba66dd..d7407c0f83 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -1,10 +1,13 @@use super::context::SearchToolContext;-use super::types::{PAGE_SIZE, SearchMatchType, SearchToolResponse};+use super::types::{+ PAGE_SIZE, SearchMatchType, SearchToolResponse, annotate_result_tags, resolve_tag_filters,+};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};use macro_user_id::user_id::MacroUserIdStr;+use models_properties::service::tag_sets::TagFilter;use models_search::unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include,};@@ -14,7 +17,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, chat title, project name, the channel name a call belongs to. 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.",+ description = "Search items by their name or title: document name, email subject, chat title, project name, the channel name a call belongs to. 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, AI chats, and projects 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).",title = "NameSearch")]pub struct NameSearch {@@ -40,6 +43,16 @@ pub struct NameSearch {)]#[serde(default)]pub inbox: Option<String>,++ #[schemars(description = "\+Restrict results to items carrying at least one of the given tags (OR semantics). Each entry \+names a tag by its label, matched case-insensitively against the user's own tags; only set \+scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \+tags. An unknown label fails with the list of available tags — call ListTags first when \+unsure what tags exist. Only taggable items (documents, emails, AI chats, projects) can \+match, so channels and call records are dropped while a tag filter is active.")]+ #[serde(default)]+ pub tags: Option<Vec<TagFilter>>,}#[async_trait]@@ -87,8 +100,22 @@ impl AsyncTool<SearchToolContext> for NameSearch {)?;email_filters.link_ids = vec![link.id.to_string()];}+ let mut tag_sets = None;+ let mut tag_option_ids = Vec::new();+ if let Some(filters) = self.tags.as_deref().filter(|t| !t.is_empty()) {+ let (sets, option_ids) = resolve_tag_filters(+ &search_context,+ (*request_context.user_id).as_ref(),+ filters,+ )+ .await?;+ tag_sets = Some(sets);+ tag_option_ids = option_ids;+ }+let base_filters = EntityFilters {email_filters,+ tag_option_ids,..Default::default()};let search_request = UnifiedSearchRequest {@@ -121,6 +148,14 @@ impl AsyncTool<SearchToolContext> for NameSearch {results.retain(|item| item.entity_id() != self_chat_id);}+ let results = annotate_result_tags(+ &search_context,+ (*request_context.user_id).as_ref(),+ results,+ tag_sets,+ )+ .await?;+Ok(SearchToolResponse { results })}}diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/types.rs b/rust/cloud-storage/ai_tools/src/search/search_service/types.rsindex dc89fce7f0..49be1aef1b 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/types.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/types.rs@@ -1,8 +1,16 @@+use ai_toolset::{ToolCallError, ToolResult};+use models_properties::DataType;+use models_properties::service::property_value::PropertyValue;+use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter};use models_search::MatchType;use models_search::unified::UnifiedSearchResponseItem;+use models_soup::SoupProperty;+use properties::PropertiesService as _;use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use super::context::SearchToolContext;+pub const PAGE_SIZE: i64 = 50;/// How search tools match query terms. Restricted to partial/exact — the@@ -27,7 +35,132 @@ impl From<SearchMatchType> for MatchType {}}+/// A search result annotated with the caller-visible tags on the item.+#[derive(Serialize, Deserialize, Debug, JsonSchema)]+pub struct TaggedSearchResult {+ /// The search result itself.+ #[serde(flatten)]+ pub item: UnifiedSearchResponseItem,+ /// Tags on this item visible to the user.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub tags: Vec<AppliedTag>,+}+#[derive(Serialize, Deserialize, Debug, JsonSchema)]pub struct SearchToolResponse {- pub results: Vec<UnifiedSearchResponseItem>,+ pub results: Vec<TaggedSearchResult>,+}++/// Resolve the model's tag filters against the caller's tag sets, returning+/// the matched option ids for `EntityFilters::tag_option_ids` plus the sets+/// for later result annotation. An unknown label fails with the available tags.+pub(super) async fn resolve_tag_filters(+ context: &SearchToolContext,+ user_id: &str,+ filters: &[TagFilter],+) -> ToolResult<(CallerTagSets, Vec<String>)> {+ let sets = fetch_caller_tag_sets(context, user_id).await?;+ let resolved = sets.resolve_filters(filters).map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?;+ let option_ids = resolved+ .into_iter()+ .map(|option| option.option_id.to_string())+ .collect();+ Ok((sets, option_ids))+}++/// Annotate search results with caller-visible tags. Tag properties are+/// translated into `tags` labels and removed from the raw property payload;+/// non-tag properties pass through untouched. Tag sets are only fetched when+/// a result actually carries a tag property and none were supplied.+pub(super) async fn annotate_result_tags(+ context: &SearchToolContext,+ user_id: &str,+ results: Vec<UnifiedSearchResponseItem>,+ tag_sets: Option<CallerTagSets>,+) -> ToolResult<Vec<TaggedSearchResult>> {+ let any_tags = results.iter().any(|item| {+ item_properties(item).is_some_and(|props| {+ props+ .iter()+ .any(|p| p.definition.data_type == DataType::Tag)+ })+ });++ let tag_map = if any_tags {+ let sets = match tag_sets {+ Some(sets) => sets,+ None => fetch_caller_tag_sets(context, user_id).await?,+ };+ sets.applied_tag_by_option_id()+ } else {+ Default::default()+ };++ Ok(results+ .into_iter()+ .map(|mut item| {+ let mut tags: Vec<AppliedTag> = Vec::new();+ if let Some(props) = item_properties_mut(&mut item) {+ for property in props.iter() {+ if property.definition.data_type != DataType::Tag {+ continue;+ }+ let Some(PropertyValue::SelectOption(option_ids)) = &property.value else {+ continue;+ };+ for option_id in option_ids {+ if let Some(tag) = tag_map.get(option_id)+ && !tags.contains(tag)+ {+ tags.push(tag.clone());+ }+ }+ }+ props.retain(|p| p.definition.data_type != DataType::Tag);+ }+ TaggedSearchResult { item, tags }+ })+ .collect())+}++async fn fetch_caller_tag_sets(+ context: &SearchToolContext,+ user_id: &str,+) -> ToolResult<CallerTagSets> {+ let definitions = context+ .properties_service+ .list_caller_tag_sets(user_id)+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to resolve the user's tags: {e}"),+ internal_error: e.into(),+ })?;+ Ok(CallerTagSets::new(definitions))+}++fn item_properties(item: &UnifiedSearchResponseItem) -> Option<&Vec<SoupProperty>> {+ match item {+ UnifiedSearchResponseItem::Document(i) => i.properties.as_ref(),+ UnifiedSearchResponseItem::Chat(i) => i.properties.as_ref(),+ UnifiedSearchResponseItem::Email(i) => i.properties.as_ref(),+ UnifiedSearchResponseItem::Project(i) => i.properties.as_ref(),+ UnifiedSearchResponseItem::Channel(_)+ | UnifiedSearchResponseItem::Call(_)+ | UnifiedSearchResponseItem::Company(_) => None,+ }+}++fn item_properties_mut(item: &mut UnifiedSearchResponseItem) -> Option<&mut Vec<SoupProperty>> {+ match item {+ UnifiedSearchResponseItem::Document(i) => i.properties.as_mut(),+ UnifiedSearchResponseItem::Chat(i) => i.properties.as_mut(),+ UnifiedSearchResponseItem::Email(i) => i.properties.as_mut(),+ UnifiedSearchResponseItem::Project(i) => i.properties.as_mut(),+ UnifiedSearchResponseItem::Channel(_)+ | UnifiedSearchResponseItem::Call(_)+ | UnifiedSearchResponseItem::Company(_) => None,+ }}diff --git a/rust/cloud-storage/graphql_soup/src/schema.rs b/rust/cloud-storage/graphql_soup/src/schema.rsindex 943cda9884..32351592b4 100644--- a/rust/cloud-storage/graphql_soup/src/schema.rs+++ b/rust/cloud-storage/graphql_soup/src/schema.rs@@ -46,6 +46,16 @@ impl SoupService for SchemaOnlySoupService {) -> Result<Vec<soup::domain::models::GroupedSoupItem>, soup::domain::models::SoupErr> {Err(soup::domain::models::SoupErr::CommsErr)}++ async fn caller_tag_sets<'a>(+ &self,+ _user_id: macro_user_id::user_id::MacroUserIdStr<'a>,+ ) -> Result<+ Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,+ soup::domain::models::SoupErr,+ >{+ Err(soup::domain::models::SoupErr::CommsErr)+ }}/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.@@ -86,6 +96,16 @@ where) -> Result<Vec<soup::domain::models::GroupedSoupItem>, soup::domain::models::SoupErr> {self.0.get_user_soup_grouped(req).await}++ async fn caller_tag_sets<'a>(+ &self,+ user_id: macro_user_id::user_id::MacroUserIdStr<'a>,+ ) -> Result<+ Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,+ soup::domain::models::SoupErr,+ >{+ self.0.caller_tag_sets(user_id).await+ }}/// Root GraphQL query object for Soup.diff --git a/rust/cloud-storage/models_properties/Cargo.toml b/rust/cloud-storage/models_properties/Cargo.tomlindex c14d340149..645ed68a02 100644--- a/rust/cloud-storage/models_properties/Cargo.toml+++ b/rust/cloud-storage/models_properties/Cargo.toml@@ -7,6 +7,7 @@ version = "0.1.0"[dependencies]chrono = { workspace = true }document_sub_type = { path = "../document_sub_type" }+schemars = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }serde_with = { workspace = true }diff --git a/rust/cloud-storage/models_properties/src/service/mod.rs b/rust/cloud-storage/models_properties/src/service/mod.rsindex 0eab763237..71d01c4679 100644--- a/rust/cloud-storage/models_properties/src/service/mod.rs+++ b/rust/cloud-storage/models_properties/src/service/mod.rs@@ -11,4 +11,5 @@ pub mod property_definition;pub mod property_definition_with_options;pub mod property_option;pub mod property_value;+pub mod tag_sets;pub mod thread_metadata;diff --git a/rust/cloud-storage/models_properties/src/service/tag_sets.rs b/rust/cloud-storage/models_properties/src/service/tag_sets.rsnew file mode 100644index 0000000000..57df6686c0--- /dev/null+++ b/rust/cloud-storage/models_properties/src/service/tag_sets.rs@@ -0,0 +1,190 @@+//! Caller-visible tag sets and label resolution for AI tool surfaces.++#[cfg(test)]+mod test;++use std::collections::HashMap;++use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::shared::PropertyOwner;++use super::property_definition_with_options::PropertyDefinitionWithOptions;+use super::property_option::PropertyOptionValue;++/// Which tag set a tag belongs to, relative to the caller.+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, utoipa::ToSchema,+)]+#[serde(rename_all = "snake_case")]+pub enum TagScope {+ /// The caller's personal tag set.+ Personal,+ /// A team tag set the caller belongs to.+ Team,+}++/// A tag applied to an item, resolved to its human-readable label.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct AppliedTag {+ /// The tag's label.+ pub label: String,+ /// Whether the tag comes from the caller's personal set or a team set.+ pub scope: TagScope,+}++/// A tag selector in a tool request, matched by label against the caller's tag sets.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct TagFilter {+ /// The tag label to match, case-insensitive.+ #[schemars(description = "The tag label to match, case-insensitive.")]+ pub label: String,+ /// Restrict the match to one scope. When omitted, both the personal and+ /// team sets are matched.+ #[schemars(+ description = "Restrict the label match to \"personal\" or \"team\". Omit to match both scopes."+ )]+ #[serde(default)]+ pub scope: Option<TagScope>,+}++/// A tag filter label that matched nothing in the caller's tag sets.+#[derive(Debug, Clone, thiserror::Error)]+#[error("unknown tag \"{label}\"{}", format_available(available))]+pub struct UnknownTagError {+ /// The label that failed to resolve.+ pub label: String,+ /// Every label the caller can actually filter by.+ pub available: Vec<String>,+}++fn format_available(available: &[String]) -> String {+ if available.is_empty() {+ ". The user has no tags yet.".to_string()+ } else {+ format!(". Available tags: {}.", available.join(", "))+ }+}++/// One resolved tag option from the caller's sets.+#[derive(Debug, Clone)]+pub struct CallerTagOption {+ /// The owning tag property definition.+ pub definition_id: Uuid,+ /// The option id, used in property/tag filters and when applying the tag.+ pub option_id: Uuid,+ /// The tag's label.+ pub label: String,+ /// The tag's color, when set.+ pub color: Option<String>,+ /// Whether the tag is personal or team-scoped.+ pub scope: TagScope,+}++/// The tag sets visible to a caller (their personal set plus their teams' sets),+/// flattened for label/option resolution.+#[derive(Debug, Clone, Default)]+pub struct CallerTagSets {+ options: Vec<CallerTagOption>,+}++impl CallerTagSets {+ /// Flatten tag definitions into resolvable options. Definitions without a+ /// user or team owner are skipped.+ pub fn new(definitions: Vec<PropertyDefinitionWithOptions>) -> Self {+ let mut options = Vec::new();+ for def in definitions {+ let scope = match def.definition.owner {+ PropertyOwner::User { .. } => TagScope::Personal,+ PropertyOwner::Team { .. } => TagScope::Team,+ PropertyOwner::System => continue,+ };+ for option in def.property_options {+ let label = match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ };+ options.push(CallerTagOption {+ definition_id: def.definition.id,+ option_id: option.id,+ label,+ color: option.color,+ scope,+ });+ }+ }+ Self { options }+ }++ /// Every resolvable tag option.+ pub fn options(&self) -> &[CallerTagOption] {+ &self.options+ }++ /// True when the caller has no tags in any set.+ pub fn is_empty(&self) -> bool {+ self.options.is_empty()+ }++ /// Map from option id to its resolved applied-tag form.+ pub fn applied_tag_by_option_id(&self) -> HashMap<Uuid, AppliedTag> {+ self.options+ .iter()+ .map(|o| {+ (+ o.option_id,+ AppliedTag {+ label: o.label.clone(),+ scope: o.scope,+ },+ )+ })+ .collect()+ }++ /// Every label the caller can filter by, deduplicated case-insensitively+ /// and sorted.+ pub fn available_labels(&self) -> Vec<String> {+ let mut labels: Vec<String> = self.options.iter().map(|o| o.label.clone()).collect();+ labels.sort_by_key(|l| l.to_lowercase());+ labels.dedup_by(|a, b| a.eq_ignore_ascii_case(b));+ labels+ }++ /// Resolve tag filters to concrete options. Each filter matches+ /// case-insensitively within its scope (both scopes when unset); a filter+ /// matching nothing fails with the caller's available labels. Matches+ /// across all filters are unioned (OR semantics).+ pub fn resolve_filters(+ &self,+ filters: &[TagFilter],+ ) -> Result<Vec<CallerTagOption>, UnknownTagError> {+ let mut resolved: Vec<CallerTagOption> = Vec::new();+ for filter in filters {+ let matches: Vec<&CallerTagOption> = self+ .options+ .iter()+ .filter(|o| {+ o.label.eq_ignore_ascii_case(filter.label.trim())+ && filter.scope.is_none_or(|scope| o.scope == scope)+ })+ .collect();+ if matches.is_empty() {+ return Err(UnknownTagError {+ label: filter.label.clone(),+ available: self.available_labels(),+ });+ }+ for option in matches {+ if !resolved.iter().any(|r| r.option_id == option.option_id) {+ resolved.push(option.clone());+ }+ }+ }+ Ok(resolved)+ }+}diff --git a/rust/cloud-storage/models_properties/src/service/tag_sets/test.rs b/rust/cloud-storage/models_properties/src/service/tag_sets/test.rsnew file mode 100644index 0000000000..385d8ae523--- /dev/null+++ b/rust/cloud-storage/models_properties/src/service/tag_sets/test.rs@@ -0,0 +1,164 @@+use super::*;+use crate::service::property_definition::PropertyDefinition;+use crate::service::property_option::PropertyOption;+use crate::shared::DataType;+use chrono::Utc;++fn tag_set(+ definition_id: Uuid,+ owner: PropertyOwner,+ labels: &[(Uuid, &str)],+) -> PropertyDefinitionWithOptions {+ let now = Utc::now();+ PropertyDefinitionWithOptions {+ definition: PropertyDefinition {+ id: definition_id,+ owner,+ display_name: "Tags".to_string(),+ data_type: DataType::Tag,+ is_multi_select: true,+ specific_entity_type: None,+ created_at: now,+ updated_at: now,+ is_system: false,+ is_metadata: false,+ },+ property_options: labels+ .iter()+ .map(|(id, label)| PropertyOption {+ id: *id,+ property_definition_id: definition_id,+ display_order: 0,+ value: PropertyOptionValue::String(label.to_string()),+ color: None,+ created_at: now,+ updated_at: now,+ })+ .collect(),+ }+}++fn user_owner() -> PropertyOwner {+ PropertyOwner::User {+ user_id: "user1".to_string(),+ }+}++fn team_owner() -> PropertyOwner {+ PropertyOwner::Team {+ team_id: Uuid::from_u128(99),+ }+}++fn filter(label: &str, scope: Option<TagScope>) -> TagFilter {+ TagFilter {+ label: label.to_string(),+ scope,+ }+}++#[test]+fn resolves_labels_case_insensitively() {+ let option_id = Uuid::from_u128(1);+ let sets = CallerTagSets::new(vec![tag_set(+ Uuid::from_u128(10),+ user_owner(),+ &[(option_id, "Bug-Report")],+ )]);++ let resolved = sets.resolve_filters(&[filter("bug-report", None)]).unwrap();+ assert_eq!(resolved.len(), 1);+ assert_eq!(resolved[0].option_id, option_id);+ assert_eq!(resolved[0].scope, TagScope::Personal);+}++#[test]+fn scope_narrows_a_label_present_in_both_sets() {+ let personal_option = Uuid::from_u128(1);+ let team_option = Uuid::from_u128(2);+ let sets = CallerTagSets::new(vec![+ tag_set(+ Uuid::from_u128(10),+ user_owner(),+ &[(personal_option, "urgent")],+ ),+ tag_set(+ Uuid::from_u128(11),+ team_owner(),+ &[(team_option, "urgent")],+ ),+ ]);++ // Without a scope both options match (OR of the two sets).+ let resolved = sets.resolve_filters(&[filter("urgent", None)]).unwrap();+ assert_eq!(resolved.len(), 2);++ let resolved = sets+ .resolve_filters(&[filter("urgent", Some(TagScope::Team))])+ .unwrap();+ assert_eq!(resolved.len(), 1);+ assert_eq!(resolved[0].option_id, team_option);+}++#[test]+fn unknown_label_errors_with_available_labels() {+ let sets = CallerTagSets::new(vec![tag_set(+ Uuid::from_u128(10),+ user_owner(),+ &[+ (Uuid::from_u128(1), "mobile"),+ (Uuid::from_u128(2), "backend"),+ ],+ )]);++ let err = sets+ .resolve_filters(&[filter("nonexistent", None)])+ .unwrap_err();+ assert_eq!(err.label, "nonexistent");+ assert_eq!(err.available, vec!["backend", "mobile"]);+ assert!(err.to_string().contains("backend, mobile"));+}++#[test]+fn duplicate_filters_dedupe_options() {+ let option_id = Uuid::from_u128(1);+ let sets = CallerTagSets::new(vec![tag_set(+ Uuid::from_u128(10),+ user_owner(),+ &[(option_id, "mobile")],+ )]);++ let resolved = sets+ .resolve_filters(&[filter("mobile", None), filter("MOBILE", None)])+ .unwrap();+ assert_eq!(resolved.len(), 1);+}++#[test]+fn system_owned_definitions_are_skipped() {+ let sets = CallerTagSets::new(vec![tag_set(+ Uuid::from_u128(10),+ PropertyOwner::System,+ &[(Uuid::from_u128(1), "hidden")],+ )]);+ assert!(sets.is_empty());+}++#[test]+fn applied_tag_map_carries_label_and_scope() {+ let option_id = Uuid::from_u128(1);+ let sets = CallerTagSets::new(vec![tag_set(+ Uuid::from_u128(10),+ team_owner(),+ &[(option_id, "urgent")],+ )]);++ let map = sets.applied_tag_by_option_id();+ assert_eq!(+ map.get(&option_id),+ Some(&AppliedTag {+ label: "urgent".to_string(),+ scope: TagScope::Team,+ })+ );+}diff --git a/rust/cloud-storage/properties/fixtures/tags.sql b/rust/cloud-storage/properties/fixtures/tags.sqlindex fe51c190ec..82faf204f0 100644--- a/rust/cloud-storage/properties/fixtures/tags.sql+++ b/rust/cloud-storage/properties/fixtures/tags.sql@@ -7,6 +7,15 @@ VALUES('aa333333-3333-3333-3333-333333333333', NULL, 'macro|[email protected]', 'Tags', 'TAG', true, NULL)ON CONFLICT (id) DO NOTHING;+-- Tag options (labels). Ids match the option ids referenced by tagdoc1 below.+INSERT INTO property_options (id, property_definition_id, display_order, number_value, string_value, color)+VALUES+ ('0aa11111-1111-1111-1111-111111111111', 'aa111111-1111-1111-1111-111111111111', 0, NULL, 'bug-report', '#ff0000'),+ ('0aa11111-1111-1111-1111-111111111112', 'aa111111-1111-1111-1111-111111111111', 1, NULL, 'mobile', NULL),+ ('0aa22222-2222-2222-2222-222222222222', 'aa222222-2222-2222-2222-222222222222', 0, NULL, 'urgent', NULL),+ ('0aa33333-3333-3333-3333-333333333333', 'aa333333-3333-3333-3333-333333333333', 0, NULL, 'user2-private', NULL)+ON CONFLICT (id) DO NOTHING;+-- tagdoc1 carries a regular select plus one tag application per owner above.INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)VALUESdiff --git a/rust/cloud-storage/properties/src/domain/model.rs b/rust/cloud-storage/properties/src/domain/model.rsindex f20d5a9df2..11f33ed199 100644--- a/rust/cloud-storage/properties/src/domain/model.rs+++ b/rust/cloud-storage/properties/src/domain/model.rs@@ -4,7 +4,7 @@ use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;-use models_properties::{DataType, EntityReference, EntityType};+use models_properties::{DataType, EntityReference, EntityType, PropertyOwner};use uuid::Uuid;/// Key identifying the properties attached to one entity.@@ -28,6 +28,8 @@ impl From<&EntityReference> for EntityPropertiesKey {pub struct EntityPropertyInfo {/// The property definition ID (used to set values via `set_entity_property`).pub property_definition_id: Uuid,+ /// Who owns the property definition (user, team, or system).+ pub owner: PropertyOwner,/// Human-readable name of the property.pub display_name: String,/// The data type of the property.diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 6aadd0f123..06156f71e2 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -237,13 +237,22 @@ pub trait PropertiesRepo: Send + Sync + 'static {) -> impl Future<Output = Result<Option<PropertyValue>, Self::Err>> + Send;/// Get all properties attached to an entity, with definitions, values, and options.+ /// Tag properties are restricted to the viewer's own and their teams' definitions./// Returns properties sorted by display name.fn get_entity_properties(&self,entity_id: &str,entity_type: EntityType,+ tag_viewer_user_id: &str,) -> impl Future<Output = Result<Vec<EntityPropertyInfo>, Self::Err>> + Send;+ /// Get the tag definitions visible to a user — their own plus their teams' —+ /// with options attached.+ fn get_caller_tag_definitions(+ &self,+ user_id: &str,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, Self::Err>> + Send;+/// Get all properties attached to multiple entities, keyed by entity id and type./// Returns properties sorted by display name for each entity.fn get_entity_properties_batch(diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rsindex b46235e15a..32ff855ffa 100644--- a/rust/cloud-storage/properties/src/domain/service.rs+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -57,12 +57,21 @@ pub trait PropertiesService: Send + Sync + 'static {) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Get all properties attached to an entity, with definitions, values, and options.+ /// Tag properties are restricted to the viewer's own and their teams' definitions.fn get_entity_properties(&self,entity_id: &str,entity_type: EntityType,+ tag_viewer_user_id: &str,) -> impl Future<Output = Result<Vec<EntityPropertyInfo>, PropertiesErr>> + Send;+ /// Get the tag sets visible to a caller — their personal set plus their+ /// teams' sets — with options attached.+ fn list_caller_tag_sets(+ &self,+ user_id: &str,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr>> + Send;+/// Get all properties attached to multiple entities, keyed by entity id and type.fn get_entity_properties_batch(&self,diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsindex 1137c1a713..468f6aafc3 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -269,10 +269,35 @@ where&self,entity_id: &str,entity_type: EntityType,+ tag_viewer_user_id: &str,) -> Result<Vec<EntityPropertyInfo>, PropertiesErr> {+ // Check view permission first (permission service is required)+ let permission_service = self+ .permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;+ let viewer = MacroUserIdStr::parse_from_str(tag_viewer_user_id)+ .map_err(|_| PropertiesErr::PermissionDenied)?;+ permission_service+ .check_entity_view_permission(Some(&viewer), entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;++ Ok(self+ .repository+ .get_entity_properties(entity_id, entity_type, tag_viewer_user_id)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_caller_tag_sets(+ &self,+ user_id: &str,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr> {Ok(self.repository- .get_entity_properties(entity_id, entity_type)+ .get_caller_tag_definitions(user_id).await.map_err(anyhow::Error::from)?)}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rsindex e25a4e3a29..0904f260b5 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs@@ -4,8 +4,10 @@ use crate::domain::model::{EntityPropertyInfo, PropertyOptionInfo};use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use models_properties::PropertyOwner;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;+use models_properties::service::tag_sets::TagScope;use models_properties::{DataType, EntityType};use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -44,7 +46,7 @@ impl From<ToolEntityType> for EntityType {#[derive(Debug, Deserialize, JsonSchema)]#[schemars(title = "GetEntityProperties",- description = "Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties."+ description = "Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Select and tag values also come back resolved as human-readable labels in currentValueLabels. Tags are properties with dataType \"tag\"; only tags visible to the user (their own and their team's) are returned. Use ListTags to see every tag available to the user, and SetEntityProperty with the tag definition id and add_option_ids/remove_option_ids to apply or remove tags. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties.")]pub struct GetEntityProperties {#[schemars(description = "The ID of the entity to get properties for.")]@@ -74,7 +76,7 @@ pub struct ToolPropertyItem {pub property_definition_id: Uuid,/// Human-readable name of the property.pub display_name: String,- /// The data type (boolean, date, number, string, select_number, select_string, entity, link).+ /// The data type (boolean, date, number, string, select_number, select_string, tag, entity, link).pub data_type: String,/// Whether this property supports multiple values.pub is_multi_select: bool,@@ -82,6 +84,13 @@ pub struct ToolPropertyItem {pub is_system: bool,/// The current value, if set.pub current_value: Option<serde_json::Value>,+ /// The current value's option ids resolved to human-readable labels, for+ /// select and tag properties with a value set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub current_value_labels: Option<Vec<String>>,+ /// For tag properties, whether this is the user's personal set or a team set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub scope: Option<TagScope>,/// Available options for select-type properties.#[serde(skip_serializing_if = "Vec::is_empty")]pub options: Vec<ToolPropertyOption>,@@ -111,13 +120,16 @@ whererequest_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(params=?self, "Get entity properties");- let _ = &request_context;let entity_type = EntityType::from(self.entity_type);let props = service_context.service- .get_entity_properties(&self.entity_id, entity_type)+ .get_entity_properties(+ &self.entity_id,+ entity_type,+ request_context.user_id.as_ref(),+ ).await.map_err(|e| ToolCallError {description: format!("Failed to get entity properties: {e}"),@@ -162,6 +174,32 @@ fn to_tool_property(info: EntityPropertyInfo) -> ToolPropertyItem {}.to_string();+ let current_value_labels = info.value.as_ref().and_then(|v| match v {+ PropertyValue::SelectOption(option_ids) => Some(+ option_ids+ .iter()+ .filter_map(|id| {+ info.options+ .iter()+ .find(|o| o.id == *id)+ .map(|o| match &o.value {+ PropertyOptionValue::String(s) => s.clone(),+ PropertyOptionValue::Number(n) => n.to_string(),+ })+ })+ .collect(),+ ),+ _ => None,+ });++ let scope = (info.data_type == DataType::Tag)+ .then_some(match info.owner {+ PropertyOwner::User { .. } => Some(TagScope::Personal),+ PropertyOwner::Team { .. } => Some(TagScope::Team),+ PropertyOwner::System => None,+ })+ .flatten();+let current_value = info.value.map(|v| property_value_to_json(&v));let options = info.options.into_iter().map(to_tool_option).collect();@@ -173,6 +211,8 @@ fn to_tool_property(info: EntityPropertyInfo) -> ToolPropertyItem {is_multi_select: info.is_multi_select,is_system: info.is_system,current_value,+ current_value_labels,+ scope,options,}}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/list_tags.rs b/rust/cloud-storage/properties/src/inbound/toolset/list_tags.rsnew file mode 100644index 0000000000..4319da2bc6--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/toolset/list_tags.rs@@ -0,0 +1,128 @@+//! ListTags tool for reading the tags available to the caller.++use crate::domain::service::PropertiesService;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use models_properties::PropertyOwner;+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::service::tag_sets::TagScope;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::PropertiesToolContext;++/// A single tag in a tag set.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolTag {+ /// The tag's option id. Use it with SetEntityProperty to apply or remove the tag.+ pub id: Uuid,+ /// The tag's human-readable label.+ pub label: String,+ /// The tag's display color, when set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub color: Option<String>,+}++/// One tag set available to the caller.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolTagSet {+ /// Whether this is the caller's personal set or a team set.+ pub scope: TagScope,+ /// The tag property definition id. Use it as propertyDefinitionId when+ /// calling SetEntityProperty to apply or remove one of this set's tags.+ pub property_definition_id: Uuid,+ /// The tags in this set.+ pub tags: Vec<ToolTag>,+}++/// Response from [`ListTags`].+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListTagsResponse {+ /// The tag sets available to the caller.+ pub tag_sets: Vec<ToolTagSet>,+ /// Human-readable summary.+ pub summary: String,+}++/// List the tags available to the caller.+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]+#[schemars(+ title = "ListTags",+ description = "List the tags available to the user: their personal tag set plus their team's set when they belong to a team. Each tag has a human-readable label, an option id, and optionally a color. Refer to tags by label when talking to the user. To filter items by tag, pass the labels to the tags argument of ListEntities, ContentSearch, or NameSearch. To apply or remove a tag on an entity, call SetEntityProperty with the set's propertyDefinitionId and the tag's option id in add_option_ids or remove_option_ids — never rewrite the full value to add or remove one tag. Call this before tag operations when you don't already know the user's tags."+)]+#[allow(unused)]+// empty structs can't be deserialized;+pub struct ListTags {}++#[async_trait]+impl<T> AsyncTool<PropertiesToolContext<T>> for ListTags+where+ T: PropertiesService,+{+ type Output = ListTagsResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<PropertiesToolContext<T>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("List tags");++ let definitions = service_context+ .service+ .list_caller_tag_sets(request_context.user_id.as_ref())+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to list tags: {e}"),+ internal_error: e.into(),+ })?;++ let mut tag_sets: Vec<ToolTagSet> = definitions+ .into_iter()+ .filter_map(|def| {+ let scope = match def.definition.owner {+ PropertyOwner::User { .. } => TagScope::Personal,+ PropertyOwner::Team { .. } => TagScope::Team,+ PropertyOwner::System => return None,+ };+ let tags = def+ .property_options+ .into_iter()+ .map(|option| ToolTag {+ id: option.id,+ label: match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ },+ color: option.color,+ })+ .collect();+ Some(ToolTagSet {+ scope,+ property_definition_id: def.definition.id,+ tags,+ })+ })+ .collect();+ tag_sets.sort_by_key(|set| set.scope != TagScope::Personal);++ let tag_count: usize = tag_sets.iter().map(|set| set.tags.len()).sum();+ let summary = if tag_count == 0 {+ "The user has no tags yet.".to_string()+ } else {+ format!(+ "Found {tag_count} tag{} across {} set{}.",+ if tag_count == 1 { "" } else { "s" },+ tag_sets.len(),+ if tag_sets.len() == 1 { "" } else { "s" },+ )+ };++ Ok(ListTagsResponse { tag_sets, summary })+ }+}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/mod.rs b/rust/cloud-storage/properties/src/inbound/toolset/mod.rsindex 2e6f7a6395..b710246a07 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/mod.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/mod.rs@@ -1,6 +1,7 @@//! Toolset inbound adapter for the Properties service.mod get_entity_properties;+mod list_tags;mod set_entity_property;#[cfg(test)]@@ -11,6 +12,7 @@ use ai_toolset::AsyncToolCollection;use std::sync::Arc;pub use get_entity_properties::{GetEntityProperties, GetEntityPropertiesResponse};+pub use list_tags::{ListTags, ListTagsResponse};pub use set_entity_property::{SetEntityProperty, SetEntityPropertyResponse};/// Service context for properties AI tools.@@ -44,4 +46,5 @@ whereAsyncToolCollection::new().add_tool::<GetEntityProperties, PropertiesToolContext<T>>().add_tool::<SetEntityProperty, PropertiesToolContext<T>>()+ .add_tool::<ListTags, PropertiesToolContext<T>>()}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rsindex 4c28f9100f..c37fd081ea 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs@@ -38,6 +38,8 @@ pub struct ToolEntityRef {title = "SetEntityProperty",description = "Set or update a property value on an entity (document, task, project, etc.). Provide the property_definition_id and exactly one value field matching the property's data type.+For multi-select properties — including tags — prefer add_option_ids / remove_option_ids over option_ids: they add or remove just those options atomically, composing with concurrent edits. option_ids replaces the entire value, so a stale read can silently drop options someone else just added; only use it when the user asks to set the value to exactly a given list. To apply a tag, pass the tag set's property_definition_id and the tag's option id (both from ListTags) in add_option_ids; to remove a tag, use remove_option_ids.+Tasks always have these system properties (use these property_definition_id values directly):- Assignees (00000001-0000-0000-0000-000000000001): entity type, multi-select. Use entity_refs with entity_type='user' and entity_id='macro|[email protected]'.- Status (00000001-0000-0000-0000-000000000002): select_string, single. Options: Not Started (00000001-0000-0000-0002-000000000001), In Progress (...0002), In Review (...0003), Completed (...0004), Canceled (...0005).@@ -91,11 +93,23 @@ pub struct SetEntityProperty {pub option_id: Option<Uuid>,#[schemars(- description = "For multi-select properties. The option UUIDs from available options."+ description = "For multi-select properties. Replaces the entire value with these option UUIDs — prefer add_option_ids / remove_option_ids for adding or removing specific options.")]#[serde(default)]pub option_ids: Option<Vec<Uuid>>,+ #[schemars(+ description = "For multi-select properties (including tags): add these options to the current value atomically without touching other options. Cannot be combined with other value fields."+ )]+ #[serde(default)]+ pub add_option_ids: Option<Vec<Uuid>>,++ #[schemars(+ description = "For multi-select properties (including tags): remove these options from the current value atomically without touching other options. Removing an absent option is a no-op. Cannot be combined with other value fields."+ )]+ #[serde(default)]+ pub remove_option_ids: Option<Vec<Uuid>>,+#[schemars(description = "For single entity reference properties.")]#[serde(default)]pub entity_ref: Option<ToolEntityRef>,@@ -200,6 +214,59 @@ wherelet entity_type = EntityType::from(self.entity_type);let set_value = self.to_set_property_value();+ // Delta mode: add/remove specific options atomically so concurrent+ // edits to the same multi-select value are never overwritten.+ let add_option_ids = self.add_option_ids.as_deref().unwrap_or_default();+ let remove_option_ids = self.remove_option_ids.as_deref().unwrap_or_default();+ if !add_option_ids.is_empty() || !remove_option_ids.is_empty() {+ if set_value.is_some() {+ return Err(ToolCallError {+ description: "add_option_ids/remove_option_ids cannot be combined with other value fields".to_string(),+ internal_error: anyhow::anyhow!(+ "delta option fields combined with a value field"+ ),+ });+ }++ for option_id in add_option_ids {+ service_context+ .service+ .add_entity_property_option(+ &request_context.user_id,+ &self.entity_id,+ entity_type,+ self.property_definition_id,+ *option_id,+ )+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to add option {option_id}: {e}"),+ internal_error: e.into(),+ })?;+ }+ for option_id in remove_option_ids {+ service_context+ .service+ .remove_entity_property_option(+ &request_context.user_id,+ &self.entity_id,+ entity_type,+ self.property_definition_id,+ *option_id,+ )+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to remove option {option_id}: {e}"),+ internal_error: e.into(),+ })?;+ }++ return Ok(SetEntityPropertyResponse {+ success: true,+ message: "Property options updated successfully.".to_string(),+ });+ }+service_context.service.set_entity_property(diff --git a/rust/cloud-storage/properties/src/inbound/toolset/test.rs b/rust/cloud-storage/properties/src/inbound/toolset/test.rsindex 8da8cc033b..e1c8f5829c 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/test.rs@@ -28,6 +28,41 @@ fn test_set_entity_property_schema_validation() {);}+#[test]+fn test_set_entity_property_schema_documents_delta_options() {+ let validated = generate_validated_input_schema::<SetEntityProperty>().unwrap();+ let schema_json = serde_json::to_string(&validated.schema).unwrap();+ assert!(+ schema_json.contains("add_option_ids"),+ "schema should expose add_option_ids"+ );+ assert!(+ schema_json.contains("remove_option_ids"),+ "schema should expose remove_option_ids"+ );+ assert!(+ validated.description.contains("atomically"),+ "description should steer to atomic add/remove over full replace"+ );+}++#[test]+fn test_list_tags_schema_validation() {+ let result = generate_validated_input_schema::<ListTags>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(validated.name, "ListTags");+ assert!(+ validated.description.contains("personal tag set"),+ "Description should explain the personal/team tag sets"+ );+ assert!(+ validated.description.contains("SetEntityProperty"),+ "Description should point at SetEntityProperty for applying tags"+ );+}+// run `cargo test -p properties inbound::toolset::test::print_get_input_schema -- --nocapture --include-ignored`#[test]#[ignore = "prints the input schema"]diff --git a/rust/cloud-storage/properties/src/outbound/definitions_test.rs b/rust/cloud-storage/properties/src/outbound/definitions_test.rsindex b636d68588..1fd85b0476 100644--- a/rust/cloud-storage/properties/src/outbound/definitions_test.rs+++ b/rust/cloud-storage/properties/src/outbound/definitions_test.rs@@ -1,6 +1,7 @@//! Integration tests for property definition operations on PropertiesPgRepo.use super::properties_pg_repo::PropertiesPgRepo;+use super::property_definition_queries;use crate::domain::model::PropertyDefinitionOwner;use crate::domain::ports::PropertiesRepo;use macro_db_migrator::MACRO_DB_MIGRATIONS;@@ -437,3 +438,54 @@ async fn delete_nonexistent_property_definition_is_noop(Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties", "tags"))+)]+async fn get_caller_tag_definitions_with_options(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let user1_tags: Uuid = "aa111111-1111-1111-1111-111111111111".parse()?;+ let team1_tags: Uuid = "aa222222-2222-2222-2222-222222222222".parse()?;+ let user2_tags: Uuid = "aa333333-3333-3333-3333-333333333333".parse()?;++ // user1 gets their personal set (first) and their team's set, with+ // options, never another user's personal set.+ let sets = property_definition_queries::get_caller_tag_definitions_with_options(+ &pool,+ "macro|[email protected]",+ )+ .await?;+ assert_eq!(sets.len(), 2);+ assert_eq!(sets[0].definition.id, user1_tags);+ assert_eq!(sets[0].property_options.len(), 2);+ assert_eq!(+ sets[0].property_options[0].value,+ PropertyOptionValue::String("bug-report".to_string())+ );+ assert_eq!(+ sets[0].property_options[0].color,+ Some("#ff0000".to_string())+ );+ assert_eq!(sets[1].definition.id, team1_tags);+ assert_eq!(sets[1].property_options.len(), 1);++ // A teammate without a personal set only gets the team set.+ let sets = property_definition_queries::get_caller_tag_definitions_with_options(+ &pool,+ "macro|[email protected]",+ )+ .await?;+ assert_eq!(sets.len(), 1);+ assert_eq!(sets[0].definition.id, team1_tags);++ // user2 only gets their own personal set (Team 2 has no tag set).+ let sets = property_definition_queries::get_caller_tag_definitions_with_options(+ &pool,+ "macro|[email protected]",+ )+ .await?;+ assert_eq!(sets.len(), 1);+ assert_eq!(sets[0].definition.id, user2_tags);++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs b/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rsindex 477b2ed417..a2bbcfea66 100644--- a/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs+++ b/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs@@ -17,6 +17,8 @@ use crate::domain::model::{EntityPropertyInfo, PropertyOptionInfo};/// Database row from the joined query.struct PropertyRow {property_definition_id: Uuid,+ team_id: Option<Uuid>,+ user_id: Option<String>,display_name: String,data_type: DataType,is_multi_select: bool,@@ -34,12 +36,14 @@ struct OptionRow {}/// Get all properties attached to an entity, with their definitions, values, and options.-/// Results are sorted by display_name (case-insensitive).+/// Tag properties are restricted to definitions the viewer can see: their own+/// and their teams'. Results are sorted by display_name (case-insensitive).#[tracing::instrument(skip(pool))]pub async fn get_entity_properties(pool: &Pool<Postgres>,entity_id: &str,entity_type: EntityType,+ tag_viewer_user_id: &str,) -> anyhow::Result<Vec<EntityPropertyInfo>> {// Fetch all entity properties with their definitionslet rows = sqlx::query_as!(@@ -47,6 +51,8 @@ pub async fn get_entity_properties(r#"SELECTep.property_definition_id,+ pd.team_id,+ pd.user_id,pd.display_name,pd.data_type as "data_type: DataType",pd.is_multi_select,@@ -56,10 +62,17 @@ pub async fn get_entity_properties(INNER JOIN property_definitions pd ON pd.id = ep.property_definition_idWHERE ep.entity_id = $1AND ep.entity_type = $2+ AND (+ pd.data_type <> $4+ OR pd.user_id = $3+ OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $3)+ )ORDER BY LOWER(pd.display_name)"#,entity_id,entity_type as EntityType,+ tag_viewer_user_id,+ DataType::Tag as DataType,).fetch_all(pool).await?;@@ -139,6 +152,11 @@ pub async fn get_entity_properties(result.push(EntityPropertyInfo {property_definition_id: row.property_definition_id,+ owner: models_properties::PropertyOwner::from_optional_ids(+ row.team_id,+ row.user_id,+ row.is_system,+ ),display_name: row.display_name,data_type: row.data_type,is_multi_select: row.is_multi_select,diff --git a/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rs b/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rsindex b3fe963eca..763b7fd07e 100644--- a/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rs+++ b/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rs@@ -414,6 +414,48 @@ async fn get_bulk_filtered_includes_caller_visible_tags(Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties", "tags"))+)]+async fn get_entity_properties_scopes_tags_to_viewer(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let user1_tags = Uuid::parse_str("aa111111-1111-1111-1111-111111111111")?;+ let team1_tags = Uuid::parse_str("aa222222-2222-2222-2222-222222222222")?;+ let user2_tags = Uuid::parse_str("aa333333-3333-3333-3333-333333333333")?;++ // user1 sees non-tag properties plus their own and their team's tags,+ // never user2's personal tags.+ let props = entity_properties_get_query::get_entity_properties(+ &pool,+ "tagdoc1",+ EntityType::Document,+ "macro|[email protected]",+ )+ .await?;+ let ids: Vec<Uuid> = props.iter().map(|p| p.property_definition_id).collect();+ assert_eq!(ids.len(), 3);+ assert!(ids.contains(&priority));+ assert!(ids.contains(&user1_tags));+ assert!(ids.contains(&team1_tags));+ assert!(!ids.contains(&user2_tags));++ // user2 sees non-tag properties plus only their own tags.+ let props = entity_properties_get_query::get_entity_properties(+ &pool,+ "tagdoc1",+ EntityType::Document,+ "macro|[email protected]",+ )+ .await?;+ let ids: Vec<Uuid> = props.iter().map(|p| p.property_definition_id).collect();+ assert_eq!(ids.len(), 2);+ assert!(ids.contains(&priority));+ assert!(ids.contains(&user2_tags));++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("properties"))diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsindex d642982024..20d0f452fa 100644--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -336,8 +336,24 @@ impl PropertiesRepo for PropertiesPgRepo {&self,entity_id: &str,entity_type: EntityType,+ tag_viewer_user_id: &str,) -> Result<Vec<EntityPropertyInfo>, Self::Err> {- entity_properties_get_query::get_entity_properties(&self.pool, entity_id, entity_type).await+ entity_properties_get_query::get_entity_properties(+ &self.pool,+ entity_id,+ entity_type,+ tag_viewer_user_id,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_caller_tag_definitions(+ &self,+ user_id: &str,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, Self::Err> {+ property_definition_queries::get_caller_tag_definitions_with_options(&self.pool, user_id)+ .await}#[tracing::instrument(skip(self), err)]diff --git a/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rsindex f33affb42d..081ebb627a 100644--- a/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs+++ b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs@@ -507,6 +507,122 @@ pub async fn get_or_create_tag_definition(}}+/// Gets the tag definitions visible to a user — their own plus their teams' —+/// with options attached. Team membership is resolved in the query.+#[tracing::instrument(skip(pool))]+pub async fn get_caller_tag_definitions_with_options(+ pool: &Pool<Postgres>,+ user_id: &str,+) -> anyhow::Result<Vec<PropertyDefinitionWithOptions>> {+ let rows = sqlx::query!(+ r#"+ SELECT+ pd.id,+ pd.team_id,+ pd.user_id,+ pd.display_name,+ pd.data_type as "data_type: DataType",+ pd.is_multi_select,+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",+ pd.created_at,+ pd.updated_at,+ pd.is_system,+ po.id as "option_id?",+ po.display_order as "option_display_order?",+ po.number_value as option_number_value,+ po.string_value as option_string_value,+ po.color as option_color,+ po.created_at as "option_created_at?",+ po.updated_at as "option_updated_at?"+ FROM property_definitions pd+ LEFT JOIN property_options po ON pd.id = po.property_definition_id+ WHERE+ pd.data_type = $2+ AND (+ pd.user_id = $1+ OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $1)+ )+ ORDER BY pd.user_id NULLS LAST, po.display_order, LOWER(po.string_value)+ "#,+ user_id,+ DataType::Tag as DataType+ )+ .fetch_all(pool)+ .await?;++ let mut ordered_ids: Vec<Uuid> = Vec::new();+ let mut property_map: HashMap<Uuid, PropertyDefinitionWithOptions> = HashMap::new();++ for row in rows {+ let owner = models_properties::PropertyOwner::from_optional_ids(+ row.team_id,+ row.user_id.clone(),+ row.is_system,+ );++ let property_def = PropertyDefinition {+ id: row.id,+ owner,+ display_name: row.display_name.clone(),+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: row.is_system,+ is_metadata: false,+ };++ if !property_map.contains_key(&row.id) {+ ordered_ids.push(row.id);+ }+ let entry = property_map+ .entry(row.id)+ .or_insert_with(|| PropertyDefinitionWithOptions {+ definition: property_def,+ property_options: Vec::new(),+ });++ if let Some(option_id) = row.option_id {+ let value = match (row.option_number_value, &row.option_string_value) {+ (Some(num), None) => PropertyOptionValue::Number(num),+ (None, Some(str)) => PropertyOptionValue::String(str.clone()),+ (Some(_), Some(_)) => {+ return Err(+ models_properties::db::DbConversionError::PropertyOptionBothValuesSet {+ id: option_id,+ }+ .into(),+ );+ }+ (None, None) => {+ return Err(+ models_properties::db::DbConversionError::PropertyOptionNoValueSet {+ id: option_id,+ }+ .into(),+ );+ }+ };++ entry.property_options.push(PropertyOption {+ id: option_id,+ property_definition_id: row.id,+ display_order: row.option_display_order.unwrap_or(0),+ value,+ color: row.option_color,+ created_at: row.option_created_at.unwrap_or(row.created_at),+ updated_at: row.option_updated_at.unwrap_or(row.updated_at),+ });+ }+ }++ Ok(ordered_ids+ .into_iter()+ .filter_map(|id| property_map.remove(&id))+ .collect())+}+/// Deletes a property definition and all associated data (cascades).#[tracing::instrument(skip(pool))]pub async fn delete_property_definition(diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rsindex 883137548c..81f515ccce 100644--- a/rust/cloud-storage/soup/src/domain/ports.rs+++ b/rust/cloud-storage/soup/src/domain/ports.rs@@ -6,6 +6,7 @@ use either::Either;use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{Frecency, PaginatedCursor, SimpleSortMethod};+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_soup::item::SoupItem;use serde::Serialize;@@ -46,6 +47,13 @@ pub trait SoupRepo: Send + Sync + 'static {items: &'a mut [SoupItem],) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Fetches the tag definitions visible to a user — their own plus their+ /// teams' — with options attached.+ fn caller_tag_sets<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, Self::Err>> + Send;+/// Fetches expanded soup items with group metadata.fn expanded_grouped_cursor_soup<'a>(&self,@@ -86,4 +94,11 @@ pub trait SoupService: Send + Sync + 'static {&self,req: GroupedSortRequest<'_>,) -> impl Future<Output = Result<Vec<GroupedSoupItem>, SoupErr>> + Send;++ /// Fetch the tag definitions visible to a user — their own plus their+ /// teams' — with options attached.+ fn caller_tag_sets<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, SoupErr>> + Send;}diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 2eb260fa06..d0e3c3190f 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -33,6 +33,7 @@ use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,};+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_soup::{call_record::SoupCallRecord,comms::{SoupChannel, SoupChannelThread},@@ -647,4 +648,16 @@ where) -> Result<Vec<GroupedSoupItem>, SoupErr> {self.handle_grouped_soup_request(req).await}++ #[tracing::instrument(err, skip(self))]+ async fn caller_tag_sets<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, SoupErr> {+ Ok(self+ .soup_storage+ .caller_tag_sets(user_id)+ .await+ .map_err(anyhow::Error::from)?)+ }}diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex f743febfbe..8624f84bd0 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -116,6 +116,16 @@ impl SoupService for MockSoup {) -> Result<Vec<GroupedSoupItem>, SoupErr> {Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))}++ async fn caller_tag_sets<'a>(+ &self,+ _user_id: MacroUserIdStr<'a>,+ ) -> Result<+ Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,+ SoupErr,+ >{+ Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))+ }}struct MockEmail;diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex 2f35b61b74..08c855fdf0 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -20,16 +20,20 @@ use item_filters::{email::EmailLiteral,foreign_entity::ForeignEntityLiteral,project::ProjectLiteral,- properties::PropertiesLiteral,+ properties::{PropertiesLiteral, PropertyMatchValue},},};use models_pagination::{SimpleSortMethod, TypeEraseCursor};-use models_soup::item::SoupItem;+use models_properties::DataType;+use models_properties::service::property_value::PropertyValue;+use models_properties::service::tag_sets::{AppliedTag, CallerTagSets, TagFilter};+use models_soup::{SoupProperty, item::SoupItem};use schemars::JsonSchema;use serde::{Deserialize, Serialize};use uuid::Uuid;use cowlike::CowLike;+use std::collections::HashMap;use std::sync::Arc;use super::SoupToolContext;@@ -111,6 +115,9 @@ pub enum EntityItem {id: Uuid,/// Document name.name: String,+ /// Tags on the document visible to the user.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ tags: Vec<AppliedTag>,},/// AI chat item.#[serde(rename_all = "camelCase")]@@ -119,6 +126,9 @@ pub enum EntityItem {id: Uuid,/// Chat name.name: String,+ /// Tags on the chat visible to the user.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ tags: Vec<AppliedTag>,},/// Project item.#[serde(rename_all = "camelCase")]@@ -127,6 +137,9 @@ pub enum EntityItem {id: Uuid,/// Project name.name: String,+ /// Tags on the project visible to the user.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ tags: Vec<AppliedTag>,},/// Email thread item.#[serde(rename_all = "camelCase")]@@ -135,6 +148,9 @@ pub enum EntityItem {id: Uuid,/// Email subject, when present.subject: Option<String>,+ /// Tags on the thread visible to the user.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ tags: Vec<AppliedTag>,},/// Channel item.#[serde(rename_all = "camelCase")]@@ -174,24 +190,28 @@ pub enum EntityItem {},}-impl From<SoupItem> for EntityItem {- fn from(item: SoupItem) -> Self {+impl EntityItem {+ pub(super) fn from_soup_item(item: SoupItem, tag_map: &HashMap<Uuid, AppliedTag>) -> Self {match item {SoupItem::Document(doc) => EntityItem::Document {id: doc.id,name: doc.name,+ tags: resolve_applied_tags(&doc.properties, tag_map),},SoupItem::Chat(chat) => EntityItem::AiChat {id: chat.id,name: chat.name,+ tags: resolve_applied_tags(&chat.properties, tag_map),},SoupItem::Project(project) => EntityItem::Project {id: project.id,name: project.name,+ tags: resolve_applied_tags(&project.properties, tag_map),},SoupItem::EmailThread(thread) => EntityItem::Email {id: thread.thread.id,subject: thread.thread.name,+ tags: resolve_applied_tags(&thread.properties, tag_map),},SoupItem::Channel(channel) => EntityItem::Channel {id: channel.channel.channel.id.0,@@ -220,6 +240,51 @@ impl From<SoupItem> for EntityItem {}}+/// Resolve an item's tag properties to labels via the caller's tag sets.+/// Option ids outside the caller's sets are dropped.+fn resolve_applied_tags(+ properties: &[SoupProperty],+ tag_map: &HashMap<Uuid, AppliedTag>,+) -> Vec<AppliedTag> {+ let mut tags: Vec<AppliedTag> = Vec::new();+ for property in properties {+ if property.definition.data_type != DataType::Tag {+ continue;+ }+ let Some(PropertyValue::SelectOption(option_ids)) = &property.value else {+ continue;+ };+ for option_id in option_ids {+ if let Some(tag) = tag_map.get(option_id)+ && !tags.contains(tag)+ {+ tags.push(tag.clone());+ }+ }+ }+ tags+}++/// True when any item carries a tag property that would need label resolution.+fn any_item_has_tags(items: &[FrecencySoupItem]) -> bool {+ items.iter().any(|FrecencySoupItem { item, .. }| {+ let properties = match item {+ SoupItem::Document(doc) => &doc.properties,+ SoupItem::Chat(chat) => &chat.properties,+ SoupItem::Project(project) => &project.properties,+ SoupItem::EmailThread(thread) => &thread.properties,+ SoupItem::CrmCompany(company) => &company.properties,+ SoupItem::Channel(_)+ | SoupItem::ChannelThread(_)+ | SoupItem::Call(_)+ | SoupItem::ForeignEntity(_) => return false,+ };+ properties+ .iter()+ .any(|p| p.definition.data_type == DataType::Tag)+ })+}+/// Response returned by the list entities AI tool.#[derive(Debug, Serialize, JsonSchema)]#[serde(rename_all = "camelCase")]@@ -235,7 +300,7 @@ pub struct ListEntitiesResponse {#[serde(rename_all = "camelCase")]#[schemars(title = "ListEntities",- description = "Browse the user's Macro workspace to see recent items they have access to. Returns Macro documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. Start here for activity-summary questions such as \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; apply precise time, type, channel, or mailbox filters when the user gives that scope. For Macro task requests such as \"list my tasks\", \"tasks assigned to me\", or \"tasks I completed yesterday\", prefer this tool over external task trackers such as Linear unless the user explicitly asks for Linear. Macro tasks are document items with df subtype {\"l\":{\"dst\":\"task\"}} and includeTypes [\"document\"]. Filter task Status and Assignees through propf using entity_type TASK: Status property 00000001-0000-0000-0000-000000000002, Completed option 00000001-0000-0000-0002-000000000004, Assignees property 00000001-0000-0000-0000-000000000001. The current user's assignee entity id is their Macro user id, usually macro|<their email address from context>. For \"completed yesterday\", combine status Completed, assigned-to-me, and a df updatedAt yesterday window with ua gte/lt ISO timestamps. For finding specific items by name or content, use the search tool instead."+ description = "Browse the user's Macro workspace to see recent items they have access to. Returns Macro documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. Start here for activity-summary questions such as \"what happened today\", \"what's going on\", \"catch me up\", or \"what happened in standup today\"; apply precise time, type, channel, or mailbox filters when the user gives that scope. For Macro task requests such as \"list my tasks\", \"tasks assigned to me\", or \"tasks I completed yesterday\", prefer this tool over external task trackers such as Linear unless the user explicitly asks for Linear. Macro tasks are document items with df subtype {\"l\":{\"dst\":\"task\"}} and includeTypes [\"document\"]. Filter task Status and Assignees through propf using entity_type TASK: Status property 00000001-0000-0000-0000-000000000002, Completed option 00000001-0000-0000-0002-000000000004, Assignees property 00000001-0000-0000-0000-000000000001. The current user's assignee entity id is their Macro user id, usually macro|<their email address from context>. For \"completed yesterday\", combine status Completed, assigned-to-me, and a df updatedAt yesterday window with ua gte/lt ISO timestamps. Returned documents, AI chats, projects, and emails include the tags visible to the user as {label, scope} pairs. To filter by tag (e.g. \"my items tagged bug-report\"), pass the tag labels in the tags argument — ListTags shows which tags exist. For finding specific items by name or content, use the search tool instead.")]pub struct ListEntities {/// Filter returned items to specific item types.@@ -352,6 +417,17 @@ inbox\"); call ListInboxes first to get the exact address. Only affects email re#[serde(default)]pub inbox: Option<String>,+ /// Filter results to items carrying at least one of these tags.+ #[schemars(description = "\+Filter results to items carrying at least one of the given tags (OR semantics). Each entry \+names a tag by its label, matched case-insensitively against the user's own tags; only set \+scope (\"personal\" or \"team\") when the user distinguishes between their personal and team \+tags. An unknown label fails with the list of available tags — call ListTags first when \+unsure what tags exist. Only taggable items (documents, tasks, projects, emails, AI chats) \+can match a tag filter. Prefer this over hand-building a propf filter for tags.")]+ #[serde(default)]+ pub tags: Option<Vec<TagFilter>>,+/// Maximum number of items to return.#[schemars(description = "Maximum number of items to return. Defaults to 50; max 500.")]#[serde(default)]@@ -359,7 +435,17 @@ inbox\"); call ListInboxes first to get the exact address. Only affects email re}impl ListEntities {- pub(super) fn entity_filter_ast(&self) -> EntityFilterAst {+ pub(super) fn entity_filter_ast(+ &self,+ tag_filter: Option<Expr<PropertiesLiteral>>,+ ) -> EntityFilterAst {+ // A resolved tag filter ANDs with any explicit propf tree.+ let properties_filter = match (self.properties_filter.clone(), tag_filter) {+ (Some(existing), Some(tags)) => Some(Arc::new(Expr::and((*existing).clone(), tags))),+ (None, Some(tags)) => Some(Arc::new(tags)),+ (existing, None) => existing,+ };+let ast = EntityFilterAst {document_filter: self.document_filter.clone(),project_filter: self.project_filter.clone(),@@ -380,12 +466,16 @@ impl ListEntities {// AI never sees one.crm_company_filter: Some(Arc::new(Expr::val(CrmCompanyLiteral::Id(Uuid::nil())))),foreign_entity_filter: self.foreign_entity_filter.clone(),- properties_filter: self.properties_filter.clone(),+ properties_filter,};self.apply_include_types_to_ast(ast)}+ fn tag_filters(&self) -> &[TagFilter] {+ self.tags.as_deref().unwrap_or_default()+ }+fn apply_include_types_to_ast(&self, ast: EntityFilterAst) -> EntityFilterAst {let Some(include_types) = self.effective_include_types()@@ -483,7 +573,35 @@ wheretracing::info!(params=?self, "List entities");let sort_method = SimpleSortMethod::from(self.sort_by);- let filters = self.entity_filter_ast();++ // Resolve tag filters against the caller's tag sets before querying,+ // so an unknown label fails loudly with the available tags.+ let mut tag_sets: Option<CallerTagSets> = None;+ let tag_filter_expr = if self.tag_filters().is_empty() {+ None+ } else {+ let sets = fetch_caller_tag_sets(&service_context, &request_context).await?;+ let resolved = sets+ .resolve_filters(self.tag_filters())+ .map_err(|e| ToolCallError {+ description: e.to_string(),+ internal_error: anyhow::anyhow!(e),+ })?;+ let expr = resolved+ .into_iter()+ .map(|option| {+ Expr::val(PropertiesLiteral {+ property_definition_id: option.definition_id,+ entity_type: None,+ value: PropertyMatchValue::SelectOption(option.option_id),+ })+ })+ .reduce(Expr::or);+ tag_sets = Some(sets);+ expr+ };++ let filters = self.entity_filter_ast(tag_filter_expr);let email_preview_view = self.email_view()?;let limit = self.limit@@ -527,7 +645,7 @@ wheresoup_type: SoupType::Expanded,limit,cursor: SoupQuery::new_sort_simple(sort_method, filters),- user: request_context.user_id,+ user: request_context.user_id.clone(),email_preview_view,link_ids,},@@ -542,10 +660,19 @@ wherelet paginated = result.type_erase();let has_more = paginated.next_cursor.is_some();+ // Fetch tag sets lazily: only when a returned item actually carries a+ // tag property and the filter path didn't already fetch them.+ if tag_sets.is_none() && any_item_has_tags(&paginated.items) {+ tag_sets = Some(fetch_caller_tag_sets(&service_context, &request_context).await?);+ }+ let tag_map = tag_sets+ .map(|sets| sets.applied_tag_by_option_id())+ .unwrap_or_default();+let items: Vec<EntityItem> = paginated.items.into_iter()- .map(|FrecencySoupItem { item, .. }| EntityItem::from(item))+ .map(|FrecencySoupItem { item, .. }| EntityItem::from_soup_item(item, &tag_map)).collect();// Build summary@@ -555,6 +682,25 @@ where}}+async fn fetch_caller_tag_sets<T, E>(+ service_context: &ServiceContext<SoupToolContext<T, E>>,+ request_context: &RequestContext,+) -> ToolResult<CallerTagSets>+where+ T: SoupService,+ E: EmailService,+{+ let definitions = service_context+ .service+ .caller_tag_sets(request_context.user_id.copied())+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to resolve the user's tags: {e}"),+ internal_error: e.into(),+ })?;+ Ok(CallerTagSets::new(definitions))+}+pub(super) fn build_summary(items: &[EntityItem],has_more: bool,diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rsindex 2204c54548..60046a1144 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs@@ -81,7 +81,7 @@ fn test_macro_task_completed_assigned_to_me_filter_deserializes() {});let list: ListEntities = serde_json::from_value(input).unwrap();- let ast = list.entity_filter_ast();+ let ast = list.entity_filter_ast(None);assert_eq!(list.effective_include_types(),@@ -117,7 +117,7 @@ fn test_full_ast_input_deserializes() {});let list: ListEntities = serde_json::from_value(input).unwrap();- let ast = list.entity_filter_ast();+ let ast = list.entity_filter_ast(None);assert_eq!(list.limit, Some(100));assert!(matches!(list.sort_by, SortBy::RecentlyUpdated));@@ -136,7 +136,7 @@ fn test_email_preset_defaults_to_email_results() {})).unwrap();- let ast = list.entity_filter_ast();+ let ast = list.entity_filter_ast(None);assert!(ast.email_filter.tree.is_some());assert!(ast.document_filter.is_some());assert!(ast.project_filter.is_some());@@ -154,7 +154,7 @@ fn test_include_types_document_without_filter_keeps_document_unfiltered() {})).unwrap();- let ast = list.entity_filter_ast();+ let ast = list.entity_filter_ast(None);assert!(ast.document_filter.is_none());assert!(ast.foreign_entity_filter.is_some());assert_eq!(@@ -170,7 +170,7 @@ fn test_include_types_foreign_entity_without_filter_keeps_foreign_entity_unfilte})).unwrap();- let ast = list.entity_filter_ast();+ let ast = list.entity_filter_ast(None);assert!(ast.document_filter.is_some());assert!(ast.project_filter.is_some());assert!(ast.chat_filter.is_some());@@ -199,14 +199,17 @@ fn test_build_summary_with_items() {EntityItem::Document {id: Uuid::new_v4(),name: "test.md".to_string(),+ tags: vec![],},EntityItem::Document {id: Uuid::new_v4(),name: "other.md".to_string(),+ tags: vec![],},EntityItem::Email {id: Uuid::new_v4(),subject: Some("Hello".to_string()),+ tags: vec![],},EntityItem::ForeignEntity {id: Uuid::new_v4(),@@ -241,7 +244,7 @@ fn test_converts_foreign_entity_soup_item() {updated_at: Utc::now(),});- let entity_item = EntityItem::from(item);+ let entity_item = EntityItem::from_soup_item(item, &Default::default());match entity_item {EntityItem::ForeignEntity {@@ -259,6 +262,156 @@ fn test_converts_foreign_entity_soup_item() {}}+#[test]+fn test_tags_arg_deserializes_and_documents_or_semantics() {+ let validated = generate_validated_input_schema::<ListEntities>().unwrap();+ let schema_json = serde_json::to_string(&validated.schema).unwrap();+ assert!(+ schema_json.contains("OR semantics"),+ "tags arg should document OR semantics"+ );+ assert!(+ schema_json.contains("ListTags"),+ "tags arg should point at ListTags"+ );++ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "tags": [+ { "label": "bug-report" },+ { "label": "urgent", "scope": "team" }+ ]+ }))+ .unwrap();+ let tags = list.tags.unwrap();+ assert_eq!(tags.len(), 2);+ assert_eq!(tags[0].label, "bug-report");+ assert!(tags[0].scope.is_none());+ assert_eq!(+ tags[1].scope,+ Some(models_properties::service::tag_sets::TagScope::Team)+ );+}++#[test]+fn test_tag_filter_expr_ands_with_existing_propf() {+ use filter_ast::Expr;+ use item_filters::ast::properties::{PropertiesLiteral, PropertyMatchValue};++ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "propf": {+ "l": {+ "pd": "00000001-0000-0000-0000-000000000002",+ "et": "TASK",+ "v": { "so": "00000001-0000-0000-0002-000000000004" }+ }+ }+ }))+ .unwrap();++ let tag_expr = Expr::val(PropertiesLiteral {+ property_definition_id: Uuid::new_v4(),+ entity_type: None,+ value: PropertyMatchValue::SelectOption(Uuid::new_v4()),+ });++ let ast = list.entity_filter_ast(Some(tag_expr));+ let tree = serde_json::to_value(ast.properties_filter.unwrap().as_ref()).unwrap();+ let and = tree.get("&").expect("tag filter should AND with propf");+ assert_eq!(and.as_array().unwrap().len(), 2);++ // Without a propf, the tag expr becomes the whole tree.+ let list = ListEntities::default();+ let tag_expr = Expr::val(PropertiesLiteral {+ property_definition_id: Uuid::new_v4(),+ entity_type: None,+ value: PropertyMatchValue::SelectOption(Uuid::new_v4()),+ });+ let ast = list.entity_filter_ast(Some(tag_expr));+ let tree = serde_json::to_value(ast.properties_filter.unwrap().as_ref()).unwrap();+ assert!(tree.get("l").is_some());+}++#[test]+fn test_from_soup_item_resolves_tags_via_caller_map() {+ use macro_user_id::user_id::MacroUserIdStr;+ use models_properties::service::property_definition::PropertyDefinition;+ use models_properties::service::property_value::PropertyValue;+ use models_properties::service::tag_sets::{AppliedTag, TagScope};+ use models_properties::{DataType, PropertyOwner};+ use models_soup::SoupProperty;+ use models_soup::document::SoupDocument;+ use std::collections::HashMap;++ let known_option = Uuid::new_v4();+ let unknown_option = Uuid::new_v4();+ let definition_id = Uuid::new_v4();++ let now = Utc::now();+ let tag_property = SoupProperty {+ definition: PropertyDefinition {+ id: definition_id,+ owner: PropertyOwner::User {+ user_id: "user1".to_string(),+ },+ display_name: "Tags".to_string(),+ data_type: DataType::Tag,+ is_multi_select: true,+ specific_entity_type: None,+ created_at: now,+ updated_at: now,+ is_system: false,+ is_metadata: false,+ },+ value: Some(PropertyValue::SelectOption(vec![+ known_option,+ unknown_option,+ ])),+ };++ let doc = SoupDocument {+ id: Uuid::new_v4(),+ document_version_id: 1,+ owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),+ name: "tagged.md".to_string(),+ file_type: None,+ sha: None,+ project_id: None,+ branched_from_id: None,+ branched_from_version_id: None,+ document_family_id: None,+ created_at: now,+ updated_at: now,+ viewed_at: None,+ sub_type: None,+ deleted_at: None,+ properties: vec![tag_property],+ };++ let tag_map: HashMap<_, _> = [(+ known_option,+ AppliedTag {+ label: "bug-report".to_string(),+ scope: TagScope::Personal,+ },+ )]+ .into();++ let entity_item = EntityItem::from_soup_item(SoupItem::Document(doc), &tag_map);+ match entity_item {+ EntityItem::Document { tags, .. } => {+ // The unknown option (another user's tag) is dropped.+ assert_eq!(+ tags,+ vec![AppliedTag {+ label: "bug-report".to_string(),+ scope: TagScope::Personal,+ }]+ );+ }+ other => panic!("expected document item, got {other:?}"),+ }+}+// run `cargo test -p soup inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`#[test]#[ignore = "prints the input schema"]diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rsindex 7de486e43b..3defd1b8a3 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs@@ -12,6 +12,7 @@ use crate::{};use either::Either;use macro_user_id::user_id::MacroUserIdStr;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_soup::{SoupProperty, item::SoupItem};use readonly_pool::ReadOnlyPool;use system_properties::SystemPropertyKey;@@ -134,6 +135,18 @@ impl SoupRepo for PgSoupRepo {populate_properties(&self.pool.0, user_id, items)}+ async fn caller_tag_sets<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, Self::Err> {+ properties::outbound::property_definition_queries::get_caller_tag_definitions_with_options(+ &self.pool.0,+ user_id.as_ref(),+ )+ .await+ .map_err(|e| sqlx::Error::Decode(e.into()))+ }+fn expanded_grouped_cursor_soup<'a>(&self,req: GroupedSortRequest<'a>,