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
Seanaye/feat/stop accepting invalid property info (#4949)
Sean Aye7186003271f7
diff --git a/.sqlx/query-68c14c7f2106ef2b3e27c398fa1ccfc398c0116e929e921a2b0d8d78ff035823.json b/.sqlx/query-68c14c7f2106ef2b3e27c398fa1ccfc398c0116e929e921a2b0d8d78ff035823.jsonnew file mode 100644index 0000000000..f5d7cb73f1--- /dev/null+++ b/.sqlx/query-68c14c7f2106ef2b3e27c398fa1ccfc398c0116e929e921a2b0d8d78ff035823.json@@ -0,0 +1,38 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n document_id,\n sub_type as \"sub_type: DocumentSubType\"\n FROM document_sub_type\n WHERE document_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "sub_type: DocumentSubType",+ "type_info": {+ "Custom": {+ "name": "document_sub_type_value",+ "kind": {+ "Enum": [+ "task",+ "snippet"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "68c14c7f2106ef2b3e27c398fa1ccfc398c0116e929e921a2b0d8d78ff035823"+}diff --git a/Cargo.lock b/Cargo.lockindex d5e9416990..da06935c85 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11016,6 +11016,7 @@ dependencies = ["async-trait","axum","chrono",+ "document_sub_type","entity_access","entity_access_db_utils","futures",diff --git a/apps/web/src/features/property/utils/entityConversion.ts b/apps/web/src/features/property/utils/entityConversion.tsindex b28819ccf1..227f6a78c3 100644--- a/apps/web/src/features/property/utils/entityConversion.ts+++ b/apps/web/src/features/property/utils/entityConversion.ts@@ -1,6 +1,7 @@import { type EntityData, isTaskEntity } from '@entity';import type { EntityReference } from '@service-properties/generated/schemas/entityReference';import { EntityType } from '@service-properties/generated/schemas/entityType';+import type { PropertyTargetEntityType } from '@service-properties/generated/schemas/propertyTargetEntityType';import type { ItemType } from '@service-storage/client';import { match } from 'ts-pattern';@@ -64,9 +65,9 @@ export function entityTypeToItemType(type: EntityType): ItemType | undefined {export function macroEntityToPropertyEntityType(entity: EntityData-): EntityType {+): PropertyTargetEntityType {return match(entity)- .when(isTaskEntity, () => EntityType.TASK)+ .when(isTaskEntity, () => EntityType.DOCUMENT).with({ type: 'channel' }, () => EntityType.CHANNEL).with({ type: 'chat' }, () => EntityType.CHAT).with({ type: 'project' }, () => EntityType.PROJECT)diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.tsindex 1dae71c9fc..d7d27e867e 100644--- a/apps/web/src/lib/queries/properties/entity.ts+++ b/apps/web/src/lib/queries/properties/entity.ts@@ -17,6 +17,7 @@ import { useMutation, useQuery } from '@tanstack/solid-query';import { type Accessor, batch } from 'solid-js';import { propertiesServiceClient } from '../../service-clients/service-properties/client';import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';+import type { PropertyTargetEntityType } from '../../service-clients/service-properties/generated/schemas/propertyTargetEntityType';import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';import { setEntityProperty } from '../../service-clients/service-storage/graphql-properties';@@ -39,6 +40,12 @@ import { type MutationCallbacks, withCallbacks } from '../utils';import { buildOptimisticSetEntityProperty } from './graphql-optimistic';import { propertiesKeys } from './keys';+function toPropertyTargetEntityType(+ entityType: EntityType+): PropertyTargetEntityType {+ return entityType === 'TASK' ? 'DOCUMENT' : entityType;+}+export function useEntityPropertiesQuery(entityType: Accessor<EntityType>,entityId: Accessor<string>,@@ -59,7 +66,7 @@ export function useEntityPropertiesQuery(const data = await throwOnErr(async () =>await propertiesServiceClient.getEntityProperties({- entity_type: type,+ entity_type: toPropertyTargetEntityType(type),entity_id: id,query: { include_metadata: true },})@@ -284,7 +291,7 @@ export function useAddEntityPropertyMutation(// New attachments have no assignment id until the server responds, so// this write is never optimistic; onSettled invalidation refetches.await setEntityProperty({- entityType: vars.entityType,+ entityType: toPropertyTargetEntityType(vars.entityType),entityId: vars.entityId,propertyDefinitionId: vars.propertyDefinitionId,value: null,@@ -385,7 +392,7 @@ export function useAddEntityPropertyOptionMutation(await throwOnErr(async () =>await propertiesServiceClient.addEntityPropertyOption({- entity_type: vars.entityType,+ entity_type: toPropertyTargetEntityType(vars.entityType),entity_id: vars.entityId,property_id: getPropertyDefinitionId(vars.property),option_id: vars.optionId,@@ -413,7 +420,7 @@ export function useRemoveEntityPropertyOptionMutation(await throwOnErr(async () =>await propertiesServiceClient.removeEntityPropertyOption({- entity_type: vars.entityType,+ entity_type: toPropertyTargetEntityType(vars.entityType),entity_id: vars.entityId,property_id: getPropertyDefinitionId(vars.property),option_id: vars.optionId,@@ -557,7 +564,7 @@ export function useBulkUpdateEntityPropertyOptionsMutation(const results = await Promise.allSettled(operations.map(({ update, delta }) => {const params = {- entity_type: variables.entityType,+ entity_type: toPropertyTargetEntityType(variables.entityType),entity_id: variables.entityId,property_id: getPropertyDefinitionId(update.property),option_id: delta.optionId,@@ -745,7 +752,7 @@ export function useBulkSaveEntityPropertiesMutation(}return setEntityProperty({- entityType: item.entityType,+ entityType: toPropertyTargetEntityType(item.entityType),entityId: item.entityId,propertyDefinitionId: getPropertyDefinitionId(item.property),value: propertyValue,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 25e08272a1..5ee0134d56 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -783,7 +783,6 @@ export const GetEntityProperties = z.object({entity_id: z.string(),entity_type: z.enum(['document',- 'task','project','chat','thread',@@ -2753,7 +2752,6 @@ export const SetEntityProperty = z.object({.optional(),entity_type: z.enum(['document',- 'task','project','chat','thread',diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 3919553ef2..dfa6afd2db 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -315,9 +315,11 @@ export type EntityItem =};type: 'foreignEntity';};-export type ToolEntityType =+/**+ * Canonical entity type accepted when an AI tool targets an entity's properties.+ */+export type ToolPropertyTargetEntityType =| 'document'- | 'task'| 'project'| 'chat'| 'thread'@@ -451,6 +453,16 @@ export type SendEmailResponse =draft_id: string;};};+export type ToolEntityType =+ | 'document'+ | 'task'+ | 'project'+ | 'chat'+ | 'thread'+ | 'channel'+ | 'call'+ | 'user'+ | 'company';/*** Content of a text editor code execution response - either a result or an error*/@@ -1601,14 +1613,14 @@ 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. 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.+ * Get all properties attached to an entity (document, project, CRM company, etc.). Tasks are targeted as entity_type=document. 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 task documents, 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 {/*** The ID of the entity to get properties for.*/entity_id: string;- entity_type: ToolEntityType;+ entity_type: ToolPropertyTargetEntityType;}/*** Response from the GetEntityProperties tool.@@ -3210,7 +3222,7 @@ export interface SendEmail {to: EmailRecipient[];}/**- * 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.+ * Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. 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.*@@ -3256,7 +3268,7 @@ export interface SetEntityProperty {* For multi entity reference properties.*/entity_refs?: ToolEntityRef[] | null;- entity_type: ToolEntityType;+ entity_type: ToolPropertyTargetEntityType;/*** For single link properties.*/diff --git a/apps/web/src/lib/service-clients/service-properties/client.ts b/apps/web/src/lib/service-clients/service-properties/client.tsindex cdf3e71ce0..0434c0052a 100644--- a/apps/web/src/lib/service-clients/service-properties/client.ts+++ b/apps/web/src/lib/service-clients/service-properties/client.ts@@ -12,18 +12,18 @@ import type { BulkEntityPropertiesRequest } from './generated/schemas/bulkEntityimport type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';import type { EnsureTagSetRequest } from './generated/schemas/ensureTagSetRequest';import type { EntityPropertiesResponse } from './generated/schemas/entityPropertiesResponse';-import type { EntityType } from './generated/schemas/entityType';import type { GetBulkEntityProperties200 } from './generated/schemas/getBulkEntityProperties200';import type { GetEntityPropertiesParams } from './generated/schemas/getEntityPropertiesParams';import type { ListPropertiesParams } from './generated/schemas/listPropertiesParams';import type { PropertyDefinition } from './generated/schemas/propertyDefinition';import type { PropertyDefinitionResponse } from './generated/schemas/propertyDefinitionResponse';import type { PropertyOption } from './generated/schemas/propertyOption';+import type { PropertyTargetEntityType } from './generated/schemas/propertyTargetEntityType';import type { SetEntityPropertyRequest } from './generated/schemas/setEntityPropertyRequest';import type { TagSetResponse } from './generated/schemas/tagSetResponse';import type { UpdatePropertyOptionRequest } from './generated/schemas/updatePropertyOptionRequest';-type PropertiesEntityType = EntityType;+type PropertiesEntityType = PropertyTargetEntityType;type ListPropertiesArgs = ListPropertiesParams;type CreatePropertyDefinitionArgs = {@@ -33,12 +33,12 @@ type DeletePropertyDefinitionArgs = {definition_id: string;};type GetEntityPropertiesArgs = {- entity_type: EntityType;+ entity_type: PropertyTargetEntityType;entity_id: string;query: GetEntityPropertiesParams;};type SetEntityPropertyArgs = {- entity_type: EntityType;+ entity_type: PropertyTargetEntityType;entity_id: string;property_id: string;body: SetEntityPropertyRequest;@@ -47,7 +47,7 @@ type DeleteEntityPropertyArgs = {entity_property_id: string;};type EntityPropertyOptionArgs = {- entity_type: EntityType;+ entity_type: PropertyTargetEntityType;entity_id: string;property_id: string;option_id: string;diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.tsindex d7b9e58b0c..1b8ad01cdd 100644--- a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts@@ -4,14 +4,14 @@* properties_service* OpenAPI spec version: 0.1.0*/-import type { EntityReference } from './entityReference';+import type { PropertyTargetReference } from './propertyTargetReference';/*** Request for getting properties for multiple entities in bulk*/export interface BulkEntityPropertiesRequest {/** Array of entity references (entity_id and entity_type pairs) */- entities: EntityReference[];+ entities: PropertyTargetReference[];/** Optional: only return properties with these definition IDs. If empty, returns all. */property_ids?: string[];}diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetEntityType.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetEntityType.tsnew file mode 100644index 0000000000..572bc005e4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetEntityType.ts@@ -0,0 +1,28 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * properties_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Canonical type of an entity receiving properties.++Tasks are documents at API boundaries. `Task` intentionally does not exist+here; task classification is resolved by the properties domain from the+document subtype.+ */+export type PropertyTargetEntityType =+ (typeof PropertyTargetEntityType)[keyof typeof PropertyTargetEntityType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const PropertyTargetEntityType = {+ CALL_RECORD: 'CALL_RECORD',+ CHANNEL: 'CHANNEL',+ CHAT: 'CHAT',+ COMPANY: 'COMPANY',+ DOCUMENT: 'DOCUMENT',+ PROJECT: 'PROJECT',+ THREAD: 'THREAD',+ USER: 'USER',+} as const;diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetReference.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetReference.tsnew file mode 100644index 0000000000..1ab1a5327d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/propertyTargetReference.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * properties_service+ * OpenAPI spec version: 0.1.0+ */+import type { PropertyTargetEntityType } from './propertyTargetEntityType';++/**+ * Canonical reference to an entity receiving properties.+ */+export interface PropertyTargetReference {+ /** Entity identifier. */+ entity_id: string;+ /** Canonical entity type. */+ entity_type: PropertyTargetEntityType;+}diff --git a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts b/apps/web/src/lib/service-clients/service-properties/generated/zod.tsindex a1337fabc2..e7a2927706 100644--- a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts@@ -507,7 +507,7 @@ export const getBulkEntityPropertiesBody = zod.array(zod.object({- entity_id: zod.string(),+ entity_id: zod.string().describe('Entity identifier.'),entity_type: zod.enum(['CALL_RECORD',@@ -516,21 +516,14 @@ export const getBulkEntityPropertiesBody = zod'COMPANY','DOCUMENT','PROJECT',- 'TASK','THREAD','USER',]).describe(- 'Type of entity that can be referenced by entity properties.'- ),- specific_message_id: zod- .uuid()- .nullish()- .describe(- 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ 'Canonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.'),})- .describe('Entity reference for entity-type property values.')+ .describe('Canonical reference to an entity receiving properties.')).describe('Array of entity references (entity_id and entity_type pairs)'),property_ids: zod@@ -842,11 +835,10 @@ export const getEntityPropertiesParams = zod.object({'COMPANY','DOCUMENT','PROJECT',- 'TASK','THREAD','USER',])- .describe('Entity type (user, document, channel, project, thread)'),+ .describe('Canonical entity type; tasks use DOCUMENT'),entity_id: zod.string().describe('Entity ID'),});@@ -1152,11 +1144,10 @@ export const setEntityPropertyParams = zod.object({'COMPANY','DOCUMENT','PROJECT',- 'TASK','THREAD','USER',])- .describe('Entity type (user, document, channel, project, thread)'),+ .describe('Canonical entity type; tasks use DOCUMENT'),entity_id: zod.string().describe('Entity ID'),property_id: zod.uuid().describe('Property ID'),});@@ -1315,11 +1306,10 @@ export const addEntityPropertyOptionParams = zod.object({'COMPANY','DOCUMENT','PROJECT',- 'TASK','THREAD','USER',])- .describe('Entity type (user, document, channel, project, thread)'),+ .describe('Canonical entity type; tasks use DOCUMENT'),entity_id: zod.string().describe('Entity ID'),property_id: zod.uuid().describe('Property ID'),option_id: zod.uuid().describe('Option ID to add'),@@ -1340,11 +1330,10 @@ export const removeEntityPropertyOptionParams = zod.object({'COMPANY','DOCUMENT','PROJECT',- 'TASK','THREAD','USER',])- .describe('Entity type (user, document, channel, project, thread)'),+ .describe('Canonical entity type; tasks use DOCUMENT'),entity_id: zod.string().describe('Entity ID'),property_id: zod.uuid().describe('Property ID'),option_id: zod.uuid().describe('Option ID to remove'),diff --git a/apps/web/src/lib/service-clients/service-properties/openapi.json b/apps/web/src/lib/service-clients/service-properties/openapi.jsonindex 4e12a93e9c..720b784908 100644--- a/apps/web/src/lib/service-clients/service-properties/openapi.json+++ b/apps/web/src/lib/service-clients/service-properties/openapi.json@@ -395,10 +395,10 @@{"name": "entity_type","in": "path",- "description": "Entity type (user, document, channel, project, thread)",+ "description": "Canonical entity type; tasks use DOCUMENT","required": true,"schema": {- "$ref": "#/components/schemas/EntityType"+ "$ref": "#/components/schemas/PropertyTargetEntityType"}},{@@ -455,10 +455,10 @@{"name": "entity_type","in": "path",- "description": "Entity type (user, document, channel, project, thread)",+ "description": "Canonical entity type; tasks use DOCUMENT","required": true,"schema": {- "$ref": "#/components/schemas/EntityType"+ "$ref": "#/components/schemas/PropertyTargetEntityType"}},{@@ -520,10 +520,10 @@{"name": "entity_type","in": "path",- "description": "Entity type (user, document, channel, project, thread)",+ "description": "Canonical entity type; tasks use DOCUMENT","required": true,"schema": {- "$ref": "#/components/schemas/EntityType"+ "$ref": "#/components/schemas/PropertyTargetEntityType"}},{@@ -580,10 +580,10 @@{"name": "entity_type","in": "path",- "description": "Entity type (user, document, channel, project, thread)",+ "description": "Canonical entity type; tasks use DOCUMENT","required": true,"schema": {- "$ref": "#/components/schemas/EntityType"+ "$ref": "#/components/schemas/PropertyTargetEntityType"}},{@@ -796,7 +796,7 @@"entities": {"type": "array","items": {- "$ref": "#/components/schemas/EntityReference"+ "$ref": "#/components/schemas/PropertyTargetReference"},"description": "Array of entity references (entity_id and entity_type pairs)"},@@ -1504,6 +1504,35 @@"description": "Scope filter for property queries","enum": ["user", "team", "system", "all"]},+ "PropertyTargetEntityType": {+ "type": "string",+ "description": "Canonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.",+ "enum": [+ "CALL_RECORD",+ "CHANNEL",+ "CHAT",+ "COMPANY",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER"+ ]+ },+ "PropertyTargetReference": {+ "type": "object",+ "description": "Canonical reference to an entity receiving properties.",+ "required": ["entity_id", "entity_type"],+ "properties": {+ "entity_id": {+ "type": "string",+ "description": "Entity identifier."+ },+ "entity_type": {+ "$ref": "#/components/schemas/PropertyTargetEntityType",+ "description": "Canonical entity type."+ }+ }+ },"PropertyValue": {"oneOf": [{diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.tsindex 192194717c..d73cbffa17 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts@@ -6,6 +6,7 @@ import type { SoupPropertyFieldsFragment } from './graphql/generated/graphql';import {setEntityProperty,toGraphqlPropertyEntityType,+ toGraphqlPropertyTargetEntityType,toGraphqlSetPropertyValue,} from './graphql-properties';import { getGraphqlSoupClient } from './graphql-soup';@@ -97,12 +98,17 @@ describe('toGraphqlSetPropertyValue', () => {});});-describe('toGraphqlPropertyEntityType', () => {- it('maps every REST entity type', () => {- expect(toGraphqlPropertyEntityType('DOCUMENT')).toBe('DOCUMENT');+describe('property entity type conversion', () => {+ it('keeps TASK for referenced property values', () => {expect(toGraphqlPropertyEntityType('TASK')).toBe('TASK');- expect(toGraphqlPropertyEntityType('COMPANY')).toBe('COMPANY');- expect(toGraphqlPropertyEntityType('CALL_RECORD')).toBe('CALL_RECORD');+ });++ it('maps canonical property targets without TASK', () => {+ expect(toGraphqlPropertyTargetEntityType('DOCUMENT')).toBe('DOCUMENT');+ expect(toGraphqlPropertyTargetEntityType('COMPANY')).toBe('COMPANY');+ expect(toGraphqlPropertyTargetEntityType('CALL_RECORD')).toBe(+ 'CALL_RECORD'+ );});});diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.tsindex bc27d3d7e1..087bfcedbf 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts@@ -20,10 +20,12 @@ import { match } from 'ts-pattern';import { propertiesServiceClient } from '../service-properties/client';import type { EntityReference } from '../service-properties/generated/schemas/entityReference';import type { EntityType } from '../service-properties/generated/schemas/entityType';+import type { PropertyTargetEntityType } from '../service-properties/generated/schemas/propertyTargetEntityType';import type { SetPropertyValue } from '../service-properties/generated/schemas/setPropertyValue';import {type GraphqlEntityReferenceInput,type GraphqlPropertyEntityType,+ type GraphqlPropertyTargetEntityType,type GraphqlSetPropertyValue,SetEntityPropertyDocument,type SetEntityPropertyMutation,@@ -55,6 +57,26 @@ export function toGraphqlPropertyEntityType(return ENTITY_TYPE_TO_GRAPHQL[entityType];}+const TARGET_ENTITY_TYPE_TO_GRAPHQL: Record<+ PropertyTargetEntityType,+ GraphqlPropertyTargetEntityType+> = {+ CALL_RECORD: 'CALL_RECORD',+ CHANNEL: 'CHANNEL',+ CHAT: 'CHAT',+ COMPANY: 'COMPANY',+ DOCUMENT: 'DOCUMENT',+ PROJECT: 'PROJECT',+ THREAD: 'THREAD',+ USER: 'USER',+};++export function toGraphqlPropertyTargetEntityType(+ entityType: PropertyTargetEntityType+): GraphqlPropertyTargetEntityType {+ return TARGET_ENTITY_TYPE_TO_GRAPHQL[entityType];+}+function toGraphqlEntityReference(reference: EntityReference): GraphqlEntityReferenceInput {@@ -125,7 +147,7 @@ export function toGraphqlSetPropertyValue(}export type SetEntityPropertyArgs = {- entityType: EntityType;+ entityType: PropertyTargetEntityType;entityId: string;propertyDefinitionId: string;/** REST-shaped value; `null` attaches the property without a value. */@@ -165,7 +187,7 @@ export async function setEntityProperty(const client = getGraphqlSoupClient();const variables: SetEntityPropertyMutationVariables = {input: {- entityType: toGraphqlPropertyEntityType(args.entityType),+ entityType: toGraphqlPropertyTargetEntityType(args.entityType),entityId: args.entityId,propertyDefinitionId: args.propertyDefinitionId,value: toGraphqlSetPropertyValue(args.value),diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex aa52aa21ca..92f347c894 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -568,6 +568,25 @@ export type GraphqlPropertyMatchValue =| { entityRef?: never; /** Select option id to match. */selectOption: string | number; };+/** Canonical entity type accepted for property targets. */+export type GraphqlPropertyTargetEntityType =+ /** Call record target. */+ | 'CALL_RECORD'+ /** Channel target. */+ | 'CHANNEL'+ /** Chat target. */+ | 'CHAT'+ /** CRM company target. */+ | 'COMPANY'+ /** Document target, including tasks and snippets. */+ | 'DOCUMENT'+ /** Project target. */+ | 'PROJECT'+ /** Email thread target. */+ | 'THREAD'+ /** User target. */+ | 'USER';+/** A typed value accepted when setting an entity property. */export type GraphqlSetPropertyValue ={ /** A Boolean value. */@@ -674,7 +693,7 @@ export type SetEntityPropertyInput = {/** Identifier of the entity receiving the property. */entityId: string;/** Type of entity receiving the property. */- entityType: GraphqlPropertyEntityType;+ entityType: GraphqlPropertyTargetEntityType;/** Identifier of the property definition to assign. */propertyDefinitionId: string | number;/** Omit or pass null to attach the property without a value. */diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex f5615f9be8..66e97aef5d 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -256,16 +256,11 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {&user_id,None,entity_id,- properties::access_entity_type(models_properties::EntityType::Task),+ model_entity::EntityType::Document,).await?;- let access = properties::PropertiesAccessReceipt::try_from_entity_access_receipt(- entity_access_receipt,- models_properties::EntityType::Task,- )?;-self.properties- .set_entity_property(&access, property_definition_id, value)+ .set_entity_property(&entity_access_receipt, property_definition_id, value).await.map(|_| ()).map_err(Into::into)diff --git a/crates/crm/src/inbound/toolset/get_company.rs b/crates/crm/src/inbound/toolset/get_company.rsindex 76e1c21601..9cbf8296c5 100644--- a/crates/crm/src/inbound/toolset/get_company.rs+++ b/crates/crm/src/inbound/toolset/get_company.rs@@ -10,9 +10,9 @@ use entity_access::domain::{},ports::EntityAccessService,};+use models_properties::DataType;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_option::PropertyOptionValue;-use models_properties::{DataType, EntityType as PropertyEntityType};use properties::PropertiesService;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -208,10 +208,10 @@ where// Asserted rather than minted: view access to this company was just// verified above via `get_crm_entity_permission_with_team`.let properties_access =- properties::PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(request_context.user_id.clone(),&company_id,- PropertyEntityType::Company,+ EntityType::CrmCompany,);let properties = service_context.propertiesdiff --git a/crates/crm/src/inbound/toolset/list_companies.rs b/crates/crm/src/inbound/toolset/list_companies.rsindex 1bddc1e972..03bb28a0c5 100644--- a/crates/crm/src/inbound/toolset/list_companies.rs+++ b/crates/crm/src/inbound/toolset/list_companies.rs@@ -3,9 +3,11 @@use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use chrono::{DateTime, Utc};-use entity_access::domain::{models::TeamRole, ports::EntityAccessService};-use models_properties::EntityType as PropertyEntityType;-use properties::{EntityPropertiesKey, PropertiesService};+use entity_access::domain::{+ models::{EntityType, TeamRole},+ ports::EntityAccessService,+};+use properties::{PropertiesService, PropertyTargetKey};use schemars::JsonSchema;use serde::{Deserialize, Serialize};use system_properties::SystemPropertyKey;@@ -241,9 +243,9 @@ wherelet mut items: Vec<CompanyListItem> = Vec::new();let mut total_matching = 0usize;for company in companies {- let props_key = EntityPropertiesKey {+ let props_key = PropertyTargetKey {entity_id: company.company.id.to_string(),- entity_type: PropertyEntityType::Company,+ entity_type: EntityType::CrmCompany,};let props = properties_map.get(&props_key)diff --git a/crates/crm/src/inbound/toolset/mod.rs b/crates/crm/src/inbound/toolset/mod.rsindex 188f9333bd..d86bd49330 100644--- a/crates/crm/src/inbound/toolset/mod.rs+++ b/crates/crm/src/inbound/toolset/mod.rs@@ -15,14 +15,14 @@ use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};use entity_access::domain::{models::{AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole,- TeamRole,+ TeamRole, ViewAccessLevel,},ports::EntityAccessService,};+use models_properties::DataType;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;-use models_properties::{DataType, EntityType as PropertyEntityType};use properties::PropertiesService;use schemars::JsonSchema;use serde::Serialize;@@ -309,10 +309,10 @@ pub(crate) fn company_view_receipts(company_ids.into_iter().map(|id| {- properties::PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(user_id.clone(),&id.to_string(),- PropertyEntityType::Company,+ EntityType::CrmCompany,)}).collect()diff --git a/crates/graphql_properties/src/lib.rs b/crates/graphql_properties/src/lib.rsindex 76253f76bb..bed9ad31df 100644--- a/crates/graphql_properties/src/lib.rs+++ b/crates/graphql_properties/src/lib.rs@@ -18,8 +18,8 @@ pub use loaders::{PropertiesEntityPropertyReader, entity_properties_loader,};pub use mutations::{- EntityPropertyWriter, NoOpEntityPropertyWriter, PropertiesEntityPropertyWriter,- PropertiesMutationRoot,+ EntityPropertyWriter, GraphqlPropertyTargetEntityType, NoOpEntityPropertyWriter,+ PropertiesEntityPropertyWriter, PropertiesMutationRoot,};pub use objects::{GraphqlBooleanPropertyValue, GraphqlDatePropertyValue, GraphqlEntityReferencePropertyValue,diff --git a/crates/graphql_properties/src/loaders.rs b/crates/graphql_properties/src/loaders.rsindex 7f8036815a..24ec7f43e3 100644--- a/crates/graphql_properties/src/loaders.rs+++ b/crates/graphql_properties/src/loaders.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, str::FromStr, sync::Arc};+use std::{collections::HashMap, sync::Arc};use async_graphql::dataloader::{DataLoader, Loader};use entity_access::domain::models::ViewAccessLevel;@@ -7,17 +7,20 @@ use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use rootcause::markers::{Cloneable, Dynamic};-/// Map a shared entity type to its properties-domain representation.-fn property_entity_type(- entity_type: model_entity::EntityType,-) -> Option<models_properties::EntityType> {+/// Whether the canonical entity type supports property targets.+fn is_property_target(entity_type: model_entity::EntityType) -> bool {use model_entity::EntityType;- match entity_type {- EntityType::EmailThread => Some(models_properties::EntityType::Thread),- EntityType::CrmCompany => Some(models_properties::EntityType::Company),- EntityType::Call | EntityType::ChannelMessage | EntityType::ForeignEntity => None,- other => models_properties::EntityType::from_str(other.as_ref()).ok(),- }+ matches!(+ entity_type,+ EntityType::Document+ | EntityType::EmailThread+ | EntityType::CrmCompany+ | EntityType::Call+ | EntityType::Chat+ | EntityType::Channel+ | EntityType::Project+ | EntityType::User+ )}/// Reader used by GraphQL property edges.@@ -96,24 +99,19 @@ where// skipped and keep their empty property list.let mut receipts = Vec::with_capacity(keys.len());for key in keys {- let Some(entity_type) = property_entity_type(key.entity_type) else {+ if !is_property_target(key.entity_type) {continue;- };+ }let access_receipt = self.entity_access_service.generate_entity_access_receipt::<ViewAccessLevel>(user_id,None,&key.entity_id,- properties::access_entity_type(entity_type),+ key.entity_type,).await;- match access_receipt.and_then(|receipt| {- properties::PropertiesAccessReceipt::try_from_entity_access_receipt(- receipt,- entity_type,- )- }) {+ match access_receipt {Ok(receipt) => receipts.push(receipt),Err(err) => {tracing::debug!(@@ -136,16 +134,14 @@ where.await.map_err(|err| rootcause::report!(err))?;- // Merge back under the original loader keys: the batch result is keyed- // by the normalized entity type, which for alias keys ("email",- // "email_thread", "crm_company") differs from the requested key.+ // Merge back under the original canonical loader keys.for key in keys {- let Some(entity_type) = property_entity_type(key.entity_type) else {+ if !is_property_target(key.entity_type) {continue;- };- let batch_key = properties::EntityPropertiesKey {+ }+ let batch_key = properties::PropertyTargetKey {entity_id: key.entity_id.to_string(),- entity_type,+ entity_type: key.entity_type,};if let Some(properties) = properties_by_entity.get(&batch_key) {result.insert(key.clone(), properties.clone());diff --git a/crates/graphql_properties/src/mutations.rs b/crates/graphql_properties/src/mutations.rsindex 6f0c1da6cd..3e615c3fce 100644--- a/crates/graphql_properties/src/mutations.rs+++ b/crates/graphql_properties/src/mutations.rs@@ -6,7 +6,7 @@ use macro_user_id::user_id::MacroUserIdStr;use models_properties::api::requests::SetPropertyValue;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::shared::EntityReference;-use properties::{PropertiesAccessReceipt, PropertiesService, access_entity_type};+use properties::PropertiesService;use std::{marker::PhantomData, sync::Arc};use uuid::Uuid;@@ -28,7 +28,7 @@ pub trait EntityPropertyWriter: Send + Sync + 'static {/// Set or attach one property on an entity.fn set_entity_property(&self,- entity_type: models_properties::EntityType,+ entity_type: model_entity::EntityType,entity_id: String,property_definition_id: Uuid,value: Option<SetPropertyValue>,@@ -42,7 +42,7 @@ pub struct NoOpEntityPropertyWriter;impl EntityPropertyWriter for NoOpEntityPropertyWriter {async fn set_entity_property(&self,- _entity_type: models_properties::EntityType,+ _entity_type: model_entity::EntityType,_entity_id: String,_property_definition_id: Uuid,_value: Option<SetPropertyValue>,@@ -83,7 +83,7 @@ where{async fn set_entity_property(&self,- entity_type: models_properties::EntityType,+ entity_type: model_entity::EntityType,entity_id: String,property_definition_id: Uuid,value: Option<SetPropertyValue>,@@ -94,29 +94,59 @@ where&self.user_id,None,&entity_id,- access_entity_type(entity_type),+ entity_type,).await.map_err(|err| rootcause::report!(err))?;- let access = PropertiesAccessReceipt::try_from_entity_access_receipt(- entity_access_receipt,- entity_type,- )- .map_err(|err| rootcause::report!(err))?;-Ok(self.properties_service- .set_entity_property(&access, property_definition_id, value)+ .set_entity_property(&entity_access_receipt, property_definition_id, value).await.map_err(|err| rootcause::report!(err))?)}}+/// Canonical entity type accepted for property targets.+#[derive(async_graphql::Enum, Copy, Clone, Eq, PartialEq)]+pub enum GraphqlPropertyTargetEntityType {+ /// Call record target.+ CallRecord,+ /// Channel target.+ Channel,+ /// Chat target.+ Chat,+ /// CRM company target.+ Company,+ /// Document target, including tasks and snippets.+ Document,+ /// Project target.+ Project,+ /// Email thread target.+ Thread,+ /// User target.+ User,+}++impl From<GraphqlPropertyTargetEntityType> for model_entity::EntityType {+ fn from(value: GraphqlPropertyTargetEntityType) -> Self {+ match value {+ GraphqlPropertyTargetEntityType::CallRecord => Self::Call,+ GraphqlPropertyTargetEntityType::Channel => Self::Channel,+ GraphqlPropertyTargetEntityType::Chat => Self::Chat,+ GraphqlPropertyTargetEntityType::Company => Self::CrmCompany,+ GraphqlPropertyTargetEntityType::Document => Self::Document,+ GraphqlPropertyTargetEntityType::Project => Self::Project,+ GraphqlPropertyTargetEntityType::Thread => Self::EmailThread,+ GraphqlPropertyTargetEntityType::User => Self::User,+ }+ }+}+/// Input for assigning or updating an entity property.#[derive(async_graphql::InputObject)]struct SetEntityPropertyInput {/// Type of entity receiving the property.- entity_type: GraphqlPropertyEntityType,+ entity_type: GraphqlPropertyTargetEntityType,/// Identifier of the entity receiving the property.entity_id: String,/// Identifier of the property definition to assign.@@ -268,7 +298,7 @@ mod tests {}type CapturedWrite = (- models_properties::EntityType,+ model_entity::EntityType,String,Uuid,Option<SetPropertyValue>,@@ -283,7 +313,7 @@ mod tests {impl EntityPropertyWriter for CapturingWriter {async fn set_entity_property(&self,- entity_type: models_properties::EntityType,+ entity_type: model_entity::EntityType,entity_id: String,property_definition_id: Uuid,value: Option<SetPropertyValue>,@@ -344,7 +374,7 @@ mod tests {r#"mutation {{setEntityProperty(input: {{- entityType: TASK,+ entityType: DOCUMENT,entityId: "task-1",propertyDefinitionId: "{property_definition_id}",value: {{ selectOption: "{option_id}" }}@@ -392,7 +422,7 @@ mod tests {assert_eq!(writer.write.lock().expect("capture mutex poisoned").clone(),Some((- models_properties::EntityType::Task,+ model_entity::EntityType::Document,"task-1".to_string(),property_definition_id,Some(SetPropertyValue::SelectOption { option_id }),diff --git a/crates/models_properties/src/api/mod.rs b/crates/models_properties/src/api/mod.rsindex f2446ccb9b..149f90b3e4 100644--- a/crates/models_properties/src/api/mod.rs+++ b/crates/models_properties/src/api/mod.rs@@ -4,6 +4,7 @@//! They use ToSchema for OpenAPI documentation and may use camelCase serialization.pub mod error;+pub mod property_target;pub mod query_params;pub mod requests;pub mod responses;@@ -12,6 +13,7 @@ pub use error::{PropertyDefinitionValidationError, PropertyOptionValidationError, PropertyValueValidationError,QueryParamValidationError,};+pub use property_target::{PropertyTargetEntityType, PropertyTargetReference};pub use query_params::{BulkEntityQueryParams, EntityQueryParams};pub use requests::{AddNumberOptionRequest, AddPropertyOptionRequest, AddStringOptionRequest,diff --git a/crates/models_properties/src/api/property_target.rs b/crates/models_properties/src/api/property_target.rsnew file mode 100644index 0000000000..61813e4b7e--- /dev/null+++ b/crates/models_properties/src/api/property_target.rs@@ -0,0 +1,39 @@+//! Canonical entity targets accepted by property APIs.++use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++/// Canonical type of an entity receiving properties.+///+/// Tasks are documents at API boundaries. `Task` intentionally does not exist+/// here; task classification is resolved by the properties domain from the+/// document subtype.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema, PartialEq, Eq, Hash)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum PropertyTargetEntityType {+ /// Voice/video call.+ CallRecord,+ /// Channel conversation.+ Channel,+ /// AI chat.+ Chat,+ /// CRM company.+ Company,+ /// Document, including tasks and snippets.+ Document,+ /// Project.+ Project,+ /// Email thread.+ Thread,+ /// User.+ User,+}++/// Canonical reference to an entity receiving properties.+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq, Hash)]+pub struct PropertyTargetReference {+ /// Entity identifier.+ pub entity_id: String,+ /// Canonical entity type.+ pub entity_type: PropertyTargetEntityType,+}diff --git a/crates/properties/Cargo.toml b/crates/properties/Cargo.tomlindex d5dfb894d9..94bb1dd593 100644--- a/crates/properties/Cargo.toml+++ b/crates/properties/Cargo.toml@@ -45,6 +45,7 @@ anyhow = { workspace = true }async-trait = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }+document_sub_type = { path = "../document_sub_type" }entity_access = { path = "../entity_access", default-features = false, features = ["ports",] }diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rsindex 60fdfc6c2d..17cd7c8b6b 100644--- a/crates/properties/src/domain/model.rs+++ b/crates/properties/src/domain/model.rs@@ -1,8 +1,8 @@//! Domain models for properties.use entity_access::domain::models::{- AccessLevel, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,- EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityType as AccessEntityType,+ RequiredPermission, ViewAccessLevel,};use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::property_definition::PropertyDefinition;@@ -11,150 +11,81 @@ use models_properties::service::property_value::PropertyValue;use models_properties::{DataType, EntityReference, EntityType, PropertyOwner};use uuid::Uuid;-/// Map a properties entity type onto the entity type used by the access-/// control system. Tasks are stored as documents, so the mapping collapses-/// Task into Document; [`PropertiesAccessReceipt`] preserves the original type.-pub fn access_entity_type(entity_type: EntityType) -> AccessEntityType {+/// Map an internal properties storage type to its canonical entity type.+pub fn canonical_entity_type(entity_type: EntityType) -> AccessEntityType {match entity_type {- EntityType::Document => AccessEntityType::Document,- // Call access is resolved through the call's owning channel.+ EntityType::Document | EntityType::Task => AccessEntityType::Document,EntityType::CallRecord => AccessEntityType::Call,EntityType::Chat => AccessEntityType::Chat,EntityType::Project => AccessEntityType::Project,EntityType::Thread => AccessEntityType::EmailThread,EntityType::Channel => AccessEntityType::Channel,- // Tasks are stored as documents, so they share document permissions.- EntityType::Task => AccessEntityType::Document,- // CRM company access is resolved from the owning team's membership.EntityType::Company => AccessEntityType::CrmCompany,EntityType::User => AccessEntityType::User,}}-/// Proof that a caller holds (at least) permission `T` on one entity.-///-/// Wraps the [`EntityAccessReceipt`] minted by the permission adapter together-/// with the original properties entity type, which the access-control mapping-/// loses (Task maps to Document). Every entity-scoped-/// [`PropertiesService`](super::service::PropertiesService) method takes one of-/// these, so an unchecked call cannot compile.-#[derive(Debug, Clone)]-pub struct PropertiesAccessReceipt<T: RequiredPermission> {- receipt: EntityAccessReceipt<T>,- entity_id: String,- entity_type: EntityType,+/// Proof of view (or better) access to one canonical entity.+pub type ViewReceipt = EntityAccessReceipt<ViewAccessLevel>;+/// Proof of edit (or better) access to one canonical entity.+pub type EditReceipt = EntityAccessReceipt<EditAccessLevel>;++/// Convenience accessors for canonical property access receipts.+pub trait PropertyAccessReceiptExt {+ /// Canonical entity identifier.+ fn entity_id(&self) -> &str;+ /// Canonical entity type.+ fn entity_type(&self) -> AccessEntityType;+ /// Authenticated user, if the receipt represents one.+ fn authenticated_user(&self) -> Option<&MacroUserIdStr<'static>>;}-/// Proof of view (or better) access to one entity.-pub type ViewReceipt = PropertiesAccessReceipt<ViewAccessLevel>;-/// Proof of edit (or better) access to one entity.-pub type EditReceipt = PropertiesAccessReceipt<EditAccessLevel>;--impl<T: RequiredPermission> PropertiesAccessReceipt<T> {- /// Wrap a receipt minted by the entity access service while preserving the- /// original properties entity type (notably, tasks map to documents in the- /// access service).- pub fn try_from_entity_access_receipt(- receipt: EntityAccessReceipt<T>,- entity_type: EntityType,- ) -> Result<Self, entity_access::domain::models::AccessError> {- if receipt.entity().entity_type != access_entity_type(entity_type) {- return Err(entity_access::domain::models::AccessError::BadRequest(- "entity access receipt type does not match properties entity type",- ));- }-- let entity_id = receipt.entity().entity_id.clone();- Ok(Self {- receipt,- entity_id,- entity_type,- })+impl<T: RequiredPermission> PropertyAccessReceiptExt for EntityAccessReceipt<T> {+ fn entity_id(&self) -> &str {+ &self.entity().entity_id}- /// The entity this receipt grants access to.- pub fn entity_id(&self) -> &str {- &self.entity_id+ fn entity_type(&self) -> AccessEntityType {+ self.entity().entity_type}- /// The properties entity type this receipt grants access to.- pub fn entity_type(&self) -> EntityType {- self.entity_type- }-- /// How the caller was authenticated.- pub fn auth(&self) -> &EntityAccessAuth {- self.receipt.auth()- }-- /// The authenticated user this receipt was minted for, if any- /// (`None` for bot, internal, and anonymous-public access).- pub fn authenticated_user(&self) -> Option<&MacroUserIdStr<'static>> {- match self.receipt.auth() {+ fn authenticated_user(&self) -> Option<&MacroUserIdStr<'static>> {+ match self.auth() {EntityAccessAuth::Authenticated(user) => Some(user),EntityAccessAuth::Bot(_)| EntityAccessAuth::Unauthenticated| EntityAccessAuth::Internal => None,}}+}- /// Dangerously mint a receipt for an internal (service-to-service or- /// worker) caller without an access check.- /// **NOTE** Use only for machine flows that operate outside a user- /// session; never to bypass a user's permission check.- pub fn dangerously_assert_internal(entity_id: &str, entity_type: EntityType) -> Self {- Self {- receipt: EntityAccessReceipt::dangerously_assert_internal_user(- entity_id,- access_entity_type(entity_type),- ),- entity_id: entity_id.to_string(),- entity_type,- }- }+/// Canonical key identifying an entity receiving properties.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct PropertyTargetKey {+ /// Canonical entity identifier.+ pub entity_id: String,+ /// Canonical entity type. Tasks use `Document`.+ pub entity_type: AccessEntityType,+}- /// Dangerously mint a receipt for an authenticated user without the- /// underlying access check. **NOTE** Intended for tests, and for callers- /// that have already verified the user's access to the entity through- /// another authoritative seam (e.g. a CRM team-scoped listing) — never as- /// a way to skip a check that hasn't happened.- pub fn dangerously_assert_authenticated_user(- user_id: MacroUserIdStr<'static>,- entity_id: &str,- entity_type: EntityType,- ) -> Self {- Self {- receipt: EntityAccessReceipt::dangerously_assert_authenticated_user(- user_id,- entity_id,- access_entity_type(entity_type),- ),- entity_id: entity_id.to_string(),- entity_type,- }- }+/// A canonical property target resolved to its internal storage namespace.+#[derive(Debug, Clone)]+pub(crate) struct ResolvedPropertySubject {+ pub(crate) canonical_key: PropertyTargetKey,+ pub(crate) storage_entity_type: EntityType,+}- /// Mint a receipt from a resolved permission, validating it satisfies `T`.- /// Only the permission adapter constructs these.- pub(crate) fn try_from_permission(- auth: EntityAccessAuth,- entity_id: &str,- entity_type: EntityType,- access_level: AccessLevel,- ) -> Result<Self, entity_access::domain::models::AccessError> {- let receipt = EntityAccessReceipt::try_new(- auth,- Entity {- entity_id: entity_id.to_string(),- entity_type: access_entity_type(entity_type),- },- EntityPermission::AccessLevel { access_level },- )?;- Self::try_from_entity_access_receipt(receipt, entity_type)+impl ResolvedPropertySubject {+ /// Return the repository key for this subject.+ pub(crate) fn storage_key(&self) -> EntityPropertiesKey {+ EntityPropertiesKey {+ entity_id: self.canonical_key.entity_id.clone(),+ entity_type: self.storage_entity_type,+ }}}-/// Key identifying the properties attached to one entity.+/// Internal repository key identifying properties attached to one entity.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct EntityPropertiesKey {pub entity_id: String,diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rsindex 66a5702273..e6e3734cc2 100644--- a/crates/properties/src/domain/ports.rs+++ b/crates/properties/src/domain/ports.rs@@ -5,6 +5,8 @@use std::collections::HashMap;+use document_sub_type::DocumentSubType;+use entity_access::domain::models::EntityType as AccessEntityType;use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::document_metadata::DocumentMetadata;use models_properties::service::entity_property::EntityProperty;@@ -296,6 +298,15 @@ pub trait PropertiesRepo: Send + Sync + 'static {entity_reference: &EntityReference,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Resolve document subtype facts in one batch.+ ///+ /// Missing IDs and documents without a subtype are omitted. Callers treat+ /// either case as a regular document.+ fn get_document_sub_types(+ &self,+ document_ids: &[Uuid],+ ) -> impl Future<Output = Result<HashMap<Uuid, DocumentSubType>, Self::Err>> + Send;+/// Get a document's metadata (name, owner, timestamps, project)./// Returns `None` if the document doesn't exist./// Tasks are stored as documents, so this works for both.@@ -340,7 +351,7 @@ pub trait PermissionService: Send + Sync + 'static {&self,user_id: Option<&'a MacroUserIdStr<'a>>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> impl Future<Output = Result<ViewReceipt, Self::Err>> + Send;/// Mint a proof that the user has edit (or owner) access to the entity.@@ -351,7 +362,7 @@ pub trait PermissionService: Send + Sync + 'static {&self,user_id: &MacroUserIdStr<'a>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> impl Future<Output = Result<EditReceipt, Self::Err>> + Send;/// Grant edit permissions to users for a task.diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rsindex c26524063b..b23293131f 100644--- a/crates/properties/src/domain/service.rs+++ b/crates/properties/src/domain/service.rs@@ -5,13 +5,14 @@//! access, and owner-scoped methods take the caller's identity plus their//! team-membership receipt. User-facing callers mint receipts through the//! entity access service at the inbound edge; internal (machine) callers mint-//! via [`PropertiesAccessReceipt::dangerously_assert_internal`](super::model::PropertiesAccessReceipt::dangerously_assert_internal),-//! which makes unchecked paths explicit and greppable.+//! via [`EntityAccessReceipt::dangerously_assert_internal_user`], which makes+//! unchecked paths explicit and greppable.use std::collections::HashMap;use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;+use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;use models_properties::api::{AddPropertyOptionRequest, CreatePropertyDefinitionRequest, UpdatePropertyOptionRequest,@@ -21,13 +22,12 @@ use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_properties::service::property_option::PropertyOption;use models_properties::service::property_value::PropertyValue;-use models_properties::{EntityPropertyReference, EntityType};use system_properties::SystemPropertyKey;use uuid::Uuid;use super::error::PropertiesErr;use super::model::{- EditReceipt, EntityPropertiesKey, EntityPropertyInfo, TagScope, TagSet, ViewReceipt,+ EditReceipt, EntityPropertyInfo, PropertyTargetKey, TagScope, TagSet, ViewReceipt,};/// The caller's team-membership proof, used to scope definition/option/tag@@ -238,7 +238,7 @@ pub trait PropertiesService: Send + Sync + 'static {property_ids: Vec<Uuid>,) -> impl Future<Output = Result<- HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>,+ HashMap<PropertyTargetKey, Vec<EntityPropertyWithDefinition>>,PropertiesErr,>,> + Send;@@ -255,7 +255,7 @@ pub trait PropertiesService: Send + Sync + 'static {fn lookup_entity_property(&self,entity_property_id: Uuid,- ) -> impl Future<Output = Result<Option<EntityPropertyReference>, PropertiesErr>> + Send;+ ) -> impl Future<Output = Result<Option<PropertyTargetKey>, PropertiesErr>> + Send;/// Delete a single entity property by its ID. The receipt must be for the/// entity the property is attached to. Fails when the property doesn'tdiff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rsindex 71048d422a..561793d78f 100644--- a/crates/properties/src/domain/service_impl/mod.rs+++ b/crates/properties/src/domain/service_impl/mod.rs@@ -3,8 +3,12 @@mod helpers;mod task_properties;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};+use document_sub_type::DocumentSubType;+use entity_access::domain::models::{+ EntityAccessReceipt, EntityType as AccessEntityType, RequiredPermission,+};use macro_user_id::user_id::MacroUserIdStr;use models_properties::DataType;use models_properties::api::requests::SetPropertyValue;@@ -18,7 +22,7 @@ use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;-use models_properties::{EntityPropertyReference, EntityReference, EntityType};+use models_properties::{EntityReference, EntityType};use system_properties::SystemPropertyKey;use uuid::Uuid;@@ -27,8 +31,9 @@ use std::sync::Arc;use super::error::PropertiesErr;use super::metadata;use super::model::{- EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagScope,- TagSet, UpdatePropertyOptionOutcome, ViewReceipt,+ EditReceipt, EntityPropertyInfo, PropertyAccessReceiptExt, PropertyDefinitionOwner,+ PropertyTargetKey, ResolvedPropertySubject, TagScope, TagSet, UpdatePropertyOptionOutcome,+ ViewReceipt,};use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};@@ -100,6 +105,80 @@ where.ok_or(PropertiesErr::PermissionServiceNotConfigured)}+ /// Resolve canonical access receipts to internal properties storage keys.+ async fn resolve_subjects<T: RequiredPermission>(+ &self,+ access: &[EntityAccessReceipt<T>],+ ) -> Result<Vec<ResolvedPropertySubject>, PropertiesErr>+ where+ anyhow::Error: From<R::Err>,+ {+ let document_ids = access+ .iter()+ .filter(|receipt| receipt.entity_type() == AccessEntityType::Document)+ .filter_map(|receipt| Uuid::parse_str(receipt.entity_id()).ok())+ .collect::<HashSet<_>>();++ let document_sub_types = if document_ids.is_empty() {+ HashMap::new()+ } else {+ self.repository+ .get_document_sub_types(&document_ids.into_iter().collect::<Vec<_>>())+ .await+ .map_err(anyhow::Error::from)?+ };++ access+ .iter()+ .map(|receipt| {+ let canonical_entity_type = receipt.entity_type();+ let storage_entity_type = match canonical_entity_type {+ AccessEntityType::Document => Uuid::parse_str(receipt.entity_id())+ .ok()+ .and_then(|document_id| document_sub_types.get(&document_id))+ .map_or(EntityType::Document, |sub_type| match sub_type {+ DocumentSubType::Task => EntityType::Task,+ DocumentSubType::Snippet => EntityType::Document,+ }),+ AccessEntityType::EmailThread => EntityType::Thread,+ AccessEntityType::Call => EntityType::CallRecord,+ AccessEntityType::CrmCompany => EntityType::Company,+ AccessEntityType::Chat => EntityType::Chat,+ AccessEntityType::Channel => EntityType::Channel,+ AccessEntityType::Project => EntityType::Project,+ AccessEntityType::User => EntityType::User,+ unsupported => {+ return Err(PropertiesErr::Validation(format!(+ "Unsupported property target type: {unsupported}"+ )));+ }+ };++ Ok(ResolvedPropertySubject {+ canonical_key: PropertyTargetKey {+ entity_id: receipt.entity_id().to_string(),+ entity_type: canonical_entity_type,+ },+ storage_entity_type,+ })+ })+ .collect()+ }++ /// Resolve one canonical access receipt to its internal storage key.+ async fn resolve_subject<T: RequiredPermission>(+ &self,+ access: &EntityAccessReceipt<T>,+ ) -> Result<ResolvedPropertySubject, PropertiesErr>+ where+ anyhow::Error: From<R::Err>,+ {+ self.resolve_subjects(std::slice::from_ref(access))+ .await?+ .pop()+ .ok_or_else(|| PropertiesErr::Validation("Missing property target".to_string()))+ }+/// Best-effort publish of a property reindex for entity types whose/// search index denormalizes property values. Logs and continues on/// failure so a missed reindex never fails the mutation itself.@@ -232,13 +311,18 @@ where// Tag properties are filtered in the query to definitions the viewer// can see: their own and their teams'. Receipts without an// authenticated user (anonymous public / internal) see no tags.+ let subject = self.resolve_subject(access).await?;let tag_viewer_user_id = access.authenticated_user().map(|user| user.as_ref()).unwrap_or_default();Ok(self.repository- .get_entity_properties(access.entity_id(), access.entity_type(), tag_viewer_user_id)+ .get_entity_properties(+ access.entity_id(),+ subject.storage_entity_type,+ tag_viewer_user_id,+ ).await.map_err(anyhow::Error::from)?)}@@ -261,11 +345,12 @@ whereaccess: &ViewReceipt,property_definition_id: Uuid,) -> Result<Option<PropertyValue>, PropertiesErr> {+ let subject = self.resolve_subject(access).await?;Ok(self.repository.get_entity_property_value(access.entity_id(),- access.entity_type(),+ subject.storage_entity_type,property_definition_id,).await@@ -296,8 +381,9 @@ whereproperty_definition_id: Uuid,value: Option<SetPropertyValue>,) -> Result<EntityPropertyWithDefinition, PropertiesErr> {+ let subject = self.resolve_subject(access).await?;let entity_id = access.entity_id();- let entity_type = access.entity_type();+ let entity_type = subject.storage_entity_type;// Get property definition to validate it exists and for validationlet property_definition = self@@ -430,7 +516,8 @@ where));}- if !is_property_applicable_to(property_definition_id, access.entity_type()) {+ let subject = self.resolve_subject(access).await?;+ if !is_property_applicable_to(property_definition_id, subject.storage_entity_type) {return Err(PropertiesErr::Validation("This property cannot be attached to this entity type".to_string(),));@@ -442,14 +529,14 @@ whereself.repository.add_entity_property_option(access.entity_id(),- access.entity_type(),+ subject.storage_entity_type,property_definition_id,option_id,).await.map_err(anyhow::Error::from)?;- self.enqueue_property_upsert(access.entity_id(), access.entity_type())+ self.enqueue_property_upsert(access.entity_id(), subject.storage_entity_type).await;Ok(())@@ -470,17 +557,18 @@ whereproperty_definition_id: Uuid,option_id: Uuid,) -> Result<(), PropertiesErr> {+ let subject = self.resolve_subject(access).await?;self.repository.remove_entity_property_option(access.entity_id(),- access.entity_type(),+ subject.storage_entity_type,property_definition_id,option_id,).await.map_err(anyhow::Error::from)?;- self.enqueue_property_upsert(access.entity_id(), access.entity_type())+ self.enqueue_property_upsert(access.entity_id(), subject.storage_entity_type).await;Ok(())@@ -887,9 +975,10 @@ where&self,access: &ViewReceipt,) -> Result<Vec<EntityPropertyWithDefinition>, PropertiesErr> {+ let subject = self.resolve_subject(access).await?;let mut properties = self.repository- .get_entity_properties_with_definitions(access.entity_id(), access.entity_type())+ .get_entity_properties_with_definitions(access.entity_id(), subject.storage_entity_type).await.map_err(anyhow::Error::from)?;retain_caller_visible_tags(&mut properties, access.auth());@@ -901,8 +990,9 @@ where&self,access: &ViewReceipt,) -> Result<Option<Vec<EntityPropertyWithDefinition>>, PropertiesErr> {+ let subject = self.resolve_subject(access).await?;let entity_id = access.entity_id();- let properties = match access.entity_type() {+ let properties = match subject.storage_entity_type {entity_type @ (EntityType::Document | EntityType::Task) => self.repository.get_document_metadata(entity_id)@@ -943,18 +1033,21 @@ where&self,access: &[ViewReceipt],property_ids: Vec<Uuid>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr>- {- let entity_refs = access+ ) -> Result<HashMap<PropertyTargetKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr> {+ let subjects = self.resolve_subjects(access).await?;+ let entity_refs = subjects.iter()- .map(|receipt| {- EntityReference::new(receipt.entity_id().to_string(), receipt.entity_type())+ .map(|subject| {+ EntityReference::new(+ subject.canonical_key.entity_id.clone(),+ subject.storage_entity_type,+ )}).collect::<Vec<_>>();// An empty property_ids means "fetch all properties"; otherwise only// the requested definitions are returned.- let mut result = if property_ids.is_empty() {+ let mut internal_result = if property_ids.is_empty() {self.repository.get_entity_properties_batch(entity_refs).await@@ -966,24 +1059,19 @@ where.map_err(anyhow::Error::from)?};- // Filter each entity's properties by the auth of the receipt that- // granted access to that entity, so personal tags stay private.- let auth_by_key: HashMap<EntityPropertiesKey, &ViewReceipt> = access- .iter()- .map(|receipt| {- (- EntityPropertiesKey {- entity_id: receipt.entity_id().to_string(),- entity_type: receipt.entity_type(),- },- receipt,- )- })- .collect();- for (key, properties) in result.iter_mut() {- if let Some(receipt) = auth_by_key.get(key) {- retain_caller_visible_tags(properties, receipt.auth());+ // Return canonical keys while preserving the internal key only at the+ // repository boundary. Filter personal tags using the receipt that+ // granted access to each canonical entity.+ let mut result = HashMap::with_capacity(subjects.len());+ for (subject, receipt) in subjects.into_iter().zip(access) {+ if result.contains_key(&subject.canonical_key) {+ continue;}+ let mut properties = internal_result+ .remove(&subject.storage_key())+ .unwrap_or_default();+ retain_caller_visible_tags(&mut properties, receipt.auth());+ result.insert(subject.canonical_key, properties);}Ok(result)@@ -991,8 +1079,9 @@ where#[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]async fn delete_entity_properties(&self, access: &EditReceipt) -> Result<(), PropertiesErr> {+ let subject = self.resolve_subject(access).await?;let entity_reference =- EntityReference::new(access.entity_id().to_string(), access.entity_type());+ EntityReference::new(access.entity_id().to_string(), subject.storage_entity_type);Ok(self.repository.delete_entity_properties(&entity_reference)@@ -1004,12 +1093,16 @@ whereasync fn lookup_entity_property(&self,entity_property_id: Uuid,- ) -> Result<Option<EntityPropertyReference>, PropertiesErr> {+ ) -> Result<Option<PropertyTargetKey>, PropertiesErr> {Ok(self.repository.lookup_entity_property(entity_property_id).await- .map_err(anyhow::Error::from)?)+ .map_err(anyhow::Error::from)?+ .map(|property| PropertyTargetKey {+ entity_id: property.entity_id,+ entity_type: super::model::canonical_entity_type(property.entity_type),+ }))}#[tracing::instrument(skip(self, access), fields(entity_property_id = %entity_property_id, entity_id = %access.entity_id()), err)]@@ -1025,10 +1118,13 @@ where.map_err(anyhow::Error::from)?.ok_or(PropertiesErr::EntityPropertyNotFound)?;- // The receipt must prove access to the entity this property is- // actually attached to - a receipt for another entity is no proof.+ let subject = self.resolve_subject(access).await?;++ // The receipt must prove access to the canonical entity this property+ // is attached to. A stored Task assignment belongs to a Document+ // receipt after subtype resolution.if property_info.entity_id != access.entity_id()- || property_info.entity_type != access.entity_type()+ || property_info.entity_type != subject.storage_entity_type{tracing::warn!(receipt_entity_id = %access.entity_id(),diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rsindex 5e932c32f4..86a5dbb454 100644--- a/crates/properties/src/domain/service_impl/task_properties.rs+++ b/crates/properties/src/domain/service_impl/task_properties.rs@@ -2,6 +2,7 @@use std::collections::HashSet;+use entity_access::domain::models::EntityAccessAuth;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use models_properties::EntityType;@@ -11,7 +12,7 @@ use system_properties::SystemPropertyKey;use uuid::Uuid;use crate::domain::error::PropertiesErr;-use crate::domain::model::{EditReceipt, TaskAssignedNotification};+use crate::domain::model::{EditReceipt, PropertyAccessReceiptExt, TaskAssignedNotification};use crate::domain::ports::{NotificationService, PermissionService, PropertiesRepo};use crate::domain::service_impl::PropertiesServiceImpl;@@ -31,17 +32,24 @@ whereaccess: &EditReceipt,referenced_task_ids: &[Uuid],) -> Result<(), PropertiesErr> {+ let user_id = match access.auth() {+ EntityAccessAuth::Internal => return Ok(()),+ EntityAccessAuth::Authenticated(user_id) => user_id,+ EntityAccessAuth::Bot(_) | EntityAccessAuth::Unauthenticated => {+ return Err(PropertiesErr::PermissionDenied);+ }+ };if referenced_task_ids.is_empty() {return Ok(());}- let Some(user_id) = access.authenticated_user() else {- // Internal callers operate outside a user session and are trusted.- return Ok(());- };let permission_service = self.permission_service()?;for task_id in referenced_task_ids {permission_service- .mint_edit_receipt(user_id, &task_id.to_string(), EntityType::Task)+ .mint_edit_receipt(+ user_id,+ &task_id.to_string(),+ entity_access::domain::models::EntityType::Document,+ ).await.map_err(|_| PropertiesErr::PermissionDenied)?;}diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex 1ceb3d9834..671bf8171a 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -1,14 +1,18 @@//! Unit tests for PropertiesServiceImpl using mockall-generated repo.use super::service_impl::PropertiesServiceImpl;-use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt};+use crate::domain::model::{+ EditReceipt, PropertyAccessReceiptExt, ViewReceipt, canonical_entity_type,+};use crate::domain::{ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo},service::PropertiesService,};use anyhow::anyhow;+use document_sub_type::DocumentSubType;use entity_access::domain::models::{- BotId, EntityAccessAuth, EntityAccessReceipt, ViewAccessLevel,+ AccessLevel, BotId, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,+ EntityType as AccessEntityType, ViewAccessLevel,};use macro_user_id::user_id::MacroUserIdStr;use models_properties::{@@ -18,6 +22,7 @@ use models_properties::{property_value::PropertyValue,},};+use std::collections::HashMap;use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;@@ -42,19 +47,19 @@ fn caller_user_id() -> MacroUserIdStr<'static> {/// An edit receipt for the test caller, minted without an access check.fn edit_receipt(entity_id: &str, entity_type: EntityType) -> EditReceipt {- PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ EditReceipt::dangerously_assert_authenticated_user(caller_user_id(),entity_id,- entity_type,+ canonical_entity_type(entity_type),)}/// A view receipt for the test caller, minted without an access check.fn view_receipt(entity_id: &str, entity_type: EntityType) -> ViewReceipt {- PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ ViewReceipt::dangerously_assert_authenticated_user(caller_user_id(),entity_id,- entity_type,+ canonical_entity_type(entity_type),)}@@ -66,9 +71,7 @@ fn bot_receipt_has_no_authenticated_user_identity() {"document-1",entity_access::domain::models::EntityType::Document,);- let access =- PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, EntityType::Document)- .unwrap();+ let access = receipt;assert!(access.authenticated_user().is_none());assert!(matches!(access.auth(), EntityAccessAuth::Bot(id) if id.bot_id() == bot_id));@@ -80,7 +83,7 @@ fn create_mock_permission_service() -> MockPermissionService {perm_checker.expect_mint_edit_receipt().returning(|_, entity_id, entity_type| {- let receipt = PropertiesAccessReceipt::dangerously_assert_authenticated_user(+ let receipt = EditReceipt::dangerously_assert_authenticated_user(caller_user_id(),entity_id,entity_type,@@ -289,6 +292,52 @@ async fn test_link_parent_task_requires_edit_on_parent() {));}+#[tokio::test]+async fn test_link_parent_task_rejects_bot_and_unauthenticated_callers() {+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));+ let bot_access = EditReceipt::dangerously_assert_bot(+ bot_id.into_storage_id(),+ &task_id.to_string(),+ AccessEntityType::Document,+ );+ let unauthenticated_access = EditReceipt::try_new(+ EntityAccessAuth::Unauthenticated,+ Entity {+ entity_id: task_id.to_string(),+ entity_type: AccessEntityType::Document,+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ )+ .unwrap();++ for access in [bot_access, unauthenticated_access] {+ let mut repo = MockPropertiesRepo::new();+ repo.expect_link_parent_task().times(0);+ let service = PropertiesServiceImpl::new(+ repo,+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ );++ let err = service+ .handle_task_relationship_property(+ &access,+ SystemPropertyKey::PARENT_TASK_UUID,+ Some(parent_task_value(Uuid::from_u128(0xF00D))),+ )+ .await+ .unwrap_err();++ assert!(matches!(+ err,+ crate::domain::error::PropertiesErr::PermissionDenied+ ));+ }+}+#[tokio::test]async fn test_link_parent_task_error_propagates() {let mut repo = MockPropertiesRepo::new();@@ -1189,3 +1238,267 @@ async fn test_remove_entity_property_option_happy_path() {.await.unwrap();}++#[tokio::test]+async fn canonical_document_task_write_uses_task_storage_type() {+ let task_id = Uuid::from_u128(0xA11CE);+ let mut repo = MockPropertiesRepo::new();++ repo.expect_get_document_sub_types()+ .withf(move |ids| ids == [task_id])+ .returning(move |_| {+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })+ });+ repo.expect_get_property_definition().returning(|_| {+ Box::pin(async {+ Ok(Some(PropertyDefinition {+ id: SystemPropertyKey::STATUS_UUID,+ owner: models_properties::PropertyOwner::System,+ display_name: "Status".to_string(),+ data_type: models_properties::DataType::SelectString,+ is_multi_select: false,+ specific_entity_type: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: true,+ is_metadata: false,+ }))+ })+ });+ repo.expect_count_valid_property_options()+ .returning(|_, _| Box::pin(async { Ok(1) }));+ repo.expect_upsert_entity_property()+ .withf(move |entity_id, entity_type, property_id, _| {+ entity_id == task_id.to_string()+ && *entity_type == EntityType::Task+ && *property_id == SystemPropertyKey::STATUS_UUID+ })+ .returning(|entity_id, entity_type, property_definition_id, _| {+ let property = entity_property(entity_id, entity_type, property_definition_id);+ Box::pin(async move { Ok(property) })+ });++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );+ let receipt = EditReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ &task_id.to_string(),+ AccessEntityType::Document,+ );++ let property = service+ .set_entity_property(+ &receipt,+ SystemPropertyKey::STATUS_UUID,+ Some(+ models_properties::api::requests::SetPropertyValue::SelectOption {+ option_id: StatusOption::COMPLETED_UUID,+ },+ ),+ )+ .await+ .unwrap();++ assert_eq!(property.property.entity_type, EntityType::Task);+}++#[tokio::test]+async fn canonical_document_task_assignee_write_grants_permissions() {+ let task_id = Uuid::from_u128(0xA5516E);+ let assignee = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mut repo = MockPropertiesRepo::new();++ repo.expect_get_document_sub_types()+ .withf(move |ids| ids == [task_id])+ .returning(move |_| {+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })+ });+ repo.expect_get_property_definition().returning(|_| {+ Box::pin(async {+ Ok(Some(PropertyDefinition {+ id: SystemPropertyKey::ASSIGNEES_UUID,+ owner: models_properties::PropertyOwner::System,+ display_name: "Assignees".to_string(),+ data_type: models_properties::DataType::Entity,+ is_multi_select: true,+ specific_entity_type: Some(EntityType::User),+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: true,+ is_metadata: false,+ }))+ })+ });+ repo.expect_upsert_entity_property()+ .withf(move |entity_id, entity_type, property_id, _| {+ entity_id == task_id.to_string()+ && *entity_type == EntityType::Task+ && *property_id == SystemPropertyKey::ASSIGNEES_UUID+ })+ .returning(|entity_id, entity_type, property_definition_id, _| {+ let property = entity_property(entity_id, entity_type, property_definition_id);+ Box::pin(async move { Ok(property) })+ });++ let mut permission_service = MockPermissionService::new();+ let expected_assignee = assignee.clone();+ permission_service+ .expect_grant_permissions_to_task()+ .withf(move |user_ids, id| {+ user_ids == [expected_assignee.clone()] && id == task_id.to_string()+ })+ .returning(|_, _| Box::pin(async { Ok(()) }));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(permission_service),+ None::<MockNotificationService>,+ );+ let receipt = EditReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ &task_id.to_string(),+ AccessEntityType::Document,+ );++ service+ .set_entity_property(+ &receipt,+ SystemPropertyKey::ASSIGNEES_UUID,+ Some(+ models_properties::api::requests::SetPropertyValue::MultiEntityReference {+ references: vec![models_properties::EntityReference::new(+ assignee.as_ref(),+ EntityType::User,+ )],+ },+ ),+ )+ .await+ .unwrap();+}++#[tokio::test]+async fn canonical_document_task_read_uses_task_storage_type() {+ let task_id = Uuid::from_u128(0xBEEF);+ let property_id = Uuid::from_u128(0xCAFE);+ let mut repo = MockPropertiesRepo::new();++ repo.expect_get_document_sub_types()+ .withf(move |ids| ids == [task_id])+ .returning(move |_| {+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })+ });+ repo.expect_get_entity_property_value()+ .withf(move |entity_id, entity_type, id| {+ entity_id == task_id.to_string()+ && *entity_type == EntityType::Task+ && *id == property_id+ })+ .returning(|_, _, _| Box::pin(async { Ok(Some(PropertyValue::Str("value".into()))) }));++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );+ let receipt = ViewReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ &task_id.to_string(),+ AccessEntityType::Document,+ );++ assert_eq!(+ service+ .get_property_value(&receipt, property_id)+ .await+ .unwrap(),+ Some(PropertyValue::Str("value".into()))+ );+}++#[tokio::test]+async fn mixed_document_bulk_read_batches_subtypes_and_returns_canonical_keys() {+ let task_id = Uuid::from_u128(0x1001);+ let snippet_id = Uuid::from_u128(0x1002);+ let mut repo = MockPropertiesRepo::new();++ repo.expect_get_document_sub_types()+ .times(1)+ .withf(move |ids| ids.len() == 2 && ids.contains(&task_id) && ids.contains(&snippet_id))+ .returning(move |_| {+ Box::pin(async move {+ Ok(HashMap::from([+ (task_id, DocumentSubType::Task),+ (snippet_id, DocumentSubType::Snippet),+ ]))+ })+ });+ repo.expect_get_entity_properties_batch()+ .withf(move |references| {+ references.len() == 2+ && references.iter().any(|reference| {+ reference.entity_id == task_id.to_string()+ && reference.entity_type == EntityType::Task+ })+ && references.iter().any(|reference| {+ reference.entity_id == snippet_id.to_string()+ && reference.entity_type == EntityType::Document+ })+ })+ .returning(|references| {+ Box::pin(async move {+ Ok(references+ .iter()+ .map(|reference| {+ (+ crate::domain::model::EntityPropertiesKey::from(reference),+ Vec::new(),+ )+ })+ .collect())+ })+ });++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );+ let receipts = [+ ViewReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ &task_id.to_string(),+ AccessEntityType::Document,+ ),+ ViewReceipt::dangerously_assert_authenticated_user(+ caller_user_id(),+ &snippet_id.to_string(),+ AccessEntityType::Document,+ ),+ ];++ let result = service+ .get_bulk_entity_properties(&receipts, Vec::new())+ .await+ .unwrap();++ assert!(+ result+ .keys()+ .all(|key| key.entity_type == AccessEntityType::Document)+ );+ assert!(+ result.contains_key(&crate::domain::model::PropertyTargetKey {+ entity_id: task_id.to_string(),+ entity_type: AccessEntityType::Document,+ })+ );+ assert!(+ result.contains_key(&crate::domain::model::PropertyTargetKey {+ entity_id: snippet_id.to_string(),+ entity_type: AccessEntityType::Document,+ })+ );+}diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rsindex bb8129c0f4..4ec1d94db8 100644--- a/crates/properties/src/inbound/axum_router/entities.rs+++ b/crates/properties/src/inbound/axum_router/entities.rs@@ -16,18 +16,18 @@ use axum::{use entity_access::domain::models::EditAccessLevel;use entity_access::domain::ports::EntityAccessService;use model::user::axum_extractor::MacroUserExtractor;-use models_properties::api::SetPropertyValue;+use models_properties::api::{PropertyTargetEntityType, PropertyTargetReference, SetPropertyValue};use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;-use models_properties::{EntityReference, EntityType};use serde::{Deserialize, Serialize};use thiserror::Error;use utoipa::ToSchema;use uuid::Uuid;use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};-use super::extract::{mint_authenticated_receipt, mint_view_receipt};+use super::extract::{mint_authenticated_receipt, mint_view_receipt, target_entity_type};use super::{PropertiesRouterState, properties_err_status};use crate::domain::error::PropertiesErr;+use crate::domain::model::PropertyAccessReceiptExt;use crate::domain::service::PropertiesService;// Re-export EntityQueryParams from models_properties for convenience@@ -52,7 +52,7 @@ pub struct SetEntityPropertyRequest {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct BulkEntityPropertiesRequest {/// Array of entity references (entity_id and entity_type pairs)- pub entities: Vec<EntityReference>,+ pub entities: Vec<PropertyTargetReference>,/// Optional: only return properties with these definition IDs. If empty, returns all.#[serde(default)]pub property_ids: Vec<Uuid>,@@ -97,7 +97,7 @@ impl IntoResponse for GetEntityPropertiesErr {get,path = "/properties/entities/{entity_type}/{entity_id}",params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),("entity_id" = String, Path, description = "Entity ID"),("include_metadata" = Option<bool>, Query, description = "Whether to include property metadata (default: false)")),@@ -259,7 +259,7 @@ pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessSerstate.entity_access_service.as_ref(),Some(&user),&entity_ref.entity_id,- entity_ref.entity_type,+ target_entity_type(entity_ref.entity_type),).await{@@ -337,7 +337,7 @@ impl IntoResponse for SetEntityPropertyErr {put,path = "/properties/entities/{entity_type}/{entity_id}/{property_id}",params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),("entity_id" = String, Path, description = "Entity ID"),("property_id" = Uuid, Path, description = "Property ID")),@@ -353,7 +353,7 @@ impl IntoResponse for SetEntityPropertyErr {)]#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, entity_type = ?access.0.entity_type(), has_value = request.value.is_some()), err)]pub async fn set_entity_property<S: PropertiesService, A: EntityAccessService>(- Path((_entity_type, _entity_id, property_uuid)): Path<(EntityType, String, Uuid)>,+ Path((_entity_type, _entity_id, property_uuid)): Path<(PropertyTargetEntityType, String, Uuid)>,State(state): State<PropertiesRouterState<S, A>>,access: EditReceiptExtractor,Json(request): Json<SetEntityPropertyRequest>,@@ -404,7 +404,7 @@ impl IntoResponse for EntityPropertyOptionErr {post,path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),("entity_id" = String, Path, description = "Entity ID"),("property_id" = Uuid, Path, description = "Property ID"),("option_id" = Uuid, Path, description = "Option ID to add")@@ -420,7 +420,7 @@ impl IntoResponse for EntityPropertyOptionErr {#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessService>(Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(- EntityType,+ PropertyTargetEntityType,String,Uuid,Uuid,@@ -447,7 +447,7 @@ pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessSerdelete,path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),("entity_id" = String, Path, description = "Entity ID"),("property_id" = Uuid, Path, description = "Property ID"),("option_id" = Uuid, Path, description = "Option ID to remove")@@ -462,7 +462,7 @@ pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessSer#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]pub async fn remove_entity_property_option<S: PropertiesService, A: EntityAccessService>(Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(- EntityType,+ PropertyTargetEntityType,String,Uuid,Uuid,diff --git a/crates/properties/src/inbound/axum_router/extract.rs b/crates/properties/src/inbound/axum_router/extract.rsindex 8457acab28..733c4f6af2 100644--- a/crates/properties/src/inbound/axum_router/extract.rs+++ b/crates/properties/src/inbound/axum_router/extract.rs@@ -14,22 +14,22 @@ use axum::{};use entity_access::domain::models::{AccessLevel, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,- RequiredPermission, ViewAccessLevel,+ EntityType as AccessEntityType, RequiredPermission, ViewAccessLevel,};use entity_access::domain::ports::EntityAccessService;use macro_user_id::user_id::MacroUserIdStr;use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};-use models_properties::EntityType;+use models_properties::api::PropertyTargetEntityType;use super::{PropertiesRouterState, properties_err_status};use crate::domain::error::PropertiesErr;-use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt, access_entity_type};+use crate::domain::model::{EditReceipt, ViewReceipt};use crate::domain::service::PropertiesService;/// Path parameters for entity-scoped properties routes.#[derive(serde::Deserialize)]struct EntityPathParams {- entity_type: EntityType,+ entity_type: PropertyTargetEntityType,entity_id: String,}@@ -67,35 +67,43 @@ impl IntoResponse for ReceiptRejection {}}+/// Convert the target-only transport enum to a canonical access entity type.+pub(crate) fn target_entity_type(entity_type: PropertyTargetEntityType) -> AccessEntityType {+ match entity_type {+ PropertyTargetEntityType::CallRecord => AccessEntityType::Call,+ PropertyTargetEntityType::Channel => AccessEntityType::Channel,+ PropertyTargetEntityType::Chat => AccessEntityType::Chat,+ PropertyTargetEntityType::Company => AccessEntityType::CrmCompany,+ PropertyTargetEntityType::Document => AccessEntityType::Document,+ PropertyTargetEntityType::Project => AccessEntityType::Project,+ PropertyTargetEntityType::Thread => AccessEntityType::EmailThread,+ PropertyTargetEntityType::User => AccessEntityType::User,+ }+}+pub(crate) async fn mint_authenticated_receipt<T, A>(entity_access_service: &A,user_id: &MacroUserIdStr<'_>,entity_id: &str,- entity_type: EntityType,-) -> Result<PropertiesAccessReceipt<T>, PropertiesErr>+ entity_type: AccessEntityType,+) -> Result<EntityAccessReceipt<T>, PropertiesErr>whereT: RequiredPermission,A: EntityAccessService,{let receipt = entity_access_service- .generate_entity_access_receipt::<T>(- user_id,- None,- entity_id,- access_entity_type(entity_type),- )+ .generate_entity_access_receipt::<T>(user_id, None, entity_id, entity_type).await.map_err(|_| PropertiesErr::PermissionDenied)?;- PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, entity_type)- .map_err(|_| PropertiesErr::PermissionDenied)+ Ok(receipt)}pub(crate) async fn mint_view_receipt<A>(entity_access_service: &A,user_id: Option<&MacroUserIdStr<'_>>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> Result<ViewReceipt, PropertiesErr>whereA: EntityAccessService,@@ -110,23 +118,21 @@ where.await;}- let access_entity_type = access_entity_type(entity_type);let access_level = entity_access_service- .check_public_access(entity_id, access_entity_type, AccessLevel::View)+ .check_public_access(entity_id, entity_type, AccessLevel::View).await.map_err(|_| PropertiesErr::PermissionDenied)?;let receipt = EntityAccessReceipt::try_new(EntityAccessAuth::Unauthenticated,Entity {entity_id: entity_id.to_string(),- entity_type: access_entity_type,+ entity_type,},EntityPermission::AccessLevel { access_level },).map_err(|_| PropertiesErr::PermissionDenied)?;- PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, entity_type)- .map_err(|_| PropertiesErr::PermissionDenied)+ Ok(receipt)}async fn entity_path_params(parts: &mut Parts) -> Result<EntityPathParams, ReceiptRejection> {@@ -166,7 +172,7 @@ wherestate.entity_access_service.as_ref(),user.as_ref(),¶ms.entity_id,- params.entity_type,+ target_entity_type(params.entity_type),).await?;@@ -204,7 +210,7 @@ wherestate.entity_access_service.as_ref(),&user,¶ms.entity_id,- params.entity_type,+ target_entity_type(params.entity_type),).await?;diff --git a/crates/properties/src/inbound/toolset/get_entity_properties.rs b/crates/properties/src/inbound/toolset/get_entity_properties.rsindex 7396a37141..f4b034d310 100644--- a/crates/properties/src/inbound/toolset/get_entity_properties.rs+++ b/crates/properties/src/inbound/toolset/get_entity_properties.rs@@ -1,8 +1,6 @@//! GetEntityProperties tool for reading properties attached to an entity.-use crate::domain::model::{- EntityPropertyInfo, PropertiesAccessReceipt, PropertyOptionInfo, access_entity_type,-};+use crate::domain::model::{EntityPropertyInfo, PropertyOptionInfo};use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;@@ -49,17 +47,46 @@ impl From<ToolEntityType> for EntityType {}}+/// Canonical entity type accepted when an AI tool targets an entity's properties.+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum ToolPropertyTargetEntityType {+ Document,+ Project,+ Chat,+ Thread,+ Channel,+ Call,+ User,+ Company,+}++impl From<ToolPropertyTargetEntityType> for model_entity::EntityType {+ fn from(value: ToolPropertyTargetEntityType) -> Self {+ match value {+ ToolPropertyTargetEntityType::Document => Self::Document,+ ToolPropertyTargetEntityType::Project => Self::Project,+ ToolPropertyTargetEntityType::Chat => Self::Chat,+ ToolPropertyTargetEntityType::Thread => Self::EmailThread,+ ToolPropertyTargetEntityType::Channel => Self::Channel,+ ToolPropertyTargetEntityType::Call => Self::Call,+ ToolPropertyTargetEntityType::User => Self::User,+ ToolPropertyTargetEntityType::Company => Self::CrmCompany,+ }+ }+}+#[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. 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."+ description = "Get all properties attached to an entity (document, project, CRM company, etc.). Tasks are targeted as entity_type=document. 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 task documents, 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.")]pub entity_id: String,#[schemars(description = "The type of entity.")]- pub entity_type: ToolEntityType,+ pub entity_type: ToolPropertyTargetEntityType,}/// A property option in the tool response.@@ -128,7 +155,7 @@ where) -> ToolResult<Self::Output> {tracing::info!(params=?self, "Get entity properties");- let entity_type = EntityType::from(self.entity_type);+ let entity_type = model_entity::EntityType::from(self.entity_type);// Prove the requesting user can view the entity before reading anything.let entity_access_receipt = service_context@@ -137,25 +164,16 @@ where&request_context.user_id,None,&self.entity_id,- access_entity_type(entity_type),+ entity_type,).await.map_err(|e| ToolCallError {description: "You do not have access to this entity".to_string(),internal_error: e.into(),})?;- let access = PropertiesAccessReceipt::try_from_entity_access_receipt(- entity_access_receipt,- entity_type,- )- .map_err(|e| ToolCallError {- description: "Unable to validate entity access".to_string(),- internal_error: e.into(),- })?;-let props = service_context.service- .get_entity_properties(&access)+ .get_entity_properties(&entity_access_receipt).await.map_err(|e| ToolCallError {description: format!("Failed to get entity properties: {e}"),diff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rsindex 1d501e2fb4..c1bca883cd 100644--- a/crates/properties/src/inbound/toolset/set_entity_property.rs+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs@@ -1,6 +1,5 @@//! SetEntityProperty tool for updating property values on entities.-use crate::domain::model::{PropertiesAccessReceipt, access_entity_type};use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;@@ -15,7 +14,7 @@ use serde::{Deserialize, Serialize};use uuid::Uuid;use super::PropertiesToolContext;-use super::get_entity_properties::ToolEntityType;+use super::get_entity_properties::{ToolEntityType, ToolPropertyTargetEntityType};#[derive(Debug, Clone, Deserialize, JsonSchema)]#[serde(rename_all = "camelCase")]@@ -39,7 +38,7 @@ pub struct ToolEntityRef {#[derive(Debug, Deserialize, JsonSchema)]#[schemars(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.+ description = "Set or update a property value on an entity (document, project, etc.). Tasks are targeted as entity_type='document'. 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.@@ -66,7 +65,7 @@ pub struct SetEntityProperty {pub entity_id: String,#[schemars(description = "The type of entity.")]- pub entity_type: ToolEntityType,+ pub entity_type: ToolPropertyTargetEntityType,#[schemars(description = "The property definition ID. Get this from GetEntityProperties results."@@ -215,7 +214,7 @@ where) -> ToolResult<Self::Output> {tracing::info!("Set entity property");- let entity_type = EntityType::from(self.entity_type);+ let entity_type = model_entity::EntityType::from(self.entity_type);let set_value = self.to_set_property_value();// Prove the requesting user can edit the entity before writing anything.@@ -225,22 +224,13 @@ where&request_context.user_id,None,&self.entity_id,- access_entity_type(entity_type),+ entity_type,).await.map_err(|e| ToolCallError {description: "You do not have edit access to this entity".to_string(),internal_error: e.into(),})?;- let access = PropertiesAccessReceipt::try_from_entity_access_receipt(- entity_access_receipt,- entity_type,- )- .map_err(|e| ToolCallError {- description: "Unable to validate entity access".to_string(),- internal_error: e.into(),- })?;-// 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();@@ -258,7 +248,11 @@ wherefor option_id in add_option_ids {service_context.service- .add_entity_property_option(&access, self.property_definition_id, *option_id)+ .add_entity_property_option(+ &entity_access_receipt,+ self.property_definition_id,+ *option_id,+ ).await.map_err(|e| ToolCallError {description: format!("Failed to add option {option_id}: {e}"),@@ -268,7 +262,11 @@ wherefor option_id in remove_option_ids {service_context.service- .remove_entity_property_option(&access, self.property_definition_id, *option_id)+ .remove_entity_property_option(+ &entity_access_receipt,+ self.property_definition_id,+ *option_id,+ ).await.map_err(|e| ToolCallError {description: format!("Failed to remove option {option_id}: {e}"),@@ -284,7 +282,11 @@ whereservice_context.service- .set_entity_property(&access, self.property_definition_id, set_value)+ .set_entity_property(+ &entity_access_receipt,+ self.property_definition_id,+ set_value,+ ).await.map_err(|e| ToolCallError {description: format!("Failed to set property: {e}"),diff --git a/crates/properties/src/lib.rs b/crates/properties/src/lib.rsindex 99311cd334..468e896301 100644--- a/crates/properties/src/lib.rs+++ b/crates/properties/src/lib.rs@@ -18,8 +18,8 @@ pub mod outbound;pub use domain::error::PropertiesErr;pub use domain::model::{- EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertiesAccessReceipt,- PropertyOptionInfo, ViewReceipt, access_entity_type,+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertyAccessReceiptExt,+ PropertyOptionInfo, PropertyTargetKey, ViewReceipt, canonical_entity_type,};pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer,diff --git a/crates/properties/src/outbound.rs b/crates/properties/src/outbound.rsindex d53e085bb7..720bce5955 100644--- a/crates/properties/src/outbound.rs+++ b/crates/properties/src/outbound.rs@@ -6,6 +6,8 @@ pub mod entity_properties_get_query;mod entity_properties_values_test;pub mod entity_property_queries;pub mod metadata_queries;+#[cfg(test)]+mod metadata_queries_test;pub mod notification_service;#[cfg(test)]mod options_test;diff --git a/crates/properties/src/outbound/metadata_queries.rs b/crates/properties/src/outbound/metadata_queries.rsindex 0c81bc286b..108eaa8811 100644--- a/crates/properties/src/outbound/metadata_queries.rs+++ b/crates/properties/src/outbound/metadata_queries.rs@@ -3,12 +3,45 @@//! These read tables owned by other domains; the properties domain surfaces//! them as read-only metadata properties.+use document_sub_type::DocumentSubType;use models_properties::service::document_metadata::DocumentMetadata;use models_properties::service::project_metadata::ProjectMetadata;use models_properties::service::thread_metadata::ThreadMetadata;use sqlx::{Pool, Postgres};+use std::collections::HashMap;use uuid::Uuid;+/// Resolve document subtypes for a batch of canonical document IDs.+#[tracing::instrument(skip(pool, document_ids), fields(document_count = document_ids.len()), err)]+pub async fn get_document_sub_types(+ pool: &Pool<Postgres>,+ document_ids: &[Uuid],+) -> anyhow::Result<HashMap<Uuid, DocumentSubType>> {+ if document_ids.is_empty() {+ return Ok(HashMap::new());+ }++ // Document ids are stored as text in MacroDB. Keep the port strongly+ // typed and convert only in this outbound adapter.+ let document_ids = document_ids.iter().map(Uuid::to_string).collect::<Vec<_>>();+ let rows = sqlx::query!(+ r#"+ SELECT+ document_id,+ sub_type as "sub_type: DocumentSubType"+ FROM document_sub_type+ WHERE document_id = ANY($1)+ "#,+ &document_ids+ )+ .fetch_all(pool)+ .await?;++ rows.into_iter()+ .map(|row| Ok((Uuid::parse_str(&row.document_id)?, row.sub_type)))+ .collect()+}+/// Get document metadata by document ID from macrodb#[tracing::instrument(skip(pool), err)]pub async fn get_document_metadata(diff --git a/crates/properties/src/outbound/metadata_queries_test.rs b/crates/properties/src/outbound/metadata_queries_test.rsnew file mode 100644index 0000000000..29544c6eb9--- /dev/null+++ b/crates/properties/src/outbound/metadata_queries_test.rs@@ -0,0 +1,60 @@+//! Integration tests for document metadata fact queries.++use super::metadata_queries;+use document_sub_type::DocumentSubType;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn document_sub_types_resolve_mixed_batch(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let task_id = Uuid::from_u128(0xD001);+ let snippet_id = Uuid::from_u128(0xD002);+ let document_id = Uuid::from_u128(0xD003);+ let missing_id = Uuid::from_u128(0xD004);++ for (id, name) in [+ (task_id, "Task"),+ (snippet_id, "Snippet"),+ (document_id, "Document"),+ ] {+ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, owner)+ VALUES ($1, $2, 'macro|[email protected]')+ "#,+ id.to_string(),+ name,+ )+ .execute(&pool)+ .await?;+ }++ sqlx::query!(+ r#"+ INSERT INTO document_sub_type (document_id, sub_type)+ VALUES ($1, 'task'), ($2, 'snippet')+ "#,+ task_id.to_string(),+ snippet_id.to_string(),+ )+ .execute(&pool)+ .await?;++ let result = metadata_queries::get_document_sub_types(+ &pool,+ &[task_id, snippet_id, document_id, task_id, missing_id],+ )+ .await?;++ assert_eq!(result.len(), 2);+ assert_eq!(result.get(&task_id), Some(&DocumentSubType::Task));+ assert_eq!(result.get(&snippet_id), Some(&DocumentSubType::Snippet));+ assert!(!result.contains_key(&document_id));+ assert!(!result.contains_key(&missing_id));++ Ok(())+}diff --git a/crates/properties/src/outbound/permission_service.rs b/crates/properties/src/outbound/permission_service.rsindex 2b0cda415f..27477c5b8e 100644--- a/crates/properties/src/outbound/permission_service.rs+++ b/crates/properties/src/outbound/permission_service.rs@@ -2,17 +2,20 @@use std::sync::Arc;-use entity_access::domain::models::{AccessError, EntityAccessAuth};+use entity_access::domain::models::{+ AccessError, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,+ EntityType as AccessEntityType,+};use entity_access::domain::ports::EntityAccessService;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use models_permissions::share_permission::access_level::AccessLevel;-use models_properties::EntityType;+use models_properties::EntityType as StorageEntityType;use sqlx::{Pool, Postgres};use uuid::Uuid;use super::permission_queries;-use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt, access_entity_type};+use crate::domain::model::{EditReceipt, ViewReceipt};use crate::domain::ports::PermissionService;/// Permission service implementation using database.@@ -36,19 +39,17 @@ impl<Svc: EntityAccessService> PermissionServiceImpl<Svc> {&self,user_id: Option<&MacroUserIdStr<'_>>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> anyhow::Result<Option<AccessLevel>> {- if entity_type == EntityType::User {+ if entity_type == AccessEntityType::User {tracing::warn!("property operations not supported for this entity type");anyhow::bail!("Unsupported entity type");}- let model_entity_type = access_entity_type(entity_type);-let user_id_ref = user_id.map(std::ops::Deref::deref);let access_level = self.entity_access_service- .get_access_level(user_id_ref, entity_id, model_entity_type)+ .get_access_level(user_id_ref, entity_id, entity_type).await.map_err(|e: AccessError| {tracing::error!(@@ -61,7 +62,7 @@ impl<Svc: EntityAccessService> PermissionServiceImpl<Svc> {// Fallback for threads: check ownership via link_id if no permission records exist.// This handles owned threads where EmailThreadPermission/UserItemAccess were never created.if access_level.is_none()- && entity_type == EntityType::Thread+ && entity_type == AccessEntityType::EmailThread&& let Some(user_id) = user_id&& let Ok(thread_id) = Uuid::parse_str(entity_id){@@ -93,6 +94,36 @@ fn caller_auth(user_id: Option<&MacroUserIdStr<'_>>) -> EntityAccessAuth {}}+fn storage_entity_type(entity_type: AccessEntityType) -> anyhow::Result<StorageEntityType> {+ Ok(match entity_type {+ AccessEntityType::Document => StorageEntityType::Document,+ AccessEntityType::Call => StorageEntityType::CallRecord,+ AccessEntityType::Chat => StorageEntityType::Chat,+ AccessEntityType::Project => StorageEntityType::Project,+ AccessEntityType::EmailThread => StorageEntityType::Thread,+ AccessEntityType::Channel => StorageEntityType::Channel,+ AccessEntityType::CrmCompany => StorageEntityType::Company,+ AccessEntityType::User => StorageEntityType::User,+ _ => anyhow::bail!("Unsupported property target type"),+ })+}++fn access_receipt<T: entity_access::domain::models::RequiredPermission>(+ auth: EntityAccessAuth,+ entity_id: &str,+ entity_type: AccessEntityType,+ access_level: AccessLevel,+) -> Result<EntityAccessReceipt<T>, AccessError> {+ EntityAccessReceipt::try_new(+ auth,+ Entity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ EntityPermission::AccessLevel { access_level },+ )+}+impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc> {type Err = anyhow::Error;@@ -101,24 +132,27 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>&self,user_id: Option<&'a MacroUserIdStr<'a>>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> Result<ViewReceipt, Self::Err> {// Check if entity is deleted: the owner always has access, and deleted// entities are only visible to their owner.match entity_type {- EntityType::CallRecord- | EntityType::Channel- | EntityType::Company- | EntityType::User- | EntityType::Thread => {}+ AccessEntityType::Call+ | AccessEntityType::Channel+ | AccessEntityType::CrmCompany+ | AccessEntityType::User+ | AccessEntityType::EmailThread => {}_ => {- let (owner, deleted) =- permission_queries::get_owner_and_deleted(&self.db, entity_id, entity_type)- .await?;+ let (owner, deleted) = permission_queries::get_owner_and_deleted(+ &self.db,+ entity_id,+ storage_entity_type(entity_type)?,+ )+ .await?;// If you are the owner fast returnif user_id.is_some_and(|u| owner == u.as_ref()) {- return Ok(PropertiesAccessReceipt::try_from_permission(+ return Ok(access_receipt(caller_auth(user_id),entity_id,entity_type,@@ -138,7 +172,7 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>.await?{// Any access level is sufficient for viewing- Some(access_level) => Ok(PropertiesAccessReceipt::try_from_permission(+ Some(access_level) => Ok(access_receipt(caller_auth(user_id),entity_id,entity_type,@@ -153,20 +187,18 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>&self,user_id: &MacroUserIdStr<'a>,entity_id: &str,- entity_type: EntityType,+ entity_type: AccessEntityType,) -> Result<EditReceipt, Self::Err> {match self.get_access_level(Some(user_id), entity_id, entity_type).await?{- Some(access_level @ (AccessLevel::Edit | AccessLevel::Owner)) => {- Ok(PropertiesAccessReceipt::try_from_permission(- caller_auth(Some(user_id)),- entity_id,- entity_type,- access_level,- )?)- }+ Some(access_level @ (AccessLevel::Edit | AccessLevel::Owner)) => Ok(access_receipt(+ caller_auth(Some(user_id)),+ entity_id,+ entity_type,+ access_level,+ )?),Some(_) | None => anyhow::bail!("Access denied"),}}diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rsindex d0d67b621a..b1f8fcec8d 100644--- a/crates/properties/src/outbound/properties_pg_repo.rs+++ b/crates/properties/src/outbound/properties_pg_repo.rs@@ -1,5 +1,6 @@//! PostgreSQL implementation for properties repository.+use document_sub_type::DocumentSubType;use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;@@ -419,6 +420,14 @@ impl PropertiesRepo for PropertiesPgRepo {entity_property_queries::delete_entity_properties(&self.pool, entity_reference).await}+ #[tracing::instrument(skip(self, document_ids), fields(document_count = document_ids.len()), err)]+ async fn get_document_sub_types(+ &self,+ document_ids: &[Uuid],+ ) -> Result<HashMap<Uuid, DocumentSubType>, Self::Err> {+ metadata_queries::get_document_sub_types(&self.pool, document_ids).await+ }+#[tracing::instrument(skip(self), err)]async fn get_document_metadata(&self,diff --git a/docs/PROPERTY_TARGET_ENTITY_TYPE_PLAN.md b/docs/PROPERTY_TARGET_ENTITY_TYPE_PLAN.mdnew file mode 100644index 0000000000..8fab23a8a8--- /dev/null+++ b/docs/PROPERTY_TARGET_ENTITY_TYPE_PLAN.md@@ -0,0 +1,408 @@+# Canonical Property Target Entity Types++## Status++Implementation plan. No code or schema changes have been made as part of this document.++## Problem++Tasks are documents with `document_sub_type = TASK` in the canonical entity and access-control systems, but the properties subsystem currently exposes a separate `TASK` target type.++That creates two property namespaces for the same entity id:++```text+(DOCUMENT, <document-id>)+(TASK, <document-id>)+```++Today a task property mutation from the web client sends `entityType: TASK`, so the properties service writes the assignment under the internal `TASK` namespace. A fresh GraphQL Soup query represents the same task as a `GraphqlSoupDocument`, mints document access, and currently loads properties under `DOCUMENT`. The mutation response is therefore correct and can update the normalized cache immediately, but a fresh read cannot find the row written under `TASK`.++The split is visible in `crates/properties/src/domain/model.rs`:++- `access_entity_type(EntityType::Task)` collapses to `entity_access::EntityType::Document`.+- `PropertiesAccessReceipt` then preserves the original properties `EntityType::Task` specifically so repositories can continue using the separate storage namespace.++The desired boundary is:++```text+external target: DOCUMENT + entity id+ |+ v+inbound adapter mints EntityAccessReceipt<Document>+ |+ v+properties domain resolves document subtype+ |+ +-- regular document/snippet -> internal DOCUMENT+ `-- task -> internal TASK+```++`TASK` remains an internal properties storage type for now. There is no data migration in this plan.++## Decisions++1. **Entity property targets use canonical entity types externally.** A task is targeted as `DOCUMENT`; task-ness comes from document subtype.+2. **The properties domain receives regular typed entity-access receipts.** Clients never provide receipts; inbound adapters mint them.+3. **Task/document classification is domain policy.** Inbound GraphQL, REST, and tool adapters must not inspect document subtype or choose the internal storage namespace.+4. **Document subtype lookup is an outbound fact.** Add a repository/port capability that can resolve document subtypes in batches; the domain maps those facts to internal `models_properties::EntityType::{Document, Task}`.+5. **Keep `models_properties::EntityType::Task` internally.** Existing rows, task initialization, task relationships, grouping, indexing, notifications, and permission side effects continue using it.+6. **Separate target types from referenced-entity types.** The current `GraphqlPropertyEntityType`/generated `EntityType` is used both for the entity receiving a property and for entities stored inside property values. Introduce a target-only transport type without `TASK`. Keep the existing internal/reference type in this iteration so Parent Task/Subtasks and property-definition constraints are not redesigned accidentally.+7. **Use one resolution path for reads and writes.** Fixing only `set_entity_property` would recreate the mismatch in the opposite direction.+8. **Do not add `Task` to `model_entity::EntityType`.** Tasks remain canonical documents.+9. **Do not run or create a database migration for this work.** Existing `TASK` rows remain authoritative for task documents.+10. **Prefer strong domain types over stringly typed interfaces.** Repository and service contracts should use types such as `Uuid` for UUID-backed identifiers rather than `String`, converting only at transport boundaries when necessary.++## Goals++- A frontend task property write sends `DOCUMENT`, not `TASK`.+- GraphQL, REST, tools, and internal user-facing property entrypoints mint a normal document access receipt.+- The properties domain resolves a task document to the internal `TASK` namespace before every repository operation.+- A mutation followed by a fresh, network-only GraphQL Soup query returns the persisted assignee/status/etc.+- Task assignee permission grants and notifications continue to run.+- Existing task property rows require no rewrite.+- Bulk property reads classify documents in one batched lookup rather than introducing an N+1 query.++## Non-goals++- Removing `TASK` from PostgreSQL's `property_entity_type` enum.+- Migrating existing `TASK` property rows to `DOCUMENT`.+- Changing how tasks are rendered (`TaskEntity` remains a document with `subType.type === "task"`).+- Redesigning task-to-task entity-reference values or Parent Task/Subtasks in the first iteration.+- Changing GraphQL normalized-cache identity. `GraphqlProperty.id` remains the assignment id, and tasks remain `GraphqlSoupDocument` objects.++## Proposed domain design++### 1. Canonical target receipt++Replace the original-type-preserving role of `PropertiesAccessReceipt<T>` for entity-scoped service operations with the regular:++```rust+EntityAccessReceipt<ViewAccessLevel>+EntityAccessReceipt<EditAccessLevel>+```++The receipt's entity type is canonical (`Document`, `EmailThread`, `Call`, `CrmCompany`, etc.). It proves authorization but does not encode the properties storage namespace.++If removing `PropertiesAccessReceipt` in one change is too disruptive, first reduce it to a transparent supported-target wrapper around `EntityAccessReceipt<T>` with no caller-provided properties `EntityType`. Do not let callers supply or preserve `Task` on the wrapper. The end-state service contract must not require a caller to choose Task versus Document.++### 2. Resolved internal subject++Add a private/domain model such as:++```rust+struct ResolvedPropertySubject {+ canonical_entity: model_entity::OwnedEntity,+ storage_entity_type: models_properties::EntityType,+}+```++The service resolves receipts as follows:++| Receipt entity type | Internal properties type |+| --- | --- |+| `Document` with task subtype | `Task` |+| `Document` without task subtype (including snippets) | `Document` |+| `EmailThread` | `Thread` |+| `Call` | `CallRecord` |+| `CrmCompany` | `Company` |+| `Chat`, `Channel`, `Project`, `User` | corresponding internal type |+| unsupported canonical types | domain validation error |++Keep both the canonical key and internal key while processing a request. The canonical key is used at service/adapter boundaries; only repository calls and task-specific domain behavior use the internal key.++### 3. Batched document subtype lookup++Extend the properties outbound port with a fact-oriented, batch API, for example:++```rust+fn get_document_sub_types(+ &self,+ document_ids: &[Uuid],+) -> impl Future<+ Output = Result<HashMap<Uuid, Option<DocumentSubType>>, Self::Err>+> + Send;+```++Implementation requirements:++- Keep UUID-backed identifiers strongly typed as `Uuid` throughout domain and repository interfaces; do not weaken them to `String` for convenience.+- Query `Document`/`document_sub_type` for all supplied document ids in one SQLx query.+- Return `Some(Task)` only for task documents; `None` means a regular document/no subtype. Snippets resolve to internal `Document`.+- Deduplicate input ids.+- Define and test missing-document behavior. Recommended compatibility behavior is to resolve a missing subtype row as `Document`; authorization and the eventual repository operation remain responsible for their existing not-found/deleted behavior.+- Use SQLx compile-time checked macros.+- Do not put the Task-versus-Document policy in the SQL adapter; return subtype facts and map them in the domain service.++The existing properties repository already contains document metadata lookup, so this capability may live on `PropertiesRepo` without adding another service generic. If a dedicated resolver port is introduced instead, wire it only in composition roots and keep the domain independent of its concrete database implementation.++### 4. Canonical bulk result keys++`get_bulk_entity_properties` currently returns maps keyed by `EntityPropertiesKey`, whose type can be internal `Task`. That prevents a caller holding only a canonical `Document` receipt from finding the result.++Change the service boundary to return canonical keys. Options, in preferred order:++1. A map keyed by a new canonical `PropertyTargetKey` containing `model_entity::EntityType` and id.+2. A map keyed by `model_entity::OwnedEntity`.+3. A vector aligned with the input receipts, if that is clearer for all callers.++Keep `EntityPropertiesKey` with `models_properties::EntityType::Task` inside the repository boundary. During bulk reads, retain a canonical-to-internal mapping, query with internal keys, then map results back to canonical keys before returning.++## Transport contracts++### GraphQL++Create a target-only GraphQL enum, e.g. `GraphqlPropertyTargetEntityType`, which excludes `TASK` and maps to canonical entity-access types. Use it only for `SetEntityPropertyInput.entity_type` and any other entity-scoped property target input.++Do not reuse or remove `GraphqlPropertyEntityType` yet; it is also used for:++- `GraphqlEntityReferenceInput.entity_type`+- `GraphqlProperty.specific_entity_type`+- property filter inputs++Those uses may still need a Task value and are outside this plan's first iteration.++Change the GraphQL mutation flow to:++1. Parse canonical target type and entity id.+2. Mint `EntityAccessReceipt<EditAccessLevel>` at the inbound boundary.+3. Pass the receipt, definition id, and value to `PropertiesService::set_entity_property`.+4. Let the service resolve internal Task/Document storage type.++Change the GraphQL property reader similarly:++1. Keep `GraphqlSoupDocument`/`model_entity::EntityType::Document` for tasks.+2. Mint canonical view receipts.+3. Call the bulk properties service.+4. Consume results under canonical Document keys.++Do not add task-subtype branching to `graphql_soup`, `complete_graph::SoupEdges`, or `graphql_properties`; that decision belongs in the properties domain.++Likely files:++- `crates/graphql_properties/src/mutations.rs`+- `crates/graphql_properties/src/loaders.rs`+- `crates/graphql_common/src/property_filter.rs` (only if types must be split/exported here)+- `crates/complete_graph/src/edges.rs`+- `crates/complete_graph/src/schema.rs`+- `services/document_storage_service/src/api/graphql_soup.rs`+- `static_assets/schema.graphql` (generated, never edited manually)++### REST/OpenAPI++The REST path currently uses the same properties `EntityType` that includes `TASK`. Introduce a target-only API type without Task for entity-scoped paths and bulk subject references. Convert it to canonical entity-access types in the receipt extractor.++Keep value-level `EntityReference.entity_type` separate so this change does not silently alter Parent Task/Subtasks or constrained property definitions.++Likely files:++- `crates/models_properties/src/api/**`+- `crates/properties/src/inbound/axum_router/extract.rs`+- `crates/properties/src/inbound/axum_router/entities.rs`+- `crates/properties_service/**` and DSS OpenAPI composition as required++### Tools and internal adapters++Update user-facing tools to target tasks as documents and pass canonical receipts. Internal task lifecycle ports may continue using internal `Task` rows where they bypass the user-facing target contract deliberately.++Review at least:++- `crates/properties/src/inbound/toolset/get_entity_properties.rs`+- `crates/properties/src/inbound/toolset/set_entity_property.rs`+- `crates/ai_tools/src/tool_context.rs`+- `services/document_storage_service/src/api/context.rs`+- `crates/documents/src/domain/ports/mod.rs`+- `crates/documents/src/domain/service.rs`++Do not blindly replace every Task occurrence: task relationship values, filters, system-property initialization, and internal repository keys remain Task in this phase.++## Properties service changes++Add one internal resolution helper and use it consistently before repository access. Audit every method that currently reads `access.entity_type()` or constructs `EntityReference`/`EntityPropertiesKey` from a receipt, including:++- `get_entity_properties`+- `get_property_value` / `get_system_property_value`+- `set_entity_property`+- `add_entity_property_option`+- `remove_entity_property_option`+- `get_entity_properties_with_definitions`+- `get_entity_metadata_properties`+- `get_bulk_entity_properties`+- `delete_entity_properties`+- assignment deletion authorization comparisons+- search reindex dispatch after writes++Task-only behavior must use the resolved internal type:++- assignee permission grants+- task-assigned notifications+- Parent Task/Subtasks relationship writes+- task-specific validation+- search indexing as a task++Authorization comparisons must use canonicalized types. For example, an assignment lookup returning internal `Task` belongs to a receipt for canonical `Document`; comparing those enums directly would incorrectly reject access.++Likely files:++- `crates/properties/src/domain/model.rs`+- `crates/properties/src/domain/service.rs`+- `crates/properties/src/domain/service_impl/mod.rs`+- `crates/properties/src/domain/service_impl/task_properties.rs`+- `crates/properties/src/domain/ports.rs`+- `crates/properties/src/outbound/metadata_queries.rs`+- `crates/properties/src/outbound/properties_pg_repo.rs`+- `crates/properties/src/domain/test.rs`+- `crates/properties/src/outbound/test.rs` and focused query tests++## Frontend changes++After backend schema/OpenAPI changes and code generation, make property **targets** canonical:++- `TaskEntity` remains `{ type: "document", subType: { type: "task" } }`.+- `macroEntityToPropertyEntityType` (or its replacement target helper) returns `DOCUMENT` for a task.+- Task grid, inline task properties, side panel, row tags, inbox property editors, title/editor property calls, and hotkey bulk property edits pass `DOCUMENT` as the target.+- `graphql-properties.ts` maps the new target type and no longer sends `TASK` for `SetEntityPropertyInput`.+- Entity-reference conversion remains separate and may still emit `TASK` where the value schema requires it.+- Do not manually edit generated TypeScript.++Audit the hardcoded target call sites found by searching for `EntityType.TASK`, `'TASK'`, and `isTaskEntity`, especially:++- `apps/web/src/features/property/utils/entityConversion.ts`+- `apps/web/src/features/entity/extractors-property/entity-key-properties.tsx`+- `apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx`+- `apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx`+- `apps/web/src/features/block-md/component/InlineTaskProperties.tsx`+- `apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx`+- `apps/web/src/features/entity/composed/list-entity/wide-layout.tsx`+- `apps/web/src/lib/service-clients/service-storage/graphql-properties.ts`++Classify each occurrence as either:++- **target type**: change to canonical `DOCUMENT`; or+- **reference/filter/rendering/internal task classification**: retain Task semantics.++## Compatibility and atomic rollout++This work uses an atomic deployment strategy. Removing `TASK` from the GraphQL target input enum is a breaking contract, so the backend and every client must deploy together.++Create the target-only enum without `TASK` immediately, regenerate all clients in the same change, and deploy the backend and clients atomically. Do not add a deprecated `TASK` alias or a compatibility phase.++Changing the committed GraphQL SDL rotates the normalized cache schema hash, so persisted client caches will rebuild automatically. Do not add manual cache-version logic.++## Test plan++### Properties domain tests++Add focused tests proving:++1. A canonical Document edit receipt for a task resolves to internal `EntityType::Task` for writes.+2. A canonical Document view receipt for a task resolves to internal Task for reads.+3. A regular document and snippet resolve to internal Document.+4. Mixed bulk task/document reads issue one batched subtype lookup and return results under canonical Document keys.+5. Assignee updates through a canonical Document receipt still grant permissions and send notifications.+6. Parent Task/Subtasks behavior still uses internal Task rows.+7. Add/remove option and delete flows resolve the same internal key as set/get.+8. Assignment deletion accepts a canonical Document receipt for an assignment stored under Task, but still rejects a receipt for a different entity id.+9. Search reindex dispatch retains the resolved internal Task type.+10. Missing subtype/document facts follow the documented fallback/error behavior.++### Outbound tests++Add query tests for batch subtype resolution:++- task document+- regular document+- snippet+- duplicate ids+- missing id+- mixed batch++Any SQLx query changes require `just prepare_db` from the repository root. Never edit `.sqlx` files manually.++### GraphQL tests++Add tests proving:++1. `SetEntityPropertyInput` accepts canonical `DOCUMENT` for a task target.+2. The target-only enum does not expose Task.+3. Entity-reference values can still represent the existing Task reference type where required.+4. A mutation setting Assignees followed by a fresh/network-equivalent GraphQL Soup query returns the assignee.+5. A regular document with the same shape still reads Document-scoped properties.+6. The committed SDL matches generated schema.++The key regression test is a mutation-then-fresh-query test; an optimistic-cache-only assertion is not sufficient.++### Frontend tests++Add or update tests proving:++1. Task property targets are sent as `DOCUMENT`.+2. Regular document targets remain `DOCUMENT`.+3. The assignee mutation still sends `multiEntityReference` values correctly.+4. Task references used as property values are not accidentally converted unless that contract is intentionally changed.+5. A real mutation response and subsequent network query keep the task's property linked in the normalized graph.++## Generated artifacts++After changing the GraphQL schema:++```bash+cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql+(\cd apps/web && bun gen-graphql)+```++After changing REST/OpenAPI types:++```bash+(\cd apps/web && bun gen-api properties-service)+```++Use the appropriate DSS/cloud-storage target too if its generated OpenAPI exposes the affected routes. Never manually edit generated Rust/TypeScript schema artifacts.++## Validation sequence++Run focused validation before workspace-wide checks:++```bash+cargo test -p properties+cargo test -p graphql_properties+cargo test -p complete_graph+cargo test -p document_storage_service+just prepare_db # required if SQLx queries changed+(\cd apps/web && bunx vitest run <focused-test-files>)+(\cd apps/web && bun type-check)+```++Then run the repository Rust validation sequence from the root:++```bash+just check+just clippy+just format+```++Also verify generated contracts are clean/up to date and run `git diff --check` (or the repository equivalent). Follow the repository rule to create a `jj` revision after each successful verification checkpoint.++Do not run migrations for this plan; none are expected.++## Acceptance criteria++- Web task property mutations send a canonical `DOCUMENT` target.+- No user-facing property target API requires callers to distinguish Task from Document.+- Existing task property rows remain stored and retrieved under internal `TASK`.+- Both single and bulk property reads resolve task subtype inside the properties domain.+- A successful Assignees mutation remains present after a hard reload/fresh GraphQL Soup network response.+- Assignee permissions and notifications still occur.+- Regular document properties are unaffected.+- No N+1 subtype queries are introduced.+- GraphQL SDL, OpenAPI clients, SQLx metadata, and tests are updated through generators.++## Hexagonal architecture boundary++This design keeps dependencies pointing inward:++- **Inbound adapters** parse canonical target ids/types, authenticate, mint typed entity-access receipts, and call the service. They do not decide whether a document is a task.+- **Properties domain service** owns Task-versus-Document classification policy and task-specific side-effect orchestration.+- **Outbound adapter** returns document subtype facts and performs internal Task/Document-keyed persistence; it does not choose business behavior.+- **Composition roots** wire concrete access, repository, notification, permission, and indexing adapters.++Authorization remains represented by `EntityAccessReceipt<ViewAccessLevel/EditAccessLevel>`. The subtype resolver must never become a substitute for authorization.diff --git a/services/document_storage_service/src/api/annotations/create_comment.rs b/services/document_storage_service/src/api/annotations/create_comment.rsindex 6955a62493..2a15ab1734 100644--- a/services/document_storage_service/src/api/annotations/create_comment.rs+++ b/services/document_storage_service/src/api/annotations/create_comment.rs@@ -12,6 +12,7 @@ use axum::{response::{IntoResponse, Response},};use connection_gateway_client::ConnectionGatewayClient;+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};use macro_authorization::MacroAuthorizationExtractor;use macro_db_client::annotations::create_comment::create_document_comment;use macro_user_id::user_id::MacroUserIdStr;@@ -110,9 +111,9 @@ pub async fn create_comment_handler(// outside the commenting user's session. The comment itself was// already authorized by the document middleware.let task_properties_access =- properties::PropertiesAccessReceipt::dangerously_assert_internal(+ EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_internal_user(&document_id,- models_properties::EntityType::Task,+ model_entity::EntityType::Document,);let task_assignee_ids: Vec<String> = match properties_service.get_system_property_value(diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 1d66b13f71..d29dd17e5f 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -206,16 +206,11 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {&user_id,None,entity_id,- properties::access_entity_type(models_properties::EntityType::Task),+ model_entity::EntityType::Document,).await?;- let access = properties::PropertiesAccessReceipt::try_from_entity_access_receipt(- entity_access_receipt,- models_properties::EntityType::Task,- )?;-self.properties- .set_entity_property(&access, property_definition_id, value)+ .set_entity_property(&entity_access_receipt, property_definition_id, value).await.map(|_| ()).map_err(Into::into)diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 48f406ca38..161313c2c4 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -1208,6 +1208,44 @@ input GraphqlPropertyMatchValue @oneOf {entityRef: String}+"""+Canonical entity type accepted for property targets.+"""+enum GraphqlPropertyTargetEntityType {+ """+ Call record target.+ """+ CALL_RECORD+ """+ Channel target.+ """+ CHANNEL+ """+ Chat target.+ """+ CHAT+ """+ CRM company target.+ """+ COMPANY+ """+ Document target, including tasks and snippets.+ """+ DOCUMENT+ """+ Project target.+ """+ PROJECT+ """+ Email thread target.+ """+ THREAD+ """+ User target.+ """+ USER+}+"""A property value represented by a type-safe GraphQL union."""@@ -2470,7 +2508,7 @@ input SetEntityPropertyInput {"""Type of entity receiving the property."""- entityType: GraphqlPropertyEntityType!+ entityType: GraphqlPropertyTargetEntityType!"""Identifier of the entity receiving the property."""