Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: record initiative activity (#6837)
teoa168b8ca6d7d
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.jsonindex 2b8e5c214b..ef5f685b1a 100644--- a/.github/kafka-cluster-topics.json+++ b/.github/kafka-cluster-topics.json@@ -10,6 +10,7 @@"macro.documents","macro.email","macro.example",+ "macro.initiatives","macro.mentions","macro.messages","macro.notifications",diff --git a/.sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.json b/.sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.jsonnew file mode 100644index 0000000000..81f3aefda1--- /dev/null+++ b/.sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.json@@ -0,0 +1,66 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_at\n FROM activity_events WHERE entity_type = $1 AND entity_id = $2\n ORDER BY occurred_at DESC, id DESC LIMIT $3",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "actor_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "action",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "action_payload",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "subject_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "occurred_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c"+}diff --git a/.sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.json b/.sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.jsonnew file mode 100644index 0000000000..51f8bfa3bb--- /dev/null+++ b/.sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.json@@ -0,0 +1,68 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_at\n FROM activity_events WHERE entity_type = $1 AND entity_id = $2 AND (occurred_at, id) < ($3, $4)\n ORDER BY occurred_at DESC, id DESC LIMIT $5",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "actor_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "action",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "action_payload",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "subject_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "occurred_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Timestamptz",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12"+}diff --git a/Cargo.lock b/Cargo.lockindex 4a21f6cf70..2bef4d5056 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3160,7 +3160,7 @@ dependencies = [[[package]]name = "cache-wasm"-version = "0.6.25"+version = "0.6.26"dependencies = ["async-lock","cache-core",@@ -7747,6 +7747,7 @@ dependencies = [name = "graphql_initiative"version = "0.1.0"dependencies = [+ "activity","async-graphql","chrono","entity_access",@@ -9152,6 +9153,7 @@ dependencies = [name = "initiative"version = "0.1.0"dependencies = [+ "activity","anyhow","axum","chrono",@@ -9160,6 +9162,8 @@ dependencies = ["http-body-util","macro_authorization","macro_db_migrator",+ "macro_event_broker",+ "macro_event_topics","macro_user_id","macro_uuid","mockall",@@ -16232,6 +16236,7 @@ dependencies = ["email","entity_access","futures",+ "initiative","kafka_util","macro_event_broker","macro_event_topics",diff --git a/apps/web/src/features/activity/components/action-glyph.tsx b/apps/web/src/features/activity/components/action-glyph.tsxindex 1fd66b9a0e..6794ffc4e3 100644--- a/apps/web/src/features/activity/components/action-glyph.tsx+++ b/apps/web/src/features/activity/components/action-glyph.tsx@@ -1,5 +1,6 @@import ChatCircle from '@phosphor/chat-circle.svg';import Eye from '@phosphor/eye.svg';+import Minus from '@phosphor/minus.svg';import PaperPlaneTilt from '@phosphor/paper-plane-tilt.svg';import PencilSimple from '@phosphor/pencil-simple.svg';import Phone from '@phosphor/phone.svg';@@ -13,6 +14,8 @@ import type { ActivityAction } from '../core/event';const GLYPHS = {created: Plus,+ 'task-added': Plus,+ 'task-removed': Minus,edited: PencilSimple,opened: Eye,deleted: Trash,diff --git a/apps/web/src/features/activity/core/describe-action.test.ts b/apps/web/src/features/activity/core/describe-action.test.tsindex 2d96bbe3e1..b1cd5a0570 100644--- a/apps/web/src/features/activity/core/describe-action.test.ts+++ b/apps/web/src/features/activity/core/describe-action.test.ts@@ -32,6 +32,14 @@ const ENTITY_CASES: Array<[ActivityAction, { verb: string; connector?: string }]> = [[{ kind: 'created' }, { verb: 'created' }],+ [+ { kind: 'task-added', taskId: 'task' },+ { verb: 'added a task', connector: 'to' },+ ],+ [+ { kind: 'task-removed', taskId: 'task' },+ { verb: 'removed a task', connector: 'from' },+ ],[{ kind: 'messaged' }, { verb: 'sent a message', connector: 'in' }],[{ kind: 'participant-added', participant: 'macro|[email protected]' },diff --git a/apps/web/src/features/activity/core/describe-action.ts b/apps/web/src/features/activity/core/describe-action.tsindex 60267bc17d..e7eff88315 100644--- a/apps/web/src/features/activity/core/describe-action.ts+++ b/apps/web/src/features/activity/core/describe-action.ts@@ -32,6 +32,8 @@ export function describeRun(entry: FeedEntry): {export function describeAction(action: ActivityAction, count = 1): string {if (count < 2) {return match(action)+ .with({ kind: 'task-added' }, () => 'added a task')+ .with({ kind: 'task-removed' }, () => 'removed a task').with({ kind: 'created' }, () => 'created this').with({ kind: 'edited' }, () => 'made an edit').with({ kind: 'opened' }, () => 'opened this')@@ -46,6 +48,8 @@ export function describeAction(action: ActivityAction, count = 1): string {.exhaustive();}return match(action)+ .with({ kind: 'task-added' }, () => `added ${count} tasks`)+ .with({ kind: 'task-removed' }, () => `removed ${count} tasks`).with({ kind: 'created' }, () => `created this ${count} times`).with({ kind: 'edited' }, () => `made ${count} edits`).with({ kind: 'opened' }, () => `opened this ${count} times`)@@ -77,6 +81,14 @@ export function describeActionForEntity(action: ActivityAction): {connector?: string;} {return match(action)+ .with({ kind: 'task-added' }, () => ({+ verb: 'added a task',+ connector: 'to',+ }))+ .with({ kind: 'task-removed' }, () => ({+ verb: 'removed a task',+ connector: 'from',+ })).with({ kind: 'created' }, () => ({verb: 'created',}))diff --git a/apps/web/src/features/activity/core/event.ts b/apps/web/src/features/activity/core/event.tsindex 8a0ec0d510..a58b2d01bc 100644--- a/apps/web/src/features/activity/core/event.ts+++ b/apps/web/src/features/activity/core/event.ts@@ -11,11 +11,14 @@ export type ActivityAction =| { kind: 'property-changed'; property: string; from: unknown; to: unknown }| { kind: 'participant-added'; participant: string }| { kind: 'participant-removed'; participant: string }+ | { kind: 'task-added'; taskId?: string }+ | { kind: 'task-removed'; taskId?: string }| { kind: 'unknown'; tag: string };export type ActivityEntityType =| 'document'| 'project'+ | 'initiative'| 'chat'| 'email-thread'| 'channel'@@ -49,6 +52,7 @@ export type ActivityOverview = {export type PropertyEntityType =| 'DOCUMENT'| 'PROJECT'+ | 'INITIATIVE'| 'CHAT'| 'THREAD'| 'CHANNEL'@@ -60,6 +64,7 @@ export function toPropertyEntityType(return match(entityType).with({ kind: 'unsupported' }, () => undefined).with('document', () => 'DOCUMENT' as const)+ .with('initiative', () => 'INITIATIVE' as const).with('project', () => 'PROJECT' as const).with('chat', () => 'CHAT' as const).with('email-thread', () => 'THREAD' as const)diff --git a/apps/web/src/features/activity/queries/decode.ts b/apps/web/src/features/activity/queries/decode.tsindex 61b2abb415..fc9847880b 100644--- a/apps/web/src/features/activity/queries/decode.ts+++ b/apps/web/src/features/activity/queries/decode.ts@@ -45,6 +45,7 @@ export function decodeEntityType(entityType: GraphqlEntityType): ActivityEntityType {return match(entityType)+ .with('INITIATIVE', () => 'initiative' as const).with('DOCUMENT', () => 'document' as const).with('PROJECT', () => 'project' as const).with('CHAT', () => 'chat' as const)@@ -58,6 +59,12 @@ function decodeAction(action: ActivityEventFieldsFragment['action']): ActivityAction {return match(action)+ .with({ __typename: 'GraphqlActivityTaskAdded' }, () => ({+ kind: 'task-added' as const,+ }))+ .with({ __typename: 'GraphqlActivityTaskRemoved' }, () => ({+ kind: 'task-removed' as const,+ })).with({ __typename: 'GraphqlActivityCreated' }, () => ({kind: 'created' as const,}))diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsxindex 15abe23d06..e7c0373d66 100644--- a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx@@ -23,6 +23,7 @@ type Activity = NamedTool<function decodeToolEntityType(raw: string): ActivityEntityType {return match(raw).with('document', () => 'document' as const)+ .with('initiative', () => 'initiative' as const).with('project', () => 'project' as const).with('chat', () => 'chat' as const).with('email_thread', () => 'email-thread' as const)@@ -33,6 +34,8 @@ function decodeToolEntityType(raw: string): ActivityEntityType {function activityAction(action: Activity['action']): ActivityAction {return match(action)+ .with({ type: 'taskAdded' }, () => ({ kind: 'task-added' as const }))+ .with({ type: 'taskRemoved' }, () => ({ kind: 'task-removed' as const })).with({ type: 'created' }, () => ({kind: 'created' as const,}))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 3502e47556..804eb9851f 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@@ -3915,6 +3915,8 @@ export const ReadActivityResponse = z.object({type: z.literal('participantRemoved'),}),z.object({ callId: z.string(), type: z.literal('callStarted') }),+ z.object({ type: z.literal('taskAdded') }),+ z.object({ type: z.literal('taskRemoved') }),z.object({tag: z.string(),payload: z.any().optional(),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 80d45225f2..c52e8c2a53 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@@ -862,6 +862,12 @@ export type ToolActivityAction =callId: string;type: 'callStarted';}+ | {+ type: 'taskAdded';+ }+ | {+ type: 'taskRemoved';+ }| {/*** The stored action tag.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 9611713681..7f87cffe63 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@@ -1401,6 +1401,8 @@ export type ActivityUpdatesSubscription = { activityUpdates:| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}| { __typename: 'GraphqlActivityInvalidation', refresh: boolean }@@ -1422,6 +1424,8 @@ export type MyActivityQuery = { user: { id: string, activity: { nextCursor: stri| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> } } };@@ -1450,6 +1454,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupCalendarEvent', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1463,6 +1469,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupCall', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1476,6 +1484,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupChannel', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1489,6 +1499,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupChannelMessage', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1502,6 +1514,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupChat', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1515,6 +1529,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupCrmCompany', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1528,6 +1544,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupDocument', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1541,6 +1559,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupEmailThread', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1554,6 +1574,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupForeignEntity', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1567,6 +1589,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupInitiative', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1580,6 +1604,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupProject', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1593,6 +1619,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }| { __typename: 'GraphqlSoupReminder', id: string, activity: Array<{ __typename: 'GraphqlActivityEvent', id: string, actorId: string, subjectId: string, entityType: GraphqlEntityType, entityId: string, occurredAt: string, action:@@ -1606,6 +1634,8 @@ export type EntityActivityQuery = { user: { id: string, soup: { items: Array<| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> }> } } };@@ -1621,6 +1651,8 @@ type EntityActivityFields_GraphqlSoupAgentSession_Fragment = { __typename: 'Grap| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1635,6 +1667,8 @@ type EntityActivityFields_GraphqlSoupCalendarEvent_Fragment = { __typename: 'Gra| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1649,6 +1683,8 @@ type EntityActivityFields_GraphqlSoupCall_Fragment = { __typename: 'GraphqlSoupC| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1663,6 +1699,8 @@ type EntityActivityFields_GraphqlSoupChannel_Fragment = { __typename: 'GraphqlSo| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1677,6 +1715,8 @@ type EntityActivityFields_GraphqlSoupChannelMessage_Fragment = { __typename: 'Gr| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1691,6 +1731,8 @@ type EntityActivityFields_GraphqlSoupChat_Fragment = { __typename: 'GraphqlSoupC| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1705,6 +1747,8 @@ type EntityActivityFields_GraphqlSoupCrmCompany_Fragment = { __typename: 'Graphq| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1719,6 +1763,8 @@ type EntityActivityFields_GraphqlSoupDocument_Fragment = { __typename: 'GraphqlS| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1733,6 +1779,8 @@ type EntityActivityFields_GraphqlSoupEmailThread_Fragment = { __typename: 'Graph| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1747,6 +1795,8 @@ type EntityActivityFields_GraphqlSoupForeignEntity_Fragment = { __typename: 'Gra| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1761,6 +1811,8 @@ type EntityActivityFields_GraphqlSoupInitiative_Fragment = { __typename: 'Graphq| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1775,6 +1827,8 @@ type EntityActivityFields_GraphqlSoupProject_Fragment = { __typename: 'GraphqlSo| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1789,6 +1843,8 @@ type EntityActivityFields_GraphqlSoupReminder_Fragment = { __typename: 'GraphqlS| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }}> };@@ -1819,6 +1875,8 @@ export type ActivityEventFieldsFragment = { __typename: 'GraphqlActivityEvent',| { __typename: 'GraphqlActivityParticipantRemoved', participant: string }| { __typename: 'GraphqlActivityPropertyChanged', property: string, from: unknown, to: unknown }| { __typename: 'GraphqlActivitySent' }+ | { __typename: 'GraphqlActivityTaskAdded' }+ | { __typename: 'GraphqlActivityTaskRemoved' }| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }};diff --git a/crates/activity/src/domain/announcements.rs b/crates/activity/src/domain/announcements.rsindex a0fd38d299..731cd712b5 100644--- a/crates/activity/src/domain/announcements.rs+++ b/crates/activity/src/domain/announcements.rs@@ -13,7 +13,7 @@ use std::{use super::{events::{ActivityTopicEvent, ActivityWireRow},- models::Activity,+ models::{Action, Activity},ports::{ActivityAudienceExpander, ActivityEventPublisher, ActivityRealtimePublisher},};@@ -55,10 +55,20 @@ impl<P: ActivityEventPublisher, A: ActivityAudienceExpander> ActivityAnnouncemen.iter().map(|user| user.as_ref().to_owned()).collect();- // A subject can read their own feed even after losing entity access.- // Bot principals cannot open a user subscription.- if MacroUserIdStr::parse_from_str(subject).is_ok() {- row_recipients.insert(subject.to_owned());+ // Project moves can originate in a project the subject has never seen.+ // Its identifier must remain private, including after access is revoked.+ // Other domains retain their existing subject-feed behavior.+ if let Ok(viewer) = MacroUserIdStr::parse_from_str(subject) {+ let allowed = kind != EntityType::Initiative+ || row_recipients.contains(subject)+ || self+ .audience+ .viewer_can_see(kind, id, &viewer)+ .await+ .unwrap_or(false);+ if allowed {+ row_recipients.insert(subject.to_owned());+ }}recipients.push(row_recipients);}@@ -95,10 +105,40 @@ impl<P: ActivityEventPublisher, A: ActivityAudienceExpander> ActivityRealtimePub.map(|a| (a.entity_type, a.entity_id.as_str(), a.subject_id.as_str())).collect();let recipients = self.recipients(&keys).await;+ let mut task_audiences = HashMap::<String, BTreeSet<String>>::new();let mut deliveries: HashMap<String, Vec<ActivityWireRow>> = HashMap::new();for (activity, users) in activities.iter().zip(recipients) {+ let task_id = match &activity.action {+ Action::TaskAdded(change) | Action::TaskRemoved(change) => {+ Some(&change.task_id)+ }+ _ => None,+ };+ if let Some(task_id) = task_id+ && !task_audiences.contains_key(task_id)+ {+ let audience = self+ .audience+ .entity_audience(EntityType::Document, task_id)+ .await;+ let allowed = match audience {+ Ok(users) => users.into_iter().map(|user| user.to_string()).collect(),+ Err(error) => {+ tracing::warn!(?error, "task activity audience lookup failed");+ BTreeSet::new()+ }+ };+ task_audiences.insert(task_id.clone(), allowed);+ }let row = ActivityWireRow::from_activity(activity);for user in users {+ // A project grant alone never reveals an associated task. Public-link+ // viewers recover through authorized history reads on refetch.+ if let Some(task_id) = task_id+ && !task_audiences[task_id].contains(&user)+ {+ continue;+ }deliveries.entry(user).or_default().push(row.clone());}}diff --git a/crates/activity/src/domain/announcements/test.rs b/crates/activity/src/domain/announcements/test.rsindex b1d3624d49..64849a3c60 100644--- a/crates/activity/src/domain/announcements/test.rs+++ b/crates/activity/src/domain/announcements/test.rs@@ -63,6 +63,130 @@ fn user(local: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(format!("macro|{local}@example.com")).expect("valid user id")}+#[tokio::test]+async fn moving_task_does_not_announce_hidden_source_project_to_the_actor() {+ struct Removed;+ impl crate::DomainActivity for Removed {+ const ENTITY_TYPE: EntityType = EntityType::Initiative;+ fn entity_id(&self) -> &str {+ "hidden-source"+ }+ fn into_action(self) -> crate::Action {+ crate::Action::TaskRemoved(crate::InitiativeTaskChange {+ task_id: "task".into(),+ })+ }+ }+ let actor = user("task-editor");+ let source_owner = user("source-owner");+ let broker = RecordingPublisher::default();+ let announcements = ActivityAnnouncements::new(+ broker.clone(),+ FakeAudience {+ by_entity: HashMap::from([+ ("hidden-source".into(), vec![source_owner.clone()]),+ ("task".into(), vec![source_owner.clone(), actor.clone()]),+ ]),+ },+ );+ announcements+ .publish_recorded(&[Activity::from_domain(+ Uuid::now_v7(),+ 0,+ Actor::new_from_user(actor.clone()),+ None,+ Removed,+ Utc::now(),+ )])+ .await;+ let deliveries = broker.recorded_events();+ assert_eq!(deliveries.len(), 1);+ assert_eq!(deliveries[0].0, source_owner.as_ref());+ assert!(+ deliveries+ .iter()+ .all(|(recipient, _)| recipient != actor.as_ref())+ );+}++#[tokio::test]+async fn project_subject_with_public_link_access_still_receives_activity() {+ struct PublicProject;+ impl ActivityAudienceExpander for PublicProject {+ type Err = std::convert::Infallible;+ async fn entity_audience(+ &self,+ _: EntityType,+ _: &str,+ ) -> Result<Vec<MacroUserIdStr<'static>>, Self::Err> {+ Ok(Vec::new())+ }+ async fn viewer_can_see(+ &self,+ _: EntityType,+ _: &str,+ _: &MacroUserIdStr<'_>,+ ) -> Result<bool, Self::Err> {+ Ok(true)+ }+ }+ let actor = user("editor");+ let broker = RecordingPublisher::default();+ let announcements = ActivityAnnouncements::new(broker.clone(), PublicProject);+ let row = Activity::common(+ Uuid::now_v7(),+ 0,+ Actor::new_from_user(actor.clone()),+ None,+ EntityType::Initiative,+ "public-project",+ CommonAction::Edited,+ Utc::now(),+ );+ announcements.publish_recorded(&[row]).await;+ assert_eq!(broker.recorded_events()[0].0, actor.as_ref());+}++#[tokio::test]+async fn project_membership_realtime_requires_task_access_as_well_as_project_access() {+ struct Membership;+ impl crate::DomainActivity for Membership {+ const ENTITY_TYPE: EntityType = EntityType::Initiative;+ fn entity_id(&self) -> &str {+ "initiative-1"+ }+ fn into_action(self) -> crate::Action {+ crate::Action::TaskAdded(crate::InitiativeTaskChange {+ task_id: "private-task".into(),+ })+ }+ }+ let owner = user("owner");+ let watcher = user("watcher");+ let broker = RecordingPublisher::default();+ let announcements = ActivityAnnouncements::new(+ broker.clone(),+ FakeAudience {+ by_entity: HashMap::from([+ ("initiative-1".into(), vec![owner.clone(), watcher]),+ ("private-task".into(), vec![owner.clone()]),+ ]),+ },+ );+ let row = Activity::from_domain(+ Uuid::from_u128(3),+ 0,+ Actor::new_from_user(owner.clone()),+ None,+ Membership,+ Utc::now(),+ );+ announcements.publish_recorded(&[row]).await;+ let deliveries = broker.recorded_events();+ assert_eq!(deliveries.len(), 1);+ assert_eq!(deliveries[0].0, owner.as_ref());+}+fn edited(ordinal: u32, actor: Actor<'static>, entity_id: &str) -> Activity {Activity::common(Uuid::from_u128(7),diff --git a/crates/activity/src/domain/models.rs b/crates/activity/src/domain/models.rsindex eafad2e3fd..d5fe3c7453 100644--- a/crates/activity/src/domain/models.rs+++ b/crates/activity/src/domain/models.rs@@ -138,6 +138,13 @@ pub struct CallStart {pub call_id: String,}+/// Task referenced by a project membership event. No task name is stored.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct InitiativeTaskChange {+ /// The task document. Readers must verify task visibility before exposing this reference.+ pub task_id: String,+}+/// The durable action vocabulary — what the `action`/`action_payload`/// columns hold. [`Action::to_columns`] is the storage codec, written out/// explicitly; the future read path adds the inverse next to it.@@ -183,6 +190,10 @@ pub enum Action {ParticipantRemoved(ParticipantChange),/// A call was started in the entity (channel).CallStarted(CallStart),+ /// A task was added to an initiative.+ TaskAdded(InitiativeTaskChange),+ /// A task was removed from an initiative.+ TaskRemoved(InitiativeTaskChange),}impl From<CommonAction> for Action {@@ -235,6 +246,7 @@ impl Action {payload(change)}Action::CallStarted(start) => payload(start),+ Action::TaskAdded(change) | Action::TaskRemoved(change) => payload(change),};(tag, payload)}@@ -272,6 +284,8 @@ impl Action {ActionTag::ParticipantAdded => Ok(Action::ParticipantAdded(parsed(payload)?)),ActionTag::ParticipantRemoved => Ok(Action::ParticipantRemoved(parsed(payload)?)),ActionTag::CallStarted => Ok(Action::CallStarted(parsed(payload)?)),+ ActionTag::TaskAdded => Ok(Action::TaskAdded(parsed(payload)?)),+ ActionTag::TaskRemoved => Ok(Action::TaskRemoved(parsed(payload)?)),}}}diff --git a/crates/activity/src/domain/models/test.rs b/crates/activity/src/domain/models/test.rsindex 846619e7f0..f0a5ebe3da 100644--- a/crates/activity/src/domain/models/test.rs+++ b/crates/activity/src/domain/models/test.rs@@ -19,6 +19,20 @@ fn every_action_maps_to_stable_columns() {(Action::Deleted, "deleted", None),(Action::Messaged, "messaged", None),(Action::Sent, "sent", None),+ (+ Action::TaskAdded(InitiativeTaskChange {+ task_id: "task-1".into(),+ }),+ "task_added",+ Some(json!({"task_id":"task-1"})),+ ),+ (+ Action::TaskRemoved(InitiativeTaskChange {+ task_id: "task-1".into(),+ }),+ "task_removed",+ Some(json!({"task_id":"task-1"})),+ ),(Action::PropertyChanged(PropertyChange {property: "prop-1".to_string(),diff --git a/crates/activity/src/domain/ports.rs b/crates/activity/src/domain/ports.rsindex 082ffe2ba8..5a882e4ba4 100644--- a/crates/activity/src/domain/ports.rs+++ b/crates/activity/src/domain/ports.rs@@ -94,6 +94,23 @@ pub trait ActivityAudienceExpander: Send + Sync {entity_type: EntityType,entity_id: &str,) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Self::Err>> + Send;++ /// Check a particular viewer, including link-based access that cannot be+ /// enumerated as an audience. The conservative default uses explicit recipients.+ fn viewer_can_see(+ &self,+ entity_type: EntityType,+ entity_id: &str,+ viewer: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send {+ async move {+ Ok(self+ .entity_audience(entity_type, entity_id)+ .await?+ .iter()+ .any(|user| user == viewer))+ }+ }}/// Publishes an already addressed activity announcement.@@ -176,3 +193,20 @@ pub trait ActivityReads {limit: NonZeroU32,) -> impl Future<Output = Result<ActivityRange, Self::Err>> + Send;}++/// Paginated entity history, separate from subject feeds and batched previews.+/// Callers must hold entity access and verify references embedded in payloads.+pub trait EntityActivityReads: Send + Sync + 'static {+ /// Persistence error.+ type Err: std::error::Error + Send + Sync + 'static;++ /// Read one entity in stable `(occurred_at DESC, id DESC)` order. The raw-row+ /// cursor advances even when a corrupt row cannot be decoded.+ fn entity_feed(+ &self,+ entity_type: EntityType,+ entity_id: &str,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ limit: NonZeroU32,+ ) -> impl Future<Output = Result<ActivityFeedPage, Self::Err>> + Send;+}diff --git a/crates/activity/src/inbound/toolset/read_activity.rs b/crates/activity/src/inbound/toolset/read_activity.rsindex 3f272650af..131343e6e1 100644--- a/crates/activity/src/inbound/toolset/read_activity.rs+++ b/crates/activity/src/inbound/toolset/read_activity.rs@@ -97,6 +97,10 @@ pub enum ToolActivityAction {/// The started call's id.call_id: String,},+ /// A task was added to the project. Resolve references through authorized project history.+ TaskAdded,+ /// A task was removed from the project.+ TaskRemoved,/// An action outside this deployment's vocabulary.Unknown {/// The stored action tag.@@ -141,6 +145,8 @@ impl ToolActivityAction {RecordedAction::Known(Action::CallStarted(start)) => Self::CallStarted {call_id: start.call_id,},+ RecordedAction::Known(Action::TaskAdded(_)) => Self::TaskAdded,+ RecordedAction::Known(Action::TaskRemoved(_)) => Self::TaskRemoved,RecordedAction::Unknown { tag, payload } => Self::Unknown { tag, payload },}}diff --git a/crates/activity/src/lib.rs b/crates/activity/src/lib.rsindex 2c66d1f2ea..6ca8b9ca2e 100644--- a/crates/activity/src/lib.rs+++ b/crates/activity/src/lib.rs@@ -30,8 +30,8 @@ pub mod outbound;pub use domain::events::{ActivityMacroEvent, ActivityTopicEvent, ActivityWireRow};pub use domain::models::{Action, ActionDecodeError, Activity, ActivityRecord, ActivitySource, Actor, Attribution,- CallStart, CommonAction, DomainActivity, EntityType, Ingest, ParticipantChange, PropertyChange,- RecordedAction, VIEW_ACTION_TAGS, activity_id, event_time,+ CallStart, CommonAction, DomainActivity, EntityType, Ingest, InitiativeTaskChange,+ ParticipantChange, PropertyChange, RecordedAction, VIEW_ACTION_TAGS, activity_id, event_time,};pub use domain::overview::{ActivityOverview, ActivityOverviewError, ActivityWindow, ActivityWindowError, DayCount,diff --git a/crates/activity/src/outbound/pg_activity_repo.rs b/crates/activity/src/outbound/pg_activity_repo.rsindex d4b9f79d2b..673a70841c 100644--- a/crates/activity/src/outbound/pg_activity_repo.rs+++ b/crates/activity/src/outbound/pg_activity_repo.rs@@ -3,6 +3,8 @@#[cfg(test)]mod test;+mod entity_history;+use std::collections::HashMap;use std::num::{NonZeroU32, NonZeroU64};use std::str::FromStr;diff --git a/crates/activity/src/outbound/pg_activity_repo/entity_history.rs b/crates/activity/src/outbound/pg_activity_repo/entity_history.rsnew file mode 100644index 0000000000..325e631fd8--- /dev/null+++ b/crates/activity/src/outbound/pg_activity_repo/entity_history.rs@@ -0,0 +1,47 @@+//! Keyset history for native entity views, independent of Soup.++use chrono::{DateTime, Utc};+use model_entity::EntityType;+use std::num::NonZeroU32;+use uuid::Uuid;++use super::{PgActivityRepo, StoredRow};+use crate::domain::ports::{ActivityFeedPage, EntityActivityReads};++impl EntityActivityReads for PgActivityRepo {+ type Err = sqlx::Error;++ async fn entity_feed(+ &self,+ entity_type: EntityType,+ entity_id: &str,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ limit: NonZeroU32,+ ) -> Result<ActivityFeedPage, Self::Err> {+ let limit = limit.get();+ let fetch = i64::from(limit) + 1;+ let mut rows = match cursor {+ None => sqlx::query_as!(StoredRow,+ r#"SELECT id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_at+ FROM activity_events WHERE entity_type = $1 AND entity_id = $2+ ORDER BY occurred_at DESC, id DESC LIMIT $3"#,+ entity_type.as_ref(), entity_id, fetch,+ ).fetch_all(&self.pool).await?,+ Some((cursor_at, cursor_id)) => sqlx::query_as!(StoredRow,+ r#"SELECT id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_at+ FROM activity_events WHERE entity_type = $1 AND entity_id = $2 AND (occurred_at, id) < ($3, $4)+ ORDER BY occurred_at DESC, id DESC LIMIT $5"#,+ entity_type.as_ref(), entity_id, cursor_at, cursor_id, fetch,+ ).fetch_all(&self.pool).await?,+ };+ let has_more = rows.len() > limit as usize;+ rows.truncate(limit as usize);+ let next = has_more+ .then(|| rows.last().map(|row| (row.occurred_at, row.id)))+ .flatten();+ Ok(ActivityFeedPage {+ records: rows.into_iter().filter_map(StoredRow::decode).collect(),+ next,+ })+ }+}diff --git a/crates/activity/src/outbound/pg_activity_repo/test.rs b/crates/activity/src/outbound/pg_activity_repo/test.rsindex 02b46ac2ec..992ca8fc59 100644--- a/crates/activity/src/outbound/pg_activity_repo/test.rs+++ b/crates/activity/src/outbound/pg_activity_repo/test.rs@@ -5,6 +5,7 @@ use uuid::Uuid;use super::*;use crate::domain::models::{Action, Actor, CommonAction};+use crate::domain::ports::EntityActivityReads;fn user(id: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(id.to_string()).expect("valid user id")@@ -14,6 +15,39 @@ fn nz(limit: u32) -> NonZeroU32 {NonZeroU32::new(limit).expect("non-zero test limit")}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn entity_history_cursor_is_stable_and_scoped_to_one_entity(+ pool: PgPool,+) -> Result<(), sqlx::Error> {+ let repo = PgActivityRepo::new(pool);+ let rows = vec![+ seed(1, CommonAction::Created, "one"),+ seed(2, CommonAction::Edited, "one"),+ seed(3, CommonAction::Edited, "one"),+ seed(4, CommonAction::Created, "other"),+ ];+ repo.insert_activities(&rows).await?;+ repo.insert_activities(&rows).await?;+ let first = repo+ .entity_feed(EntityType::Document, "one", None, nz(2))+ .await?;+ assert_eq!(first.records.len(), 2);+ assert!(first.records.iter().all(|row| row.entity_id == "one"));+ let next = first.next.expect("second page");+ let second = repo+ .entity_feed(EntityType::Document, "one", Some(next), nz(2))+ .await?;+ assert_eq!(second.records.len(), 1);+ assert!(second.next.is_none());+ assert!(+ first+ .records+ .iter()+ .all(|row| row.id != second.records[0].id)+ );+ Ok(())+}+fn seed(source_event: u128, action: CommonAction, entity_id: &str) -> Activity {Activity::common(Uuid::from_u128(source_event),diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex f85b57c67d..f2e62c6db8 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -8,7 +8,7 @@ version = "0.1.0"test-support = [][dependencies]-initiative = { path = "../initiative", default-features = false, features = ["postgres"] }+initiative = { path = "../initiative", default-features = false, features = ["postgres", "resources"] }activity = { path = "../activity", default-features = false, features = ["ai_tools", "outbound"] }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex e70faa654c..9030095681 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -252,18 +252,21 @@ pub async fn build_tool_service_context_from_env(let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone(),)));- let properties_service =- crate::tool_context::build_properties_service(pool.clone(), entity_access_service.clone());- let task_properties_service = crate::tool_context::build_task_properties_adapter(- pool.clone(),- properties_service.clone(),- entity_access_service.clone(),- );let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(macro_event_broker::KafkaEventPublisher::new(env.kafka_brokers.as_ref()).context("failed to create kafka event publisher")?,event_task_tracker,);+ let properties_service = crate::tool_context::build_properties_service_with_broker(+ pool.clone(),+ entity_access_service.clone(),+ macro_event_broker.clone(),+ );+ let task_properties_service = crate::tool_context::build_task_properties_adapter(+ pool.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );// Channel messages sent by AI tools dispatch the same side effects as the// document-storage channel API (realtime, notifications, contact sync, and// broker events that drive live search indexing), so agent-sent messagesdiff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex e014f0a80f..47f3ee1dce 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -69,9 +69,9 @@ pub use tool_context::{build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,build_channel_tool_context_without_side_effects, build_crm_tool_context,build_message_service_with_side_effects, build_message_service_without_side_effects,- build_project_tool_context, build_properties_service, build_properties_tool_context,- build_reminders_tool_context, build_skill_tool_context, build_task_properties_adapter,- build_team_repository, build_team_tool_context,+ build_project_tool_context, build_properties_service, build_properties_service_with_broker,+ build_properties_tool_context, build_reminders_tool_context, build_skill_tool_context,+ build_task_properties_adapter, build_team_repository, build_team_tool_context,};pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 6b150eddfb..fb11303f76 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -895,6 +895,7 @@ pub type ToolPropertiesService = properties::PropertiesServiceImpl<properties::PropertiesPgRepo,properties::PermissionServiceImpl<ToolEntityAccessService>,NoOpNotificationService,+ ToolBotEventBroker,>;/// Imported-document property enrichment backed by the AI tool host's Properties service.@@ -910,14 +911,47 @@ pub fn build_properties_service(pool: sqlx::PgPool,entity_access_service: Arc<ToolEntityAccessService>,) -> Arc<ToolPropertiesService> {- Arc::new(properties::PropertiesServiceImpl::new(- properties::PropertiesPgRepo::new(pool.clone()),- Some(properties::PermissionServiceImpl::new(- pool,- entity_access_service,- )),- Some(NoOpNotificationService),- ))+ properties_service_with_events(+ pool,+ entity_access_service,+ ToolBotEventBroker::NoOp(Default::default()),+ )+}++/// Build canonical property tools with committed changes published to activity.+pub fn build_properties_service_with_broker(+ pool: sqlx::PgPool,+ entity_access_service: Arc<ToolEntityAccessService>,+ broker: ToolEventBroker,+) -> Arc<ToolPropertiesService> {+ properties_service_with_events(+ pool,+ entity_access_service,+ ToolBotEventBroker::Real(broker),+ )+}++fn properties_service_with_events(+ pool: sqlx::PgPool,+ entity_access_service: Arc<ToolEntityAccessService>,+ broker: ToolBotEventBroker,+) -> Arc<ToolPropertiesService> {+ Arc::new(+ properties::PropertiesServiceImpl::new(+ properties::PropertiesPgRepo::new(pool.clone()),+ Some(properties::PermissionServiceImpl::new(+ pool.clone(),+ entity_access_service,+ )),+ Some(NoOpNotificationService),+ )+ .with_initiative_assignees(Arc::new(+ initiative::domain::assignees::InitiativeAssignees::new(+ initiative::outbound::PgInitiativeRepo::new(pool),+ ),+ ))+ .with_event_broker(broker),+ )}/// Build the real task properties adapter used by document creation tools.@@ -1397,7 +1431,10 @@ pub type ToolImportService = import::domain::service::ImportServiceImpl<pub type ToolImportToolContext = import::inbound::toolset::ImportToolContext<ToolImportService>;pub type ToolActivityToolContext = activity::inbound::toolset::ActivityToolContext<- activity::outbound::pg_activity_repo::PgActivityRepo,+ initiative::domain::personal_activity::ProjectVisibleActivityReads<+ activity::outbound::pg_activity_repo::PgActivityRepo,+ ToolEntityAccessService,+ >,>;pub fn build_activity_tool_context(@@ -1406,7 +1443,10 @@ pub fn build_activity_tool_context(entity_access_service: Arc<ToolEntityAccessService>,) -> ToolActivityToolContext {activity::inbound::toolset::ActivityToolContext::new(- activity::outbound::pg_activity_repo::PgActivityRepo::new(pool),+ initiative::domain::personal_activity::ProjectVisibleActivityReads::new(+ activity::outbound::pg_activity_repo::PgActivityRepo::new(pool),+ entity_access_service.clone(),+ ),).with_metadata_resolver(ToolActivityMetadataResolver::new(properties,diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.tomlindex c99ad6ec01..45835b9857 100644--- a/crates/client/cache-wasm/Cargo.toml+++ b/crates/client/cache-wasm/Cargo.toml@@ -2,8 +2,8 @@edition = "2024"name = "cache-wasm"publish = false-# Rebuild the browser cache with initiative discussion notification schema support.-version = "0.6.25"+# Rebuild the browser cache with initiative activity action schema support.+version = "0.6.26"[features]default = []diff --git a/crates/graphql_activity/src/objects.rs b/crates/graphql_activity/src/objects.rsindex 2b446baa7d..f8338cc906 100644--- a/crates/graphql_activity/src/objects.rs+++ b/crates/graphql_activity/src/objects.rs@@ -70,6 +70,10 @@ pub enum GraphqlActivityAction {ParticipantRemoved(GraphqlActivityParticipantRemoved),/// A call was started in the entity (channel).CallStarted(GraphqlActivityCallStarted),+ /// A task was added; references are resolved through authorized project history.+ TaskAdded(GraphqlActivityTaskAdded),+ /// A task was removed; references are resolved through authorized project history.+ TaskRemoved(GraphqlActivityTaskRemoved),/// An action outside this deployment's vocabulary, carried through raw.Unknown(GraphqlActivityUnknownAction),}@@ -100,6 +104,10 @@ payload_free_action_objects!(GraphqlActivityMessaged,/// An email message was sent on the thread.GraphqlActivitySent,+ /// A task was added to a project.+ GraphqlActivityTaskAdded,+ /// A task was removed from a project.+ GraphqlActivityTaskRemoved,);/// A property value changed on the entity.@@ -175,6 +183,8 @@ impl From<RecordedAction> for GraphqlActivityAction {call_id: ID(start.call_id),})}+ RecordedAction::Known(Action::TaskAdded(_)) => Self::TaskAdded(Default::default()),+ RecordedAction::Known(Action::TaskRemoved(_)) => Self::TaskRemoved(Default::default()),RecordedAction::Unknown { tag, payload } => {Self::Unknown(GraphqlActivityUnknownAction {tag,diff --git a/crates/graphql_activity/src/objects/test.rs b/crates/graphql_activity/src/objects/test.rsindex 18ac4f0d2e..63a25dbcb9 100644--- a/crates/graphql_activity/src/objects/test.rs+++ b/crates/graphql_activity/src/objects/test.rs@@ -95,6 +95,8 @@ fn type_name(action: &GraphqlActivityAction) -> &'static str {GraphqlActivityAction::ParticipantAdded(_) => "ParticipantAdded",GraphqlActivityAction::ParticipantRemoved(_) => "ParticipantRemoved",GraphqlActivityAction::CallStarted(_) => "CallStarted",+ GraphqlActivityAction::TaskAdded(_) => "TaskAdded",+ GraphqlActivityAction::TaskRemoved(_) => "TaskRemoved",GraphqlActivityAction::Unknown(_) => "Unknown",}}diff --git a/crates/graphql_initiative/Cargo.toml b/crates/graphql_initiative/Cargo.tomlindex be193d463d..92ba399299 100644--- a/crates/graphql_initiative/Cargo.toml+++ b/crates/graphql_initiative/Cargo.toml@@ -28,5 +28,6 @@ models_properties = { path = "../models_properties" }model_owner = { path = "../model_owner" }serde = { workspace = true }chrono = { workspace = true }+activity = { path = "../activity", default-features = false }rootcause = { workspace = true }tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/crates/graphql_initiative/src/test/access.rs b/crates/graphql_initiative/src/test/access.rsindex 4e0870a2b6..122d53cdba 100644--- a/crates/graphql_initiative/src/test/access.rs+++ b/crates/graphql_initiative/src/test/access.rs@@ -47,7 +47,14 @@ impl InitiativeService for ReceiptService {) -> Result<InitiativeDetail, InitiativeError> {unreachable!("unexpected domain call")}-+ async fn create_attributed(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateInitiativeRequest,+ attribution: activity::Attribution,+ ) -> Result<InitiativeDetail, InitiativeError> {+ unreachable!("unexpected domain call")+ }async fn internal_get_basic(&self,id: InitiativeId,diff --git a/crates/initiative/Cargo.toml b/crates/initiative/Cargo.tomlindex 42b8a167f5..57f7960a66 100644--- a/crates/initiative/Cargo.toml+++ b/crates/initiative/Cargo.toml@@ -30,11 +30,14 @@ postgres = [properties = { path = "../properties", optional = true, default-features = false }system_properties = { path = "../system_properties", optional = true }models_properties = { path = "../models_properties", optional = true }+activity = { path = "../activity", default-features = false }axum = { workspace = true, optional = true }chrono = { workspace = true, features = ["serde"] }entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }+macro_event_broker = { path = "../macro_event_broker", default-features = false }+macro_event_topics = { path = "../macro_event_topics" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid", optional = true }model-entity = { path = "../model-entity", optional = true }@@ -54,6 +57,8 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }mockall = { workspace = true }[dev-dependencies]+activity = { path = "../activity", default-features = false, features = ["outbound"] }+entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }anyhow = { workspace = true }http-body-util = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/crates/initiative/src/domain.rs b/crates/initiative/src/domain.rsindex 5d5bd92574..2e024aca86 100644--- a/crates/initiative/src/domain.rs+++ b/crates/initiative/src/domain.rs@@ -1,15 +1,20 @@//! Domain layer for initiatives.+pub mod activity;#[cfg(feature = "ports")]pub mod assignees;+pub mod events;+#[cfg(feature = "ports")]+pub mod history;+#[cfg(feature = "ports")]+pub mod lookup;pub mod models;#[cfg(feature = "ports")]+pub mod personal_activity;+#[cfg(feature = "ports")]pub mod ports;pub mod reads;#[cfg(feature = "ports")]pub mod resources;#[cfg(feature = "ports")]pub mod service;--#[cfg(feature = "ports")]-pub mod lookup;diff --git a/crates/initiative/src/domain/activity.rs b/crates/initiative/src/domain/activity.rsnew file mode 100644index 0000000000..3ea4f60540--- /dev/null+++ b/crates/initiative/src/domain/activity.rs@@ -0,0 +1,113 @@+//! Initiative facts projected into the shared, replay-safe activity model.++#[cfg(test)]+mod test;++use activity::{+ Action, Activity, ActivitySource, CommonAction, DomainActivity, EntityType, Ingest,+ InitiativeTaskChange,+};+use uuid::Uuid;++use super::events::{InitiativeChange, InitiativeTopicEvent};++enum MembershipActivity {+ Added {+ initiative_id: String,+ task_id: String,+ },+ Removed {+ initiative_id: String,+ task_id: String,+ },+}++impl DomainActivity for MembershipActivity {+ const ENTITY_TYPE: EntityType = EntityType::Initiative;+ fn entity_id(&self) -> &str {+ match self {+ Self::Added { initiative_id, .. } | Self::Removed { initiative_id, .. } => {+ initiative_id+ }+ }+ }+ fn into_action(self) -> Action {+ match self {+ Self::Added { task_id, .. } => Action::TaskAdded(InitiativeTaskChange { task_id }),+ Self::Removed { task_id, .. } => Action::TaskRemoved(InitiativeTaskChange { task_id }),+ }+ }+}++fn lifecycle(event_id: Uuid, change: &InitiativeChange, action: CommonAction) -> Ingest {+ let Some(attribution) = &change.attribution else {+ return Ingest::Ignore;+ };+ Ingest::Insert(vec![Activity::common(+ event_id,+ 0,+ attribution.actor.clone(),+ attribution.on_behalf_of.clone(),+ EntityType::Initiative,+ change.initiative_id.to_string(),+ action,+ change.occurred_at,+ )])+}++impl ActivitySource for InitiativeTopicEvent {+ fn ingest(&self, event_id: Uuid) -> Ingest {+ match self {+ Self::Created(change) => lifecycle(event_id, change, CommonAction::Created),+ Self::Updated(change) => lifecycle(event_id, change, CommonAction::Edited),+ Self::Purged { initiative_id } => {+ Ingest::Purge(vec![(EntityType::Initiative, initiative_id.to_string())])+ }+ Self::TasksChanged(changed) => {+ let Some(attribution) = &changed.attribution else {+ return Ingest::Ignore;+ };+ let mut rows = Vec::new();+ // At most 100 changes per service command; source/removal is always the+ // first ordinal and destination/addition the second, including replays.+ for (index, change) in changed.changes.iter().enumerate() {+ if change.from == change.to {+ continue;+ }+ let ordinal = u32::try_from(index).expect("bounded task batch") * 2;+ if let Some(source) = change.from {+ rows.push(Activity::from_domain(+ event_id,+ ordinal,+ attribution.actor.clone(),+ attribution.on_behalf_of.clone(),+ MembershipActivity::Removed {+ initiative_id: source.to_string(),+ task_id: change.task_id.clone(),+ },+ changed.occurred_at,+ ));+ }+ if let Some(destination) = change.to {+ rows.push(Activity::from_domain(+ event_id,+ ordinal + 1,+ attribution.actor.clone(),+ attribution.on_behalf_of.clone(),+ MembershipActivity::Added {+ initiative_id: destination.to_string(),+ task_id: change.task_id.clone(),+ },+ changed.occurred_at,+ ));+ }+ }+ if rows.is_empty() {+ Ingest::Ignore+ } else {+ Ingest::Insert(rows)+ }+ }+ }+ }+}diff --git a/crates/initiative/src/domain/activity/test.rs b/crates/initiative/src/domain/activity/test.rsnew file mode 100644index 0000000000..8dfa282b18--- /dev/null+++ b/crates/initiative/src/domain/activity/test.rs@@ -0,0 +1,81 @@+use super::super::{+ events::{+ InitiativeChange, InitiativeEventActor, InitiativeTasksChanged, InitiativeTopicEvent,+ TaskMembershipChange,+ },+ models::InitiativeId,+};+use activity::{ActivitySource, Actor, Ingest};+use chrono::{TimeZone, Utc};++fn id(value: u128) -> InitiativeId {+ InitiativeId::from_uuid(uuid::Uuid::from_u128(value))+}+fn actor() -> Option<InitiativeEventActor> {+ Some(InitiativeEventActor {+ actor: Actor::try_from("macro|[email protected]".to_string()).unwrap(),+ on_behalf_of: None,+ })+}+fn time() -> chrono::DateTime<Utc> {+ Utc.with_ymd_and_hms(2026, 9, 22, 12, 0, 0).unwrap()+}++#[test]+fn moves_record_source_and_destination_with_stable_ids() {+ let event = InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: actor(),+ occurred_at: time(),+ changes: vec![TaskMembershipChange {+ task_id: "task-1".into(),+ from: Some(id(1)),+ to: Some(id(2)),+ }],+ });+ let event_id = uuid::Uuid::from_u128(9);+ let rows = event.ingest(event_id);+ assert_eq!(rows, event.ingest(event_id));+ let Ingest::Insert(rows) = rows else {+ panic!("activities");+ };+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0].entity_id, id(1).to_string());+ assert_eq!(rows[0].action.to_columns().0, "task_removed");+ assert_eq!(rows[1].entity_id, id(2).to_string());+ assert_eq!(rows[1].action.to_columns().0, "task_added");+ assert_ne!(rows[0].id, rows[1].id);+}++#[test]+fn repeated_assignment_is_not_new_activity() {+ let event = InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: actor(),+ occurred_at: time(),+ changes: vec![TaskMembershipChange {+ task_id: "task-1".into(),+ from: Some(id(1)),+ to: Some(id(1)),+ }],+ });+ assert_eq!(event.ingest(uuid::Uuid::from_u128(9)), Ingest::Ignore);+}++#[test]+fn unattributable_mutations_are_ignored_but_purges_are_applied() {+ let change = InitiativeChange {+ initiative_id: id(1),+ attribution: None,+ occurred_at: time(),+ };+ assert_eq!(+ InitiativeTopicEvent::Created(change).ingest(uuid::Uuid::from_u128(9)),+ Ingest::Ignore+ );+ assert_eq!(+ InitiativeTopicEvent::Purged {+ initiative_id: id(1)+ }+ .ingest(uuid::Uuid::from_u128(9)),+ Ingest::Purge(vec![(activity::EntityType::Initiative, id(1).to_string())])+ );+}diff --git a/crates/initiative/src/domain/events.rs b/crates/initiative/src/domain/events.rsnew file mode 100644index 0000000000..858a4823b0--- /dev/null+++ b/crates/initiative/src/domain/events.rs@@ -0,0 +1,155 @@+//! Initiative lifecycle facts carried by the shared event broker.++use std::{future::Future, pin::Pin};++use activity::{Actor, Attribution};+use chrono::{DateTime, Utc};+use macro_event_broker::{Event, MacroEvent, TopicEvent};+use macro_event_topics::MacroInitiativesTopic;+use macro_user_id::user_id::MacroUserIdStr;+use serde::{Deserialize, Serialize};++use super::models::{AssignTasksResult, InitiativeError, InitiativeId};++/// Actor and optional delegating user retained on a committed mutation.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct InitiativeEventActor {+ /// Principal mechanically responsible for the mutation.+ pub actor: Actor<'static>,+ /// User who delegated the mutation to the actor, when any.+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,+}++impl From<Attribution> for InitiativeEventActor {+ fn from(attribution: Attribution) -> Self {+ Self {+ actor: attribution.actor(),+ on_behalf_of: attribution.on_behalf_of(),+ }+ }+}++/// The exact before/after membership committed by the repository.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct TaskMembershipChange {+ /// Task whose membership changed. Names are never stored in membership events.+ pub task_id: String,+ /// Previous initiative, absent for first assignment.+ pub from: Option<InitiativeId>,+ /// New initiative, absent for removal.+ pub to: Option<InitiativeId>,+}++/// Assignment results plus the exact committed transitions for publication.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct AssignedTasks {+ /// Public per-task outcomes.+ pub results: Vec<AssignTasksResult>,+ /// Only actual changes; repeated assignment to the same project is omitted.+ pub changes: Vec<TaskMembershipChange>,+}++/// Attributed lifecycle event for one initiative.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct InitiativeChange {+ /// Initiative that changed.+ pub initiative_id: InitiativeId,+ /// Actor, absent for unattributable internal operations.+ pub attribution: Option<InitiativeEventActor>,+ /// Time reported by the committed operation.+ pub occurred_at: DateTime<Utc>,+}++/// One atomic membership operation, including both sides of moves.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct InitiativeTasksChanged {+ /// Actor, absent for unattributable internal operations.+ pub attribution: Option<InitiativeEventActor>,+ /// Committed membership transitions in deterministic request order.+ pub changes: Vec<TaskMembershipChange>,+ /// Time of the operation.+ pub occurred_at: DateTime<Utc>,+}++/// Events owned by initiatives. Property changes use the property domain's topic.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "event_type", content = "metadata")]+pub enum InitiativeTopicEvent {+ /// A project was created.+ #[serde(rename = "initiative.created")]+ Created(InitiativeChange),+ /// A project name, sharing policy, or collaborators changed.+ #[serde(rename = "initiative.updated")]+ Updated(InitiativeChange),+ /// Tasks were assigned, moved, or removed.+ #[serde(rename = "initiative.tasks_changed")]+ TasksChanged(InitiativeTasksChanged),+ /// An initiative was permanently deleted and its history must be removed.+ #[serde(rename = "initiative.purged")]+ Purged {+ /// Deleted initiative.+ initiative_id: InitiativeId,+ },+}++impl TopicEvent for InitiativeTopicEvent {+ type Topic = MacroInitiativesTopic;+ const SCHEMA_VERSION: u8 = 1;+}++/// Broker envelope keyed by the initiative that initiated the operation.+pub struct InitiativeMacroEvent {+ key: String,+ event: Event<InitiativeTopicEvent>,+}++impl InitiativeMacroEvent {+ /// Mint one stable event envelope; broker retries reuse its event id.+ pub fn new(id: InitiativeId, event: InitiativeTopicEvent) -> Self {+ Self {+ key: id.to_string(),+ event: Event::new(event),+ }+ }+}++impl MacroEvent for InitiativeMacroEvent {+ type EventPayload = InitiativeTopicEvent;+ fn key(&self) -> &str {+ &self.key+ }+ fn event(&self) -> &Event<Self::EventPayload> {+ &self.event+ }+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {+ Self { key, event }+ }+}++/// Publication boundary called only after the initiative mutation has committed.+pub trait InitiativeEventPublisher: Send + Sync + 'static {+ /// Publish an envelope without changing its stable event identifier.+ fn publish(+ &self,+ event: InitiativeMacroEvent,+ ) -> Pin<Box<dyn Future<Output = Result<(), InitiativeError>> + Send + '_>>;+}++/// Convert a verified receipt into direct or delegated attribution.+#[cfg(feature = "ports")]+pub fn receipt_attribution<T: entity_access::domain::models::RequiredPermission>(+ receipt: &entity_access::domain::models::EntityAccessReceipt<T>,+) -> Option<InitiativeEventActor> {+ use entity_access::domain::models::EntityAccessAuth;+ match receipt.auth() {+ EntityAccessAuth::Authenticated(user) => Some(InitiativeEventActor {+ actor: Actor::new_from_user(user.clone()),+ on_behalf_of: None,+ }),+ EntityAccessAuth::Bot(bot) => Some(InitiativeEventActor {+ actor: Actor::new_from_bot(bot.bot_id()),+ on_behalf_of: bot.scope().acting_user_id().cloned(),+ }),+ EntityAccessAuth::Internal | EntityAccessAuth::Unauthenticated => None,+ }+}diff --git a/crates/initiative/src/domain/history.rs b/crates/initiative/src/domain/history.rsnew file mode 100644index 0000000000..3deeecf6e3--- /dev/null+++ b/crates/initiative/src/domain/history.rs@@ -0,0 +1,200 @@+//! Authorized, paginated project history with task references checked at read time.++use activity::domain::ports::EntityActivityReads;+use activity::{Action, ActivityRecord, RecordedAction};+use chrono::{DateTime, Utc};+use entity_access::domain::{+ models::{+ AccessError, AccessLevel, BotAccessScope, BotReceiptScope, EntityAccessAuth,+ EntityAccessReceipt, EntityType, ViewAccessLevel,+ },+ ports::EntityAccessService,+};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::{collections::HashMap, num::NonZeroU32, sync::Arc};+use uuid::Uuid;++use super::models::InitiativeError;++/// Stable cursor for project history.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct InitiativeActivityCursor {+ /// Time of the last scanned activity.+ pub occurred_at: DateTime<Utc>,+ /// Tie-breaker within the same timestamp.+ pub id: Uuid,+}++/// One authorized activity row; task names are hydrated through existing authorized task reads.+#[derive(Debug, Clone, PartialEq, Serialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct InitiativeActivityRecord {+ /// Stable record identifier, also used for realtime deduplication.+ pub id: Uuid,+ /// Principal who acted.+ pub actor_id: String,+ /// Acting user's feed identity when a bot acted on their behalf.+ pub subject_id: String,+ /// Durable activity action tag.+ pub action: String,+ /// Typed payload for known actions. Absent for unknown actions.+ pub action_payload: Option<Value>,+ /// Time of the change.+ pub occurred_at: DateTime<Utc>,+}++impl From<ActivityRecord> for InitiativeActivityRecord {+ fn from(record: ActivityRecord) -> Self {+ let (action, action_payload) = match record.action {+ RecordedAction::Known(action) => {+ let (tag, payload) = action.to_columns();+ (tag.to_string(), payload)+ }+ // A newer payload may contain references this reader cannot authorize.+ RecordedAction::Unknown { tag, .. } => (tag, None),+ };+ Self {+ id: record.id,+ actor_id: record.actor.as_ref().to_string(),+ subject_id: record.subject_id,+ action,+ action_payload,+ occurred_at: record.occurred_at,+ }+ }+}++/// History page. Access filtering can shorten records; follow nextCursor until exhausted.+#[derive(Debug, Clone, PartialEq, Serialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct InitiativeActivityPage {+ /// Visible changes in newest-first order.+ pub records: Vec<InitiativeActivityRecord>,+ /// The next raw-row boundary, including when this page had no visible task events.+ pub next_cursor: Option<InitiativeActivityCursor>,+}++/// Read service assembled with the owning activity and entity-access services.+pub struct InitiativeHistory<R, A> {+ reads: R,+ access: Arc<A>,+}++impl<R: EntityActivityReads, A: EntityAccessService> InitiativeHistory<R, A> {+ /// Compose the history reader without introducing a Soup dependency.+ pub fn new(reads: R, access: Arc<A>) -> Self {+ Self { reads, access }+ }++ /// Read project history after verifying project view access at the boundary.+ pub async fn read(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ cursor: Option<InitiativeActivityCursor>,+ limit: u32,+ ) -> Result<InitiativeActivityPage, InitiativeError> {+ if receipt.entity().entity_type != EntityType::Initiative {+ return Err(InitiativeError::BadRequest(+ "requires an initiative receipt".into(),+ ));+ }+ if !(1..=100).contains(&limit) {+ return Err(InitiativeError::BadRequest(+ "activity limit must be between 1 and 100".into(),+ ));+ }+ let page = self+ .reads+ .entity_feed(+ EntityType::Initiative,+ &receipt.entity().entity_id,+ cursor.map(|cursor| (cursor.occurred_at, cursor.id)),+ NonZeroU32::new(limit).expect("validated limit"),+ )+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?;+ let mut visibility = HashMap::new();+ let mut records = Vec::new();+ for record in page.records {+ if let RecordedAction::Known(Action::TaskAdded(change) | Action::TaskRemoved(change)) =+ &record.action+ {+ let allowed = if let Some(allowed) = visibility.get(&change.task_id) {+ *allowed+ } else {+ let allowed = self.task_visible(&receipt, &change.task_id).await?;+ visibility.insert(change.task_id.clone(), allowed);+ allowed+ };+ if !allowed {+ continue;+ }+ }+ records.push(record.into());+ }+ Ok(InitiativeActivityPage {+ records,+ next_cursor: page+ .next+ .map(|(occurred_at, id)| InitiativeActivityCursor { occurred_at, id }),+ })+ }++ async fn task_visible(+ &self,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+ task_id: &str,+ ) -> Result<bool, InitiativeError> {+ let result = match receipt.auth() {+ EntityAccessAuth::Authenticated(user) => self+ .access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ user,+ None,+ task_id,+ EntityType::Document,+ )+ .await+ .map(|_| ()),+ EntityAccessAuth::Bot(bot) => {+ let scope = match bot.scope() {+ BotReceiptScope::User { acting_user } => {+ BotAccessScope::user(acting_user.clone())+ }+ BotReceiptScope::Team { team_id } => BotAccessScope::Team { team_id: *team_id },+ BotReceiptScope::Channel { .. } => return Ok(false),+ };+ self.access+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ bot.bot_id(),+ scope,+ task_id,+ EntityType::Document,+ )+ .await+ .map(|_| ())+ }+ EntityAccessAuth::Unauthenticated => self+ .access+ .check_public_access(task_id, EntityType::Document, AccessLevel::View)+ .await+ .map(|_| ()),+ EntityAccessAuth::Internal => return Ok(true),+ };+ match result {+ Ok(()) => Ok(true),+ Err(+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_)+ | AccessError::BadRequest(_),+ ) => Ok(false),+ Err(error) => Err(error.into()),+ }+ }+}diff --git a/crates/initiative/src/domain/personal_activity.rs b/crates/initiative/src/domain/personal_activity.rsnew file mode 100644index 0000000000..6075ca6135--- /dev/null+++ b/crates/initiative/src/domain/personal_activity.rs@@ -0,0 +1,170 @@+//! Current project visibility for personal activity surfaces.+//!+//! A task move may remove it from a project the actor has never been able to+//! view. The project keeps that activity, but the actor's personal feed must+//! not disclose its identifier. This wrapper applies the same policy after+//! access is revoked and keeps raw cursors stable when rows are filtered.++use super::models::InitiativeError;+use activity::domain::ports::{ActivityFeedPage, ActivityRange, ActivityReads, EntityActivityMap};+use activity::{ActivityOverview, ActivityRecord, ActivityWindow, EntityType};+use chrono::{DateTime, Utc};+use entity_access::domain::{+ models::{AccessError, ViewAccessLevel},+ ports::EntityAccessService,+};+use macro_user_id::user_id::MacroUserIdStr;+use std::{collections::HashMap, num::NonZeroU32, sync::Arc};+use uuid::Uuid;++/// Activity reads decorated with project-owned visibility policy.+pub struct ProjectVisibleActivityReads<R, A> {+ reads: R,+ access: Arc<A>,+}++impl<R, A> ProjectVisibleActivityReads<R, A> {+ /// Compose using the owning activity reader and access service.+ pub fn new(reads: R, access: Arc<A>) -> Self {+ Self { reads, access }+ }+}++impl<R, A: EntityAccessService> ProjectVisibleActivityReads<R, A> {+ async fn visible(+ &self,+ viewer: &MacroUserIdStr<'_>,+ entity_type: EntityType,+ entity_id: &str,+ cache: &mut HashMap<String, bool>,+ ) -> Result<bool, InitiativeError> {+ if entity_type != EntityType::Initiative {+ return Ok(true);+ }+ if let Some(visible) = cache.get(entity_id) {+ return Ok(*visible);+ }+ let allowed = match self+ .access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ viewer,+ None,+ entity_id,+ EntityType::Initiative,+ )+ .await+ {+ Ok(_) => true,+ Err(+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_)+ | AccessError::BadRequest(_),+ ) => false,+ Err(error) => return Err(error.into()),+ };+ cache.insert(entity_id.to_owned(), allowed);+ Ok(allowed)+ }++ async fn filter(+ &self,+ subject: &str,+ records: Vec<ActivityRecord>,+ ) -> Result<Vec<ActivityRecord>, InitiativeError> {+ let viewer =+ MacroUserIdStr::parse_from_str(subject).map_err(|_| InitiativeError::Unauthorized)?;+ let mut cache = HashMap::new();+ let mut visible = Vec::with_capacity(records.len());+ for record in records {+ if self+ .visible(&viewer, record.entity_type, &record.entity_id, &mut cache)+ .await?+ {+ visible.push(record);+ }+ }+ Ok(visible)+ }+}++impl<R: ActivityReads + Send + Sync, A: EntityAccessService> ActivityReads+ for ProjectVisibleActivityReads<R, A>+{+ type Err = InitiativeError;++ async fn subject_feed(+ &self,+ subject_id: &str,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ limit: NonZeroU32,+ ) -> Result<ActivityFeedPage, Self::Err> {+ let page = self+ .reads+ .subject_feed(subject_id, cursor, limit)+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?;+ Ok(ActivityFeedPage {+ records: self.filter(subject_id, page.records).await?,+ next: page.next,+ })+ }++ async fn subject_activity_range(+ &self,+ subject_id: &str,+ from: DateTime<Utc>,+ to: DateTime<Utc>,+ limit: NonZeroU32,+ ) -> Result<ActivityRange, Self::Err> {+ let range = self+ .reads+ .subject_activity_range(subject_id, from, to, limit)+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?;+ Ok(ActivityRange {+ records: self.filter(subject_id, range.records).await?,+ truncated: range.truncated,+ })+ }++ async fn subject_overview(+ &self,+ subject_id: &str,+ window: ActivityWindow,+ ) -> Result<ActivityOverview, Self::Err> {+ let overview = self+ .reads+ .subject_overview(subject_id, window)+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?;+ let viewer = MacroUserIdStr::parse_from_str(subject_id)+ .map_err(|_| InitiativeError::Unauthorized)?;+ let mut cache = HashMap::new();+ let mut entities = Vec::new();+ for rank in &overview.top_entities {+ if self+ .visible(&viewer, rank.entity_type, &rank.entity_id, &mut cache)+ .await?+ {+ entities.push(rank.clone());+ }+ }+ // Daily totals count the user's own actions, including those whose target+ // can no longer be opened. Entity references always require current access.+ ActivityOverview::new(overview.window.clone(), overview.days.clone(), entities)+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))+ }++ async fn entity_activity(+ &self,+ keys: &[(EntityType, String)],+ per_entity_limit: u32,+ ) -> Result<EntityActivityMap, Self::Err> {+ // Entity edges are reached through already-authorized entity reads.+ self.reads+ .entity_activity(keys, per_entity_limit)+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))+ }+}diff --git a/crates/initiative/src/domain/ports.rs b/crates/initiative/src/domain/ports.rsindex 48a378c7b9..1c8eec7dce 100644--- a/crates/initiative/src/domain/ports.rs+++ b/crates/initiative/src/domain/ports.rs@@ -12,11 +12,12 @@ use models_permissions::share_permission::team_share::TeamShareCreation;use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};use std::collections::HashMap;+use crate::domain::events::{AssignedTasks, TaskMembershipChange};use crate::domain::models::{- AssignTasksResponse, AssignTasksResult, CreateInitiativeRepoArgs, CreateInitiativeRequest,- DescriptionDocumentId, InitiativeBasic, InitiativeDetail, InitiativeError, InitiativeId,- InitiativeList, LockstepTeamShareFacts, NewDescriptionDocument, TaskAssignment,- UpdateInitiativeRepoArgs, UpdateInitiativeRequest,+ AssignTasksResponse, CreateInitiativeRepoArgs, CreateInitiativeRequest, DescriptionDocumentId,+ InitiativeBasic, InitiativeDetail, InitiativeError, InitiativeId, InitiativeList,+ LockstepTeamShareFacts, NewDescriptionDocument, TaskAssignment, UpdateInitiativeRepoArgs,+ UpdateInitiativeRequest,};/// Outbound port for the description document's lifecycle.@@ -102,17 +103,20 @@ pub trait InitiativeRepo: Send + Sync + 'static {&self,id: InitiativeId,task_ids: Vec<String>,- ) -> impl Future<Output = Result<Vec<AssignTasksResult>, Self::Err>> + Send;+ ) -> impl Future<Output = Result<AssignedTasks, Self::Err>> + Send;/// Remove one task from the initiative.fn unassign_task(&self,id: InitiativeId,task_id: &str,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<TaskMembershipChange>, Self::Err>> + Send;/// Clear any initiative association for a task. Already unassigned tasks succeed.- fn clear_task(&self, task_id: &str) -> impl Future<Output = Result<(), Self::Err>> + Send;+ fn clear_task(+ &self,+ task_id: &str,+ ) -> impl Future<Output = Result<Option<TaskMembershipChange>, Self::Err>> + Send;/// Grant assignees edit access to the initiative and description in one transaction,/// recording non-owner recipients as collaborators without removing anyone or@@ -166,6 +170,15 @@ pub trait InitiativeService: Send + Sync + 'static {request: CreateInitiativeRequest,) -> impl Future<Output = Result<InitiativeDetail, InitiativeError>> + Send;+ /// Create for a trusted principal. Direct users must be the owner; delegated+ /// bots must act for that owner. HTTP bodies and tool inputs never provide attribution.+ fn create_attributed(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateInitiativeRequest,+ attribution: activity::Attribution,+ ) -> impl Future<Output = Result<InitiativeDetail, InitiativeError>> + Send;+/// Load identity without an access receipt. For internal callers only.fn internal_get_basic(&self,diff --git a/crates/initiative/src/domain/service.rs b/crates/initiative/src/domain/service.rsindex e3b14d5eef..34c0287c6e 100644--- a/crates/initiative/src/domain/service.rs+++ b/crates/initiative/src/domain/service.rs@@ -3,6 +3,11 @@#[cfg(test)]mod test;+use crate::domain::events::{+ AssignedTasks, InitiativeChange, InitiativeEventPublisher, InitiativeMacroEvent,+ InitiativeTasksChanged, InitiativeTopicEvent, receipt_attribution,+};+use chrono::Utc;use std::collections::{HashMap, HashSet};use std::str::FromStr;use std::sync::Arc;@@ -38,6 +43,7 @@ pub struct InitiativeServiceImpl<R, D> {repo: R,description_documents: D,resources: Arc<dyn InitiativeResources>,+ events: Option<Arc<dyn InitiativeEventPublisher>>,}impl<R, D> std::fmt::Debug for InitiativeServiceImpl<R, D> {@@ -57,6 +63,24 @@ whererepo,description_documents,resources,+ events: None,+ }+ }++ /// Attach the host's shared initiative event publisher.+ pub fn with_event_publisher(mut self, publisher: Arc<dyn InitiativeEventPublisher>) -> Self {+ self.events = Some(publisher);+ self+ }++ async fn publish(&self, id: InitiativeId, event: InitiativeTopicEvent) {+ if let Some(publisher) = &self.events+ && let Err(error) = publisher+ .publish(InitiativeMacroEvent::new(id, event))+ .await+ {+ // The write has committed. Returning an error would invite a duplicate mutation.+ tracing::error!(?error, %id, "failed to publish committed initiative event");}}@@ -144,6 +168,34 @@ whereuser_id: &MacroUserIdStr<'_>,request: CreateInitiativeRequest,) -> Result<InitiativeDetail, InitiativeError> {+ self.create_attributed(+ user_id,+ request,+ activity::Attribution::direct(activity::Actor::new_from_user(+ user_id.clone().into_owned(),+ )),+ )+ .await+ }++ #[tracing::instrument(err, skip_all)]+ async fn create_attributed(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateInitiativeRequest,+ attribution: activity::Attribution,+ ) -> Result<InitiativeDetail, InitiativeError> {+ let authorized = match &attribution {+ activity::Attribution::Direct { actor } => {+ actor.as_user().is_some_and(|actor| actor == user_id)+ }+ activity::Attribution::Delegated { actor, subject } => {+ actor.as_bot().is_some() && subject == user_id+ }+ };+ if !authorized {+ return Err(InitiativeError::Unauthorized);+ }let name = normalize_name(&request.name)?;let prefill_markdown = normalize_description(request.description)?;let owner_id = user_id.clone().into_owned();@@ -191,12 +243,22 @@ whereif self.repo.delete(id).await.inspect_err(|cleanup| {tracing::error!(error=?cleanup, %id, "failed to compensate initiative initialization");}).is_ok() {+ self.publish(id, InitiativeTopicEvent::Purged { initiative_id: id })+ .await;let _ = self.description_documents.purge(description_document_id).await.inspect_err(|cleanup| tracing::error!(error=?cleanup, %id, "failed to compensate initiative initialization"));}return Err(error);}detail.user_access_level = AccessLevel::Owner;-+ self.publish(+ id,+ InitiativeTopicEvent::Created(InitiativeChange {+ initiative_id: id,+ attribution: Some(attribution.into()),+ occurred_at: Utc::now(),+ }),+ )+ .await;Ok(detail)}Err(error) => {@@ -308,7 +370,15 @@ where}).await.map_err(Into::into)?;-+ self.publish(+ id,+ InitiativeTopicEvent::Updated(InitiativeChange {+ initiative_id: id,+ attribution: receipt_attribution(&receipt),+ occurred_at: Utc::now(),+ }),+ )+ .await;detail.user_access_level = receipt_access_level(&receipt)?;detail.task_ids = self.visible_tasks(receipt.auth(), detail.task_ids).await?;Ok(detail)@@ -341,8 +411,8 @@ where}}- let results = if candidate_ids.is_empty() {- Vec::new()+ let committed = if candidate_ids.is_empty() {+ AssignedTasks::default()} else {self.repo.assign_tasks(id, candidate_ids)@@ -350,8 +420,19 @@ where.map_err(Into::into)?};+ if !committed.changes.is_empty() {+ self.publish(+ id,+ InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: receipt_attribution(&receipt),+ changes: committed.changes,+ occurred_at: Utc::now(),+ }),+ )+ .await;+ }Ok(AssignTasksResponse {- results: merge_assign_results(&assignments, results),+ results: merge_assign_results(&assignments, committed.results),})}@@ -364,10 +445,23 @@ wherelet id = initiative_id_from_receipt(&receipt)?;validate_task_receipt(&task_receipt)?;require_same_actor(&receipt, &task_receipt)?;- self.repo+ let change = self+ .repo.unassign_task(id, &task_receipt.entity().entity_id).await- .map_err(Into::into)+ .map_err(Into::into)?;+ if let Some(change) = change {+ self.publish(+ id,+ InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: receipt_attribution(&receipt),+ changes: vec![change],+ occurred_at: Utc::now(),+ }),+ )+ .await;+ }+ Ok(())}#[tracing::instrument(err, skip_all)]@@ -376,10 +470,25 @@ wheretask_receipt: EntityAccessReceipt<EditAccessLevel>,) -> Result<(), InitiativeError> {validate_task_receipt(&task_receipt)?;- self.repo+ let change = self+ .repo.clear_task(&task_receipt.entity().entity_id).await- .map_err(Into::into)+ .map_err(Into::into)?;+ if let Some(change) = change+ && let Some(id) = change.from+ {+ self.publish(+ id,+ InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: receipt_attribution(&task_receipt),+ changes: vec![change],+ occurred_at: Utc::now(),+ }),+ )+ .await;+ }+ Ok(())}#[tracing::instrument(err, skip_all)]@@ -400,8 +509,10 @@ where) -> Result<(), InitiativeError> {let id = initiative_id_from_receipt(&receipt)?;let description_document_id = self.repo.delete(id).await.map_err(Into::into)?;-+ self.publish(id, InitiativeTopicEvent::Purged { initiative_id: id })+ .await;// Cleanup follows an authorized deletion and is not a fresh user edit.+ // Unattributed property cleanup cannot recreate history after the purge event.let cleanup_receipt = EntityAccessReceipt::try_new(EntityAccessAuth::Internal,receipt.entity().clone(),diff --git a/crates/initiative/src/domain/service/test.rs b/crates/initiative/src/domain/service/test.rsindex 3dd63119b6..32f292edc3 100644--- a/crates/initiative/src/domain/service/test.rs+++ b/crates/initiative/src/domain/service/test.rs@@ -1,6 +1,7 @@use chrono::{TimeZone, Utc};mod access;+mod events;mod reads;use entity_access::domain::models::{AccessLevel, EditAccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType,@@ -537,16 +538,19 @@ async fn assign_dedupes_enforces_cap_and_preserves_order() {.withf(|_, task_ids| task_ids == &["t1".to_string(), "t2".to_string()]).return_once(|_, _| {Box::pin(async {- Ok(vec![- AssignTasksResult {- task_id: "t1".into(),- status: AssignTaskStatus::Assigned,- },- AssignTasksResult {- task_id: "t2".into(),- status: AssignTaskStatus::Moved,- },- ])+ Ok(crate::domain::events::AssignedTasks {+ results: vec![+ AssignTasksResult {+ task_id: "t1".into(),+ status: AssignTaskStatus::Assigned,+ },+ AssignTasksResult {+ task_id: "t2".into(),+ status: AssignTaskStatus::Moved,+ },+ ],+ changes: Vec::new(),+ })})});@@ -626,7 +630,7 @@ async fn get_list_and_unassign_call_the_repo() {})});repo.expect_unassign_task()- .return_once(|_, _| Box::pin(async { Ok(()) }));+ .return_once(|_, _| Box::pin(async { Ok(None) }));let svc = service(repo);svc.internal_get_basic(initiative_id())diff --git a/crates/initiative/src/domain/service/test/access.rs b/crates/initiative/src/domain/service/test/access.rsindex 5b9d3f81de..8fb2b3e505 100644--- a/crates/initiative/src/domain/service/test/access.rs+++ b/crates/initiative/src/domain/service/test/access.rs@@ -157,7 +157,7 @@ async fn task_side_clear_needs_no_source_initiative_receipt() {repo.expect_clear_task().withf(|id| id == "task-1").times(1)- .return_once(|_| Box::pin(async { Ok(()) }));+ .return_once(|_| Box::pin(async { Ok(None) }));service(repo).clear_task(task_receipt(OWNER, "task-1")).awaitdiff --git a/crates/initiative/src/domain/service/test/events.rs b/crates/initiative/src/domain/service/test/events.rsnew file mode 100644index 0000000000..ede989c8f8--- /dev/null+++ b/crates/initiative/src/domain/service/test/events.rs@@ -0,0 +1,98 @@+use super::*;+use crate::domain::events::{+ AssignedTasks, InitiativeEventPublisher, InitiativeMacroEvent, InitiativeTopicEvent,+ TaskMembershipChange,+};+use macro_event_broker::MacroEvent;+use std::{+ future::Future,+ pin::Pin,+ sync::{Arc, Mutex},+};++#[derive(Default)]+pub(super) struct Events(pub(super) Mutex<Vec<InitiativeTopicEvent>>);++impl InitiativeEventPublisher for Events {+ fn publish(+ &self,+ event: InitiativeMacroEvent,+ ) -> Pin<Box<dyn Future<Output = Result<(), InitiativeError>> + Send + '_>> {+ Box::pin(async move {+ self.0.lock().unwrap().push(event.event().event.clone());+ Ok(())+ })+ }+}++#[tokio::test]+async fn assignment_publishes_only_committed_membership_changes() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_assign_tasks().times(1).return_once(|id, _| {+ Box::pin(async move {+ Ok(AssignedTasks {+ results: vec![AssignTasksResult {+ task_id: "task-1".into(),+ status: AssignTaskStatus::Assigned,+ }],+ changes: vec![TaskMembershipChange {+ task_id: "task-1".into(),+ from: None,+ to: Some(id),+ }],+ })+ })+ });+ let events = Arc::new(Events::default());+ let svc = service(repo).with_event_publisher(events.clone());+ svc.assign_tasks(edit_receipt(), vec![assignment("task-1")])+ .await+ .unwrap();+ let events = events.0.lock().unwrap();+ let [InitiativeTopicEvent::TasksChanged(change)] = events.as_slice() else {+ panic!("expected one committed membership event")+ };+ assert_eq!(change.changes[0].task_id, "task-1");+ assert!(change.attribution.is_some());+}++#[tokio::test]+async fn repeated_assignment_has_no_activity() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_assign_tasks()+ .times(1)+ .return_once(|_, _| Box::pin(async { Ok(AssignedTasks::default()) }));+ let events = Arc::new(Events::default());+ service(repo)+ .with_event_publisher(events.clone())+ .assign_tasks(edit_receipt(), vec![assignment("task-1")])+ .await+ .unwrap();+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn committed_deletion_purges_activity_even_when_description_cleanup_fails() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_delete()+ .times(1)+ .return_once(|_| Box::pin(async { Ok(description_document_id()) }));+ let mut documents = MockInitiativeDescriptionDocuments::new();+ documents.expect_purge().times(1).return_once(|_| {+ Box::pin(async {+ Err(InitiativeError::Internal(rootcause::report!(+ "storage unavailable"+ )))+ })+ });+ let events = Arc::new(Events::default());+ let result = service_with_documents(repo, documents)+ .with_event_publisher(events.clone())+ .delete(owner_receipt())+ .await;+ assert!(result.is_err());+ assert!(matches!(+ events.0.lock().unwrap().as_slice(),+ [InitiativeTopicEvent::Purged { .. }]+ ));+}diff --git a/crates/initiative/src/domain/service/test/reads.rs b/crates/initiative/src/domain/service/test/reads.rsindex 0f3d302aa5..ca192789ea 100644--- a/crates/initiative/src/domain/service/test/reads.rs+++ b/crates/initiative/src/domain/service/test/reads.rs@@ -147,6 +147,7 @@ async fn failed_property_initialization_compensates_project_and_description() {.withf(|id| *id == description_document_id()).times(1).return_once(|_| Box::pin(async { Ok(()) }));+ let events = Arc::new(super::events::Events::default());let svc = InitiativeServiceImpl::new(repo,documents,@@ -154,7 +155,53 @@ async fn failed_property_initialization_compensates_project_and_description() {fail_initialization: true,..Default::default()}),- );+ )+ .with_event_publisher(events.clone());+ assert!(matches!(+ svc.create(+ &user(OWNER),+ CreateInitiativeRequest {+ name: "Launch".into(),+ ..Default::default()+ }+ )+ .await,+ Err(InitiativeError::Internal(_))+ ));+ assert!(matches!(+ events.0.lock().unwrap().as_slice(),+ [crate::domain::events::InitiativeTopicEvent::Purged { .. }]+ ));+}++#[tokio::test]+async fn failed_initialization_compensation_does_not_purge_a_remaining_project() {+ let mut repo = MockInitiativeRepo::new();+ repo.expect_get_team_default_link_share()+ .return_once(|_| Box::pin(async { Ok(None) }));+ repo.expect_create()+ .return_once(|_, _, _| Box::pin(async { Ok(detail(Vec::new())) }));+ repo.expect_delete().times(1).return_once(|_| {+ Box::pin(async {+ Err(InitiativeError::Internal(rootcause::report!(+ "delete failed"+ )))+ })+ });+ let mut documents = MockInitiativeDescriptionDocuments::new();+ documents+ .expect_create()+ .return_once(|_| Box::pin(async { Ok(description_document_id()) }));+ let events = Arc::new(super::events::Events::default());+ let svc = InitiativeServiceImpl::new(+ repo,+ documents,+ Arc::new(FakeResources {+ fail_initialization: true,+ ..Default::default()+ }),+ )+ .with_event_publisher(events.clone());assert!(matches!(svc.create(&user(OWNER),@@ -166,6 +213,7 @@ async fn failed_property_initialization_compensates_project_and_description() {.await,Err(InitiativeError::Internal(_))));+ assert!(events.0.lock().unwrap().is_empty());}#[tokio::test]diff --git a/crates/initiative/src/inbound/axum_router/test.rs b/crates/initiative/src/inbound/axum_router/test.rsindex bd300773c9..7c5626e452 100644--- a/crates/initiative/src/inbound/axum_router/test.rs+++ b/crates/initiative/src/inbound/axum_router/test.rs@@ -331,6 +331,14 @@ impl InitiativeService for FakeInitiativeService {Err(InitiativeError::NotFound)}+ async fn create_attributed(+ &self,+ user_id: &MacroUserIdStr<'_>,+ request: CreateInitiativeRequest,+ _attribution: activity::Attribution,+ ) -> Result<InitiativeDetail, InitiativeError> {+ self.create(user_id, request).await+ }async fn page(&self,_user_id: &MacroUserIdStr<'_>,diff --git a/crates/initiative/src/outbound.rs b/crates/initiative/src/outbound.rsindex 0f42d8f212..2313258554 100644--- a/crates/initiative/src/outbound.rs+++ b/crates/initiative/src/outbound.rs@@ -8,6 +8,7 @@ mod pg_initiative_repo;#[cfg(feature = "postgres")]pub use pg_initiative_repo::PgInitiativeRepo;+pub mod event_publisher;#[cfg(feature = "resources")]mod assignees;diff --git a/crates/initiative/src/outbound/event_publisher.rs b/crates/initiative/src/outbound/event_publisher.rsnew file mode 100644index 0000000000..fbe6170af9--- /dev/null+++ b/crates/initiative/src/outbound/event_publisher.rs@@ -0,0 +1,37 @@+//! Initiative event publication through Macro's shared event broker.++use macro_event_broker::MacroEventBroker;+use std::{future::Future, pin::Pin};++use crate::domain::{+ events::{InitiativeEventPublisher, InitiativeMacroEvent},+ models::InitiativeError,+};++/// Adapter for the broker assembled by the host composition root.+pub struct BrokerInitiativeEventPublisher<B> {+ broker: B,+}++impl<B> BrokerInitiativeEventPublisher<B> {+ /// Compose from the host's shared broker.+ pub fn new(broker: B) -> Self {+ Self { broker }+ }+}++impl<B: MacroEventBroker + 'static> InitiativeEventPublisher for BrokerInitiativeEventPublisher<B> {+ fn publish(+ &self,+ event: InitiativeMacroEvent,+ ) -> Pin<Box<dyn Future<Output = Result<(), InitiativeError>> + Send + '_>> {+ Box::pin(async move {+ self.broker+ .send_event(&event)+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?+ .await+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))?+ .map_err(|error| InitiativeError::Internal(rootcause::report!(error).into()))+ })+ }+}diff --git a/crates/initiative/src/outbound/pg_initiative_repo.rs b/crates/initiative/src/outbound/pg_initiative_repo.rsindex 93d47dfe80..09a6b79abf 100644--- a/crates/initiative/src/outbound/pg_initiative_repo.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo.rs@@ -23,9 +23,10 @@ use share_permission_db_utils::team_share::TeamShareError;use sqlx::postgres::PgDatabaseError;use sqlx::{Executor, PgPool, Postgres};+use crate::domain::events::{AssignedTasks, TaskMembershipChange};use crate::domain::models::{- AssignTasksResult, CreateInitiativeRepoArgs, DescriptionDocumentId, InitiativeBasic,- InitiativeDetail, InitiativeError, InitiativeId, InitiativeList, LockstepTeamShareFacts,+ CreateInitiativeRepoArgs, DescriptionDocumentId, InitiativeBasic, InitiativeDetail,+ InitiativeError, InitiativeId, InitiativeList, LockstepTeamShareFacts,UpdateInitiativeRepoArgs,};use crate::domain::ports::InitiativeRepo;@@ -132,17 +133,21 @@ impl InitiativeRepo for PgInitiativeRepo {&self,id: InitiativeId,task_ids: Vec<String>,- ) -> Result<Vec<AssignTasksResult>, Self::Err> {+ ) -> Result<AssignedTasks, Self::Err> {tasks::assign_tasks(&self.pool, id, task_ids).await}#[tracing::instrument(err, skip(self))]- async fn unassign_task(&self, id: InitiativeId, task_id: &str) -> Result<(), Self::Err> {+ async fn unassign_task(+ &self,+ id: InitiativeId,+ task_id: &str,+ ) -> Result<Option<TaskMembershipChange>, Self::Err> {tasks::unassign_task(&self.pool, id, task_id).await}#[tracing::instrument(err, skip(self))]- async fn clear_task(&self, task_id: &str) -> Result<(), Self::Err> {+ async fn clear_task(&self, task_id: &str) -> Result<Option<TaskMembershipChange>, Self::Err> {tasks::clear_task(&self.pool, task_id).await}diff --git a/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs b/crates/initiative/src/outbound/pg_initiative_repo/tasks.rsindex 4a57f32c61..4813578b26 100644--- a/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo/tasks.rs@@ -4,15 +4,16 @@ use sqlx::{PgPool, Postgres, Transaction};use uuid::Uuid;use super::{AdapterError, map_sqlx};+use crate::domain::events::{AssignedTasks, TaskMembershipChange};use crate::domain::models::{AssignTaskStatus, AssignTasksResult, InitiativeError, InitiativeId};pub(super) async fn assign_tasks(pool: &PgPool,id: InitiativeId,task_ids: Vec<String>,-) -> Result<Vec<AssignTasksResult>, InitiativeError> {+) -> Result<AssignedTasks, InitiativeError> {if task_ids.is_empty() {- return Ok(Vec::new());+ return Ok(AssignedTasks::default());}let mut tx = pool@@ -96,20 +97,32 @@ pub(super) async fn assign_tasks(.map_err(AdapterError::Sqlx).map_err(map_sqlx)?;- Ok(task_ids+ let changes = task_ids+ .iter()+ .filter(|task_id| {+ returned.contains(*task_id) && prior.get(*task_id) != Some(&initiative_id)+ })+ .map(|task_id| TaskMembershipChange {+ task_id: task_id.clone(),+ from: prior.get(task_id).copied().map(InitiativeId::from_uuid),+ to: Some(id),+ })+ .collect();+ let results = task_ids.into_iter().map(|task_id| AssignTasksResult {status: assign_status_for(&task_id, &prior, &returned, initiative_id),task_id,})- .collect())+ .collect();+ Ok(AssignedTasks { results, changes })}pub(super) async fn unassign_task(pool: &PgPool,id: InitiativeId,task_id: &str,-) -> Result<(), InitiativeError> {+) -> Result<Option<TaskMembershipChange>, InitiativeError> {let mut tx = pool.begin().await@@ -151,11 +164,18 @@ pub(super) async fn unassign_task(.await.map_err(AdapterError::Sqlx).map_err(map_sqlx)?;- Ok(())+ Ok(Some(TaskMembershipChange {+ task_id: task_id.to_string(),+ from: Some(id),+ to: None,+ }))}-pub(super) async fn clear_task(pool: &PgPool, task_id: &str) -> Result<(), InitiativeError> {- sqlx::query_scalar!(+pub(super) async fn clear_task(+ pool: &PgPool,+ task_id: &str,+) -> Result<Option<TaskMembershipChange>, InitiativeError> {+ let removed = sqlx::query_scalar!(r#"WITH removed AS (DELETE FROM task_initiative@@ -173,7 +193,11 @@ pub(super) async fn clear_task(pool: &PgPool, task_id: &str) -> Result<(), Initi.await.map_err(AdapterError::Sqlx).map_err(map_sqlx)?;- Ok(())+ Ok(removed.map(|id| TaskMembershipChange {+ task_id: task_id.to_string(),+ from: Some(InitiativeId::from_uuid(id)),+ to: None,+ }))}async fn lock_initiative(diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test.rs b/crates/initiative/src/outbound/pg_initiative_repo/test.rsindex 23ba76ec18..80cf701907 100644--- a/crates/initiative/src/outbound/pg_initiative_repo/test.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo/test.rs@@ -1,6 +1,7 @@use entity_access_db_utils::AccessLevel;mod access;+mod history;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;@@ -947,6 +948,7 @@ async fn assign_tasks_moves_and_reports_non_tasks(pool: PgPool) -> anyhow::Resul.await?;assert_eq!(first_results+ .results.iter().map(|result| result.status).collect::<Vec<_>>(),@@ -959,9 +961,23 @@ async fn assign_tasks_moves_and_reports_non_tasks(pool: PgPool) -> anyhow::Resulvec![task_a.clone(), not_a_task.clone(), missing.clone()],).await?;- assert_eq!(second_results[0].status, AssignTaskStatus::Moved);- assert_eq!(second_results[1].status, AssignTaskStatus::NotATask);- assert_eq!(second_results[2].status, AssignTaskStatus::NotATask);+ assert_eq!(second_results.results[0].status, AssignTaskStatus::Moved);+ assert_eq!(second_results.results[1].status, AssignTaskStatus::NotATask);+ assert_eq!(second_results.results[2].status, AssignTaskStatus::NotATask);+ assert_eq!(+ second_results.changes,+ vec![crate::domain::events::TaskMembershipChange {+ task_id: task_a.clone(),+ from: Some(first.id),+ to: Some(second.id)+ }]+ );+ assert!(+ repo.assign_tasks(second.id, vec![task_a.clone()])+ .await?+ .changes+ .is_empty()+ );let first_detail = repo.get_detail(first.id).await?.expect("first");let second_detail = repo.get_detail(second.id).await?.expect("second");diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test/access.rs b/crates/initiative/src/outbound/pg_initiative_repo/test/access.rsindex f90db550eb..8e8796ad73 100644--- a/crates/initiative/src/outbound/pg_initiative_repo/test/access.rs+++ b/crates/initiative/src/outbound/pg_initiative_repo/test/access.rs@@ -84,6 +84,6 @@ async fn task_side_clear_is_idempotent_and_preserves_the_task(pool: PgPool) -> aassert!(detail.updated_at > created.updated_at);// Reassignment also proves that clearing preserved the task document/subtype.let assigned = repo.assign_tasks(created.id, vec![task_id]).await?;- assert_eq!(assigned[0].status, AssignTaskStatus::Assigned);+ assert_eq!(assigned.results[0].status, AssignTaskStatus::Assigned);Ok(())}diff --git a/crates/initiative/src/outbound/pg_initiative_repo/test/history.rs b/crates/initiative/src/outbound/pg_initiative_repo/test/history.rsnew file mode 100644index 0000000000..9442bdb6e9--- /dev/null+++ b/crates/initiative/src/outbound/pg_initiative_repo/test/history.rs@@ -0,0 +1,83 @@+use super::*;+use crate::domain::{+ events::{+ InitiativeEventActor, InitiativeTasksChanged, InitiativeTopicEvent, TaskMembershipChange,+ },+ history::InitiativeHistory,+};+use activity::domain::ports::ActivityRepo;+use activity::outbound::pg_activity_repo::PgActivityRepo;+use activity::{ActivitySource, Actor, EntityType, Ingest};+use entity_access::{+ domain::{+ models::ViewAccessLevel, ports::EntityAccessService, service::EntityAccessServiceImpl,+ },+ outbound::PgAccessRepository,+};+use std::sync::Arc;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn project_history_filters_task_events_until_task_access_is_granted(+ pool: PgPool,+) -> anyhow::Result<()> {+ insert_user(&pool, OWNER).await?;+ insert_user(&pool, MEMBER).await?;+ let task_id = Uuid::now_v7().to_string();+ insert_document(&pool, &task_id, OWNER, true).await?;+ let repo = repo(pool.clone());+ let created = repo+ .create(+ create_args(&pool, OWNER, "Shared project", &[MEMBER]).await?,+ share_off(),+ TeamShareCreation::Unshared,+ )+ .await?;+ let topic_event = InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: Some(InitiativeEventActor {+ actor: Actor::new_from_user(user(OWNER)),+ on_behalf_of: None,+ }),+ occurred_at: chrono::Utc::now(),+ changes: vec![TaskMembershipChange {+ task_id: task_id.clone(),+ from: None,+ to: Some(created.id),+ }],+ });+ let Ingest::Insert(rows) = topic_event.ingest(Uuid::now_v7()) else {+ panic!("membership activity");+ };+ let activity_repo = PgActivityRepo::new(pool.clone());+ activity_repo.insert_activities(&rows).await?;+ let access = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(+ pool.clone(),+ )));+ let receipt = access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &user(MEMBER),+ None,+ &created.id.to_string(),+ EntityType::Initiative,+ )+ .await?;+ let history = InitiativeHistory::new(activity_repo, access);+ let hidden = history.read(receipt.clone(), None, 50).await?;+ assert!(hidden.records.is_empty());++ entity_access_db_utils::upsert_user_entity_access_bulk(+ &pool,+ &[user(MEMBER)],+ &Uuid::parse_str(&task_id)?,+ EntityType::Document,+ AccessLevel::View,+ )+ .await?;+ let visible = history.read(receipt, None, 50).await?;+ assert_eq!(visible.records.len(), 1);+ assert_eq!(visible.records[0].action, "task_added");+ assert_eq!(+ visible.records[0].action_payload.as_ref().unwrap()["task_id"],+ task_id+ );+ Ok(())+}diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rsindex e19c1d68fa..a770779851 100644--- a/crates/macro_event_topics/src/lib.rs+++ b/crates/macro_event_topics/src/lib.rs@@ -57,6 +57,8 @@ topics! {MacroSoupRealtimeTopic => "macro.soup",/// Project lifecycle events (created, updated, deleted, restored, permanently deleted, and uploaded).MacroProjectsTopic => "macro.projects",+ /// Initiative lifecycle and task membership changes.+ MacroInitiativesTopic => "macro.initiatives",/// Property definition, option, and entity property value mutation events.MacroPropertiesTopic => "macro.properties",/// Team lifecycle, invite, and membership events.diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rsindex 1047efef29..59fd962742 100644--- a/crates/macro_event_topics/src/test.rs+++ b/crates/macro_event_topics/src/test.rs@@ -21,6 +21,7 @@ fn all_topic_names_includes_declared_topics() {assert!(all_topic_names().contains(&MacroDocumentsTopic::TOPIC_STR));assert!(all_topic_names().contains(&MacroSoupRealtimeTopic::TOPIC_STR));assert!(all_topic_names().contains(&MacroProjectsTopic::TOPIC_STR));+ assert!(all_topic_names().contains(&MacroInitiativesTopic::TOPIC_STR));assert!(all_topic_names().contains(&MacroPropertiesTopic::TOPIC_STR));assert!(all_topic_names().contains(&MacroTeamsTopic::TOPIC_STR));assert!(all_topic_names().contains(&MacroChannelsTopic::TOPIC_STR));diff --git a/crates/soup_realtime/Cargo.toml b/crates/soup_realtime/Cargo.tomlindex 98710a1a15..c1e4896fc9 100644--- a/crates/soup_realtime/Cargo.toml+++ b/crates/soup_realtime/Cargo.toml@@ -10,6 +10,7 @@ consumer = ["dep:chat","dep:documents","dep:email",+ "dep:initiative","dep:kafka_util","dep:models_properties","dep:projects",@@ -41,6 +42,7 @@ documents = { path = "../documents", default-features = false, features = ["servemail = { path = "../email", default-features = false, optional = true }entity_access = { path = "../entity_access", default-features = false, features = ["ports"], optional = true }futures = { workspace = true, optional = true }+initiative = { path = "../initiative", default-features = false, optional = true }kafka_util = { path = "../kafka_util", optional = true }macro_event_broker = { path = "../macro_event_broker", default-features = false }macro_event_topics = { path = "../macro_event_topics" }diff --git a/crates/soup_realtime/src/inbound/kafka_consumer.rs b/crates/soup_realtime/src/inbound/kafka_consumer.rsindex 96f2d9eb4d..f64347f9e8 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer.rs@@ -23,6 +23,7 @@ use channels::domain::{use chat::domain::events::{ChatMacroEvent, ChatTopicEvent};use documents::domain::events::{DocumentMacroEvent, DocumentTopicEvent, InteractionReason};use email::domain::events::{EmailMacroEvent, EmailTopicEvent};+use initiative::domain::events::{InitiativeMacroEvent, InitiativeTopicEvent};use kafka_util::{GroupName, KafkaEventConsumer};use macro_event_broker::{KafkaConsumerAdapter, MacroEvent as _, MacroEventCollection as _, MacroEventConsumerService,@@ -56,6 +57,7 @@ macro_event_broker::declare_topics!(EmailMacroEvent,ChannelMacroEvent,PropertyMacroEvent,+ InitiativeMacroEvent,);fn entity(entity_type: EntityType, entity_id: impl ToString) -> Entity<'static> {@@ -146,6 +148,27 @@ fn patches_from_document_event(event: &DocumentTopicEvent) -> Vec<SoupRealtimePaupdates}+fn patches_from_initiative_event(event: &InitiativeTopicEvent) -> Vec<SoupRealtimePatch> {+ match event {+ InitiativeTopicEvent::Created(change) | InitiativeTopicEvent::Updated(change) => {+ vec![update(EntityType::Initiative, change.initiative_id)]+ }+ InitiativeTopicEvent::Purged { initiative_id } => {+ vec![delete(EntityType::Initiative, initiative_id)]+ }+ InitiativeTopicEvent::TasksChanged(change) => {+ let mut patches = Vec::new();+ for membership in &change.changes {+ push_unique_update(&mut patches, EntityType::Document, &membership.task_id);+ for id in [membership.from, membership.to].into_iter().flatten() {+ push_unique_update(&mut patches, EntityType::Initiative, &id.to_string());+ }+ }+ patches+ }+ }+}+fn patches_from_project_event(event: &ProjectTopicEvent) -> Vec<SoupRealtimePatch> {let mut updates = Vec::new();match event {@@ -427,10 +450,9 @@ fn soup_entity_type_from_property(entity_type: PropertyEntityType) -> Option<EntPropertyEntityType::Document | PropertyEntityType::Task => Some(EntityType::Document),PropertyEntityType::Project => Some(EntityType::Project),PropertyEntityType::Thread => Some(EntityType::EmailThread),+ PropertyEntityType::Initiative => Some(EntityType::Initiative),// Soup channels do not expose properties, and users are not Soup items.- PropertyEntityType::Channel | PropertyEntityType::User | PropertyEntityType::Initiative => {- None- }+ PropertyEntityType::Channel | PropertyEntityType::User => None,}}@@ -449,6 +471,18 @@ fn patches_from_property_event(event: &PropertyTopicEvent) -> Vec<SoupRealtimePaPropertyTopicEvent::EntityPropertyDeleted(metadata) => {property_update(metadata.entity_type, &metadata.entity_id)}+ PropertyTopicEvent::EntityPropertiesCleared(metadata)+ if metadata.entity_type == PropertyEntityType::Initiative+ && metadata.actor_user_id.is_none()+ && metadata.actor.is_none()+ && metadata.on_behalf_of.is_none() =>+ {+ // Initiative deletion clears properties with an internal receipt after+ // publishing Purged. The topics have no shared ordering; refreshing here+ // could replace the deletion with a stale replica row. User/bot clears+ // remain ordinary property updates below.+ Vec::new()+ }PropertyTopicEvent::EntityPropertiesCleared(metadata) => {property_update(metadata.entity_type, &metadata.entity_id)}@@ -475,6 +509,9 @@ fn patches_from_event(event: &DeclaredMacroEvent) -> Vec<SoupRealtimePatch> {DeclaredMacroEvent::ChannelMacroEvent(event) => {patches_from_channel_event(&event.event().event)}+ DeclaredMacroEvent::InitiativeMacroEvent(event) => {+ patches_from_initiative_event(&event.event().event)+ }DeclaredMacroEvent::PropertyMacroEvent(event) => {patches_from_property_event(&event.event().event)}diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 077943ddc4..cbd8128375 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -121,6 +121,7 @@ fn subscribes_to_all_existing_soup_source_topics() {"macro.email","macro.channels","macro.properties",+ "macro.initiatives",]);}@@ -382,6 +383,74 @@ fn deleting_or_clearing_properties_updates_the_soup_entity() {assert_eq!(patch_entity(&cleared[0]).entity_id, company_id);}+#[test]+fn initiative_purge_cleanup_cannot_replace_the_deletion_in_either_event_order() {+ let id = Uuid::now_v7();+ let purged = InitiativeTopicEvent::Purged {+ initiative_id: initiative::domain::models::InitiativeId::from_uuid(id),+ };+ let cleanup = PropertyTopicEvent::EntityPropertiesCleared(EntityPropertiesClearedMetadata {+ entity_id: id.to_string(),+ entity_type: PropertyEntityType::Initiative,+ actor_user_id: None,+ actor: None,+ on_behalf_of: None,+ });++ for cleanup_first in [false, true] {+ let deletion = patches_from_initiative_event(&purged);+ let cleanup = patches_from_property_event(&cleanup);+ let patches = if cleanup_first {+ [cleanup, deletion].concat()+ } else {+ [deletion, cleanup].concat()+ };+ assert_eq!(patches.len(), 1);+ assert!(matches!(patches[0].patch, Patch::Deleted(_)));+ assert_eq!(+ patch_entity(&patches[0]).entity_type,+ EntityType::Initiative+ );+ assert_eq!(patch_entity(&patches[0]).entity_id, id.to_string());+ }+}++#[test]+fn attributed_initiative_clears_and_other_system_clears_still_refresh_soup() {+ let metadata = EntityPropertiesClearedMetadata {+ entity_id: Uuid::now_v7().to_string(),+ entity_type: PropertyEntityType::Initiative,+ actor_user_id: None,+ actor: None,+ on_behalf_of: None,+ };+ for metadata in [+ EntityPropertiesClearedMetadata {+ actor_user_id: Some(user()),+ ..metadata.clone()+ },+ EntityPropertiesClearedMetadata {+ actor: Some(ChannelSender::new_from_user(user())),+ ..metadata.clone()+ },+ EntityPropertiesClearedMetadata {+ on_behalf_of: Some(user()),+ ..metadata.clone()+ },+ EntityPropertiesClearedMetadata {+ entity_type: PropertyEntityType::Company,+ ..metadata+ },+ ] {+ let entity_id = metadata.entity_id.clone();+ let patches =+ patches_from_property_event(&PropertyTopicEvent::EntityPropertiesCleared(metadata));+ assert_eq!(patches.len(), 1);+ assert!(matches!(patches[0].patch, Patch::Updated(_)));+ assert_eq!(patch_entity(&patches[0]).entity_id, entity_id);+ }+}+#[test]fn property_events_for_non_property_soup_items_are_ignored() {for entity_type in [PropertyEntityType::Channel, PropertyEntityType::User] {@@ -869,3 +938,67 @@ async fn cancellation_during_retry_backoff_leaves_the_event_uncommitted() {assert_eq!(service.attempts.load(Ordering::SeqCst), 1);assert_eq!(commits.load(Ordering::SeqCst), 0);}++#[test]+fn initiative_lifecycle_and_properties_refresh_the_soup_entity() {+ use initiative::domain::{events::InitiativeChange, models::InitiativeId};++ let id = InitiativeId::from_uuid(Uuid::from_u128(42));+ for event in [+ InitiativeTopicEvent::Created(InitiativeChange {+ initiative_id: id,+ attribution: None,+ occurred_at: Utc::now(),+ }),+ InitiativeTopicEvent::Updated(InitiativeChange {+ initiative_id: id,+ attribution: None,+ occurred_at: Utc::now(),+ }),+ ] {+ assert_eq!(+ patches_from_initiative_event(&event),+ vec![update(EntityType::Initiative, id)]+ );+ }+ assert_eq!(+ property_update(PropertyEntityType::Initiative, &id.to_string()),+ vec![update(EntityType::Initiative, id)]+ );+ assert_eq!(+ patches_from_initiative_event(&InitiativeTopicEvent::Purged { initiative_id: id }),+ vec![delete(EntityType::Initiative, id)]+ );+}++#[test]+fn moving_tasks_refreshes_both_initiatives_once_and_each_task() {+ use initiative::domain::{+ events::{InitiativeTasksChanged, TaskMembershipChange},+ models::InitiativeId,+ };++ let from = InitiativeId::from_uuid(Uuid::from_u128(42));+ let to = InitiativeId::from_uuid(Uuid::from_u128(43));+ let event = InitiativeTopicEvent::TasksChanged(InitiativeTasksChanged {+ attribution: None,+ occurred_at: Utc::now(),+ changes: ["task-1", "task-2"]+ .into_iter()+ .map(|task_id| TaskMembershipChange {+ task_id: task_id.to_owned(),+ from: Some(from),+ to: Some(to),+ })+ .collect(),+ });+ assert_eq!(+ patches_from_initiative_event(&event),+ vec![+ update(EntityType::Document, "task-1"),+ update(EntityType::Initiative, from),+ update(EntityType::Initiative, to),+ update(EntityType::Document, "task-2"),+ ]+ );+}diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 76c439a8e6..9f0610e930 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -286,8 +286,17 @@ async fn main() -> anyhow::Result<()> {presigned_url_expiry_seconds: 3600,browser_cache_expiry_seconds: 86400,};- let properties_service =- ai_tools::build_properties_service(db.clone(), entity_access_service.clone());+ let event_broker_tracker = TaskTracker::new();+ let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(+ macro_event_broker::KafkaEventPublisher::new(config.kafka_brokers.as_ref())+ .context("failed to create kafka event publisher")?,+ event_broker_tracker.clone(),+ );+ let properties_service = ai_tools::build_properties_service_with_broker(+ db.clone(),+ entity_access_service.clone(),+ macro_event_broker.clone(),+ );let task_properties_service = ai_tools::build_task_properties_adapter(db.clone(),properties_service.clone(),@@ -300,12 +309,6 @@ async fn main() -> anyhow::Result<()> {import::outbound::document_properties::DocumentPropertiesApplicator::new(properties_service.clone(),);- let event_broker_tracker = TaskTracker::new();- let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(- macro_event_broker::KafkaEventPublisher::new(config.kafka_brokers.as_ref())- .context("failed to create kafka event publisher")?,- event_broker_tracker.clone(),- );let document_service = DocumentServiceImpl::new(document_repo,cloudfront_config,diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 2264e3efff..8180773245 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -229,8 +229,12 @@ pub(crate) type DssGraphqlSoupSchema = complete_graph::SharedSoupSchema<>;/// GraphQL activity reader over the Postgres activity log (readonly pool).-pub(crate) type DssActivityReader =- complete_graph::ActivityPortReader<activity::outbound::pg_activity_repo::PgActivityRepo>;+pub(crate) type DssActivityReader = complete_graph::ActivityPortReader<+ initiative::domain::personal_activity::ProjectVisibleActivityReads<+ activity::outbound::pg_activity_repo::PgActivityRepo,+ EntityAccessService,+ >,+>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 6ad297ef10..8b92d8d55a 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -1223,26 +1223,33 @@ async fn run() -> anyhow::Result<()> {lexical_client.clone(),),);- let initiative_service = Arc::new(InitiativeServiceImpl::new(- PgInitiativeRepo::new(db.clone()),- initiative_documents::InitiativeDescriptionDocumentsAdapter::new(- document_creator.clone(),- documents_hex::domain::purge::DocumentPurger::new(- documents_hex::outbound::document_purge::LegacyDocumentPurgeRepository::new(- db.clone(),- ),- documents_hex::outbound::document_purge::SqsDocumentPurgeQueue::new(- sqs_client.clone(),+ let initiative_service = Arc::new(+ InitiativeServiceImpl::new(+ PgInitiativeRepo::new(db.clone()),+ initiative_documents::InitiativeDescriptionDocumentsAdapter::new(+ document_creator.clone(),+ documents_hex::domain::purge::DocumentPurger::new(+ documents_hex::outbound::document_purge::LegacyDocumentPurgeRepository::new(+ db.clone(),+ ),+ documents_hex::outbound::document_purge::SqsDocumentPurgeQueue::new(+ sqs_client.clone(),+ ),+ macro_event_broker.clone(),),+ ),+ Arc::new(initiative::outbound::resources::ProjectResources::new(+ properties_service.clone(),+ system_properties_service.clone(),+ entity_access_service.clone(),+ )),+ )+ .with_event_publisher(Arc::new(+ initiative::outbound::event_publisher::BrokerInitiativeEventPublisher::new(macro_event_broker.clone(),),- ),- Arc::new(initiative::outbound::resources::ProjectResources::new(- properties_service.clone(),- system_properties_service.clone(),- entity_access_service.clone(),)),- ));+ );let collab_surface_service = CollabSurfaceServiceImpl::new(Arc::new(PgCollabSurfaceRepo::new(db.clone())),@@ -1632,7 +1639,10 @@ async fn run() -> anyhow::Result<()> {// GraphQL reads the activity log through the readonly pool; the// Kafka consumer's writer-pool repo above is separate on purpose.activity_reader: complete_graph::ActivityPortReader::new(Arc::new(- activity::outbound::pg_activity_repo::PgActivityRepo::new(readonly_db.clone()),+ initiative::domain::personal_activity::ProjectVisibleActivityReads::new(+ activity::outbound::pg_activity_repo::PgActivityRepo::new(readonly_db.clone()),+ entity_access_service.clone(),+ ),)),graphql_entity_mutation_service,github_sync_service: Arc::new(github_sync_service_impl),diff --git a/services/document_storage_service/src/service/activity.rs b/services/document_storage_service/src/service/activity.rsindex 33820215b8..9da392301b 100644--- a/services/document_storage_service/src/service/activity.rs+++ b/services/document_storage_service/src/service/activity.rs@@ -11,6 +11,7 @@ use channels::domain::broker_events::ChannelMacroEvent;use chat::domain::events::ChatMacroEvent;use documents_hex::domain::events::DocumentMacroEvent;use email::domain::events::EmailMacroEvent;+use initiative::domain::events::InitiativeMacroEvent;use macro_event_broker::MacroEvent as _;use projects_hex::domain::events::ProjectMacroEvent;use properties::domain::events::PropertyMacroEvent;@@ -28,6 +29,7 @@ mod source {EmailMacroEvent,PropertyMacroEvent,CallMacroEvent,+ InitiativeMacroEvent,);}pub(crate) use source::ActivitySourceEvent;@@ -59,6 +61,7 @@ pub(crate) async fn ingest(ActivitySourceEvent::EmailMacroEvent(e) => arm(e.event()),ActivitySourceEvent::PropertyMacroEvent(e) => arm(e.event()),ActivitySourceEvent::CallMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::InitiativeMacroEvent(e) => arm(e.event()),}}@@ -81,6 +84,29 @@ where{type Err = entity_access::domain::models::AccessError;+ async fn viewer_can_see(+ &self,+ entity_type: activity::EntityType,+ entity_id: &str,+ viewer: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<bool, Self::Err> {+ use entity_access::domain::models::{AccessError, ViewAccessLevel};+ match self+ .service+ .generate_entity_access_receipt::<ViewAccessLevel>(viewer, None, entity_id, entity_type)+ .await+ {+ Ok(_) => Ok(true),+ Err(+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_)+ | AccessError::BadRequest(_),+ ) => Ok(false),+ Err(error) => Err(error),+ }+ }+async fn entity_audience(&self,entity_type: activity::EntityType,diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex c8c79e5cff..cfd3191e99 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -237,18 +237,21 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Tolet entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone(),)));- let properties_service =- ai_tools::build_properties_service(db.clone(), entity_access_service.clone());- let task_properties_service = ai_tools::build_task_properties_adapter(- db.clone(),- properties_service.clone(),- entity_access_service.clone(),- );let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(macro_event_broker::KafkaEventPublisher::new(config.kafka_brokers.as_ref()).context("failed to create kafka event publisher")?,event_task_tracker,);+ let properties_service = ai_tools::build_properties_service_with_broker(+ db.clone(),+ entity_access_service.clone(),+ macro_event_broker.clone(),+ );+ let task_properties_service = ai_tools::build_task_properties_adapter(+ db.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );let document_service = documents::domain::service::DocumentServiceImpl {repo: document_repo,cloudfront_config,diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 9861257856..44008e593e 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -380,7 +380,7 @@ The typed activity-action vocabulary. One member per durable action, pluswith an undecodable payload) surface with their raw tag and payloadinstead of failing the page."""-union GraphqlActivityAction = GraphqlActivityCreated | GraphqlActivityEdited | GraphqlActivityOpened | GraphqlActivityDeleted | GraphqlActivityMessaged | GraphqlActivitySent | GraphqlActivityPropertyChanged | GraphqlActivityParticipantAdded | GraphqlActivityParticipantRemoved | GraphqlActivityCallStarted | GraphqlActivityUnknownAction+union GraphqlActivityAction = GraphqlActivityCreated | GraphqlActivityEdited | GraphqlActivityOpened | GraphqlActivityDeleted | GraphqlActivityMessaged | GraphqlActivitySent | GraphqlActivityPropertyChanged | GraphqlActivityParticipantAdded | GraphqlActivityParticipantRemoved | GraphqlActivityCallStarted | GraphqlActivityTaskAdded | GraphqlActivityTaskRemoved | GraphqlActivityUnknownAction"""A call was started in the entity.@@ -624,6 +624,26 @@ type GraphqlActivitySent {nothing: Boolean!}+"""+A task was added to a project.+"""+type GraphqlActivityTaskAdded {+ """+ this object has nothing as a field but we need at least 1 field+ """+ nothing: Boolean!+}++"""+A task was removed from a project.+"""+type GraphqlActivityTaskRemoved {+ """+ this object has nothing as a field but we need at least 1 field+ """+ nothing: Boolean!+}+"""An action this deployment's vocabulary doesn't know."""