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(agents): correlate session activity with code mode
Eric Hayes9cabb1b60182
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8c54ca372e..1e3fb674bf 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -41,6 +41,7 @@],"activity": ["crates/activity",+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/broadcast",@@ -48,6 +49,7 @@"crates/cowlike","crates/genai_telemetry","crates/kafka_util",+ "crates/macro_auth","crates/macro_env","crates/macro_env_var","crates/macro_event_broker",@@ -55,6 +57,7 @@"crates/macro_user_id","crates/model-entity","crates/model_owner",+ "crates/remote_env_var","crates/workspace-hack"],"agent": [@@ -87,6 +90,7 @@"crates/activity","crates/agent","crates/agent_api_keys",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -172,6 +176,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -268,6 +273,7 @@"crates/activity","crates/agent","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -385,9 +391,20 @@"crates/unfurl","crates/workspace-hack"],+ "agent_correlation": [+ "crates/agent_correlation",+ "crates/cowlike",+ "crates/macro_auth",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"agent_egress": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_egress","crates/agent_runtime_protocol","crates/agent_session",@@ -524,6 +541,7 @@"crates/activity","crates/agent","crates/agent_api_keys",+ "crates/agent_correlation","crates/agent_egress","crates/agent_harness","crates/agent_runtime_protocol",@@ -666,6 +684,7 @@"crates/agent_api_keys","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_egress","crates/agent_harness","crates/agent_inmem",@@ -877,6 +896,7 @@"crates/agent_api_keys","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_egress","crates/agent_inmem","crates/agent_runtime_protocol",@@ -1107,6 +1127,7 @@"agent_session": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -1199,6 +1220,7 @@"agent_session_realtime": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_session_realtime",@@ -1292,6 +1314,7 @@"agent_trigger": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_trigger",@@ -1390,6 +1413,7 @@"agent_trigger_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_trigger",@@ -1497,6 +1521,7 @@"ai_billing": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -1580,6 +1605,7 @@"ai_billing_cli": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -1670,6 +1696,7 @@"crates/agent","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -1855,6 +1882,7 @@"crates/agent","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -2070,6 +2098,7 @@"anthropic": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -2164,6 +2193,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -2307,6 +2337,7 @@"crates/activity","crates/agent","crates/agent_api_keys",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -2512,6 +2543,7 @@"bots": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -2603,6 +2635,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -2738,6 +2771,7 @@"calendar_events": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -2814,6 +2848,7 @@"calendar_scheduling": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/analytics_client",@@ -2900,6 +2935,7 @@"calendar_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/analytics_client",@@ -2997,6 +3033,7 @@"call": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -3080,6 +3117,7 @@"crates/agent","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -3307,6 +3345,7 @@"channels": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -3378,6 +3417,7 @@"chat": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -3449,6 +3489,7 @@"codex_cloud_agents": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -3542,6 +3583,7 @@"codex_connection": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -3647,6 +3689,7 @@"coding_agent_worker": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_trigger",@@ -3775,6 +3818,7 @@"cognition": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -3860,6 +3904,7 @@"collab_surface": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -3940,6 +3985,7 @@"comms_db_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4013,6 +4059,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_session_realtime",@@ -4234,6 +4281,7 @@],"connection_gateway": ["crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4320,6 +4368,7 @@],"contacts_service": ["crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4366,6 +4415,7 @@"convert_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4456,6 +4506,7 @@"crm": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4539,6 +4590,7 @@"cursor_cloud_agents": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -4653,6 +4705,7 @@"database_webhooks": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4719,6 +4772,7 @@"databases": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -4785,6 +4839,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -4953,6 +5008,7 @@"deleted_item_poller": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_engine",@@ -5096,6 +5152,7 @@"crates/agent","crates/agent_changes","crates/agent_code_mode",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_session_realtime",@@ -5405,6 +5462,7 @@"document_upload_finalizer_handler": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_engine",@@ -5523,6 +5581,7 @@"documents": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_engine",@@ -5642,6 +5701,7 @@"docx_unzip_handler": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -5739,6 +5799,7 @@"email": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -5837,6 +5898,7 @@"email_api_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -5927,6 +5989,7 @@"email_focus_worker": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -6069,6 +6132,7 @@"services/email_focus_worker"],"email_formatting": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -6148,6 +6212,7 @@"email_scheduled_handler": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -6248,6 +6313,7 @@"email_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -6364,6 +6430,7 @@"email_service_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -6504,6 +6571,7 @@"email_suppression_handler": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -6866,6 +6934,7 @@"forms": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -7007,6 +7076,7 @@"github": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_engine",@@ -7124,6 +7194,7 @@],"github_pull_requests": ["crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7215,6 +7286,7 @@"granola_sync": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7292,6 +7364,7 @@"graphql_activity": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7340,6 +7413,7 @@"graphql_calendar": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7418,6 +7492,7 @@"graphql_channel": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7517,6 +7592,7 @@"graphql_crm": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -7600,6 +7676,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -7751,6 +7828,7 @@"graphql_email": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -7852,6 +7930,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8003,6 +8082,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8155,6 +8235,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8304,6 +8385,7 @@"crates/workspace-hack"],"graphql_notification": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -8350,6 +8432,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8540,6 +8623,7 @@"graphql_properties": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -8599,6 +8683,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8750,6 +8835,7 @@"graphql_scheduled_action": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -8891,6 +8977,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -9068,6 +9155,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -9266,6 +9354,7 @@"image_generation": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_toolset",@@ -9364,6 +9453,7 @@"image_proxy_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -9442,6 +9532,7 @@"import": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -9637,6 +9728,7 @@"initiative": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -9695,6 +9787,7 @@"initiative_description": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -9774,6 +9867,7 @@"crates/workspace-hack"],"invite_email": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -9837,6 +9931,7 @@"jev": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -9937,6 +10032,7 @@"lexical_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -10005,6 +10101,7 @@"lexical_mention_extractor": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -10153,6 +10250,7 @@"macro_db_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -10241,11 +10339,16 @@"crates/workspace-hack"],"macro_event_broker": [+ "crates/agent_correlation",+ "crates/cowlike","crates/kafka_util",+ "crates/macro_auth","crates/macro_env","crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics",+ "crates/macro_user_id",+ "crates/remote_env_var","crates/workspace-hack"],"macro_event_topics": [@@ -10255,6 +10358,7 @@"macro_middleware": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -10513,6 +10617,7 @@"memory": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -10661,6 +10766,7 @@"messages": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -10774,6 +10880,7 @@"crates/model_file_type"],"model_notifications": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -10894,6 +11001,7 @@"models_search": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -11006,6 +11114,7 @@"models_soup": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -11109,6 +11218,7 @@"name_search": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -11195,6 +11305,7 @@"crates/non_empty"],"notification": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -11225,6 +11336,7 @@"crates/workspace-hack"],"notification_db_client": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -11264,6 +11376,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -11405,6 +11518,7 @@"crates/workspace-hack"],"notification_retention_handler": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -11437,6 +11551,7 @@"services/notification_retention_handler"],"notification_sandbox": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -11477,6 +11592,7 @@"notification_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -11719,6 +11835,7 @@"projects": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_billing","crates/ai_engine",@@ -11840,6 +11957,7 @@"properties": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -11896,6 +12014,7 @@"properties_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -11963,6 +12082,7 @@"crates/workspace-hack"],"referral": [+ "crates/agent_correlation","crates/ai_toolset","crates/bot_id","crates/bot_token",@@ -11998,6 +12118,7 @@"reminders": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -12110,6 +12231,7 @@"routine_program": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -12185,6 +12307,7 @@"routines": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -12278,6 +12401,7 @@"scheduled_action": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -12417,6 +12541,7 @@"search_processing_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -12565,6 +12690,7 @@"search_service": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -12689,6 +12815,7 @@"search_service_client": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -12839,6 +12966,7 @@"seed_cli": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -13004,6 +13132,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13148,6 +13277,7 @@"slack_import_worker": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13254,6 +13384,7 @@"slack_integration": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13362,6 +13493,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13480,6 +13612,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13605,6 +13738,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -13725,6 +13859,7 @@"soup_realtime": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",@@ -14070,6 +14205,7 @@"task_dedup": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/ai_toolset","crates/ai_usage",@@ -14142,6 +14278,7 @@"teams": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/analytics_client",@@ -14248,6 +14385,7 @@"universal_input": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -14460,6 +14598,7 @@"user_link_cleanup_handler": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_toolset","crates/ai_usage","crates/attachment",@@ -14536,6 +14675,7 @@"web_search": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/ai_billing","crates/ai_toolset","crates/ai_usage",@@ -14620,6 +14760,7 @@"webhook": ["crates/activity","crates/agent",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/agent_trigger",@@ -14926,6 +15067,7 @@"crates/activity","crates/agent","crates/agent_changes",+ "crates/agent_correlation","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",diff --git a/.sqlx/query-112b2f75056028c6f9255fbcce4d190caedc5813be3a00e4b52558f488dde4a2.json b/.sqlx/query-112b2f75056028c6f9255fbcce4d190caedc5813be3a00e4b52558f488dde4a2.jsonnew file mode 100644index 0000000000..90d39ed8e3--- /dev/null+++ b/.sqlx/query-112b2f75056028c6f9255fbcce4d190caedc5813be3a00e4b52558f488dde4a2.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id, agent_correlation_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n agent_correlation_id = EXCLUDED.agent_correlation_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Bool",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "112b2f75056028c6f9255fbcce4d190caedc5813be3a00e4b52558f488dde4a2"+}diff --git a/.sqlx/query-bad9bae721ab59d9c21b86b10d24d324e5ff56f638df3b3a3f67304a61767d6d.json b/.sqlx/query-137fa5249eb860f87f14f6b891dfc0ab2f1210f5afb6fe5cdb89e564893a07da.jsonsimilarity index 60%rename from .sqlx/query-bad9bae721ab59d9c21b86b10d24d324e5ff56f638df3b3a3f67304a61767d6d.jsonrename to .sqlx/query-137fa5249eb860f87f14f6b891dfc0ab2f1210f5afb6fe5cdb89e564893a07da.jsonindex 7df2cd613f..7c08236d71 100644--- a/.sqlx/query-bad9bae721ab59d9c21b86b10d24d324e5ff56f638df3b3a3f67304a61767d6d.json+++ b/.sqlx/query-137fa5249eb860f87f14f6b891dfc0ab2f1210f5afb6fe5cdb89e564893a07da.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT send_time, sent, processing, actor_id, delivery_claim_id,\n delivery_started_at, delivery_message_id, delivery_status, approved_attachments,\n (send_time <= NOW() AND NOT sent AND delivery_status <> 'failed'\n AND (CASE WHEN processing THEN\n COALESCE(delivery_lease_expires_at, updated_at + make_interval(secs => $3)) <= NOW()\n ELSE delivery_lease_expires_at IS NULL OR delivery_lease_expires_at <= NOW() END)) AS \"available!\"\n FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2 FOR UPDATE",+ "query": "SELECT send_time, sent, processing, actor_id, agent_correlation_id, delivery_claim_id,\n delivery_started_at, delivery_message_id, delivery_status, approved_attachments,\n (send_time <= NOW() AND NOT sent AND delivery_status <> 'failed'\n AND (CASE WHEN processing THEN\n COALESCE(delivery_lease_expires_at, updated_at + make_interval(secs => $3)) <= NOW()\n ELSE delivery_lease_expires_at IS NULL OR delivery_lease_expires_at <= NOW() END)) AS \"available!\"\n FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2 FOR UPDATE","describe": {"columns": [{@@ -25,31 +25,36 @@},{"ordinal": 4,- "name": "delivery_claim_id",+ "name": "agent_correlation_id","type_info": "Uuid"},{"ordinal": 5,+ "name": "delivery_claim_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 6,"name": "delivery_started_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "delivery_message_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "delivery_status","type_info": "Text"},{- "ordinal": 8,+ "ordinal": 9,"name": "approved_attachments","type_info": "Jsonb"},{- "ordinal": 9,+ "ordinal": 10,"name": "available!","type_info": "Bool"}@@ -69,10 +74,11 @@true,true,true,+ true,false,false,null]},- "hash": "bad9bae721ab59d9c21b86b10d24d324e5ff56f638df3b3a3f67304a61767d6d"+ "hash": "137fa5249eb860f87f14f6b891dfc0ab2f1210f5afb6fe5cdb89e564893a07da"}diff --git a/.sqlx/query-e049a110febcb8a76c2228e43a3fee8fcfbcb0a787875f10758336f97033c6cd.json b/.sqlx/query-17e24c77f549bab7ffc6d7f15034f43c783974f70bbb5b7a4d6b27e7a5891811.jsonsimilarity index 72%rename from .sqlx/query-e049a110febcb8a76c2228e43a3fee8fcfbcb0a787875f10758336f97033c6cd.jsonrename to .sqlx/query-17e24c77f549bab7ffc6d7f15034f43c783974f70bbb5b7a4d6b27e7a5891811.jsonindex 330c761291..c4d94f7259 100644--- a/.sqlx/query-e049a110febcb8a76c2228e43a3fee8fcfbcb0a787875f10758336f97033c6cd.json+++ b/.sqlx/query-17e24c77f549bab7ffc6d7f15034f43c783974f70bbb5b7a4d6b27e7a5891811.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id\n FROM email_scheduled_messages\n WHERE message_id = $1 and sent = false\n ",+ "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id\n FROM email_scheduled_messages\n WHERE message_id = $1 and sent = false\n ","describe": {"columns": [{@@ -32,6 +32,11 @@"ordinal": 5,"name": "actor_id","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "agent_correlation_id",+ "type_info": "Uuid"}],"parameters": {@@ -45,8 +50,9 @@false,false,false,+ true,true]},- "hash": "e049a110febcb8a76c2228e43a3fee8fcfbcb0a787875f10758336f97033c6cd"+ "hash": "17e24c77f549bab7ffc6d7f15034f43c783974f70bbb5b7a4d6b27e7a5891811"}diff --git a/.sqlx/query-29b8ca0e672d412aeeaf19c3f633fb10fb5b41ac6a0ff074eefcc71123353872.json b/.sqlx/query-29b8ca0e672d412aeeaf19c3f633fb10fb5b41ac6a0ff074eefcc71123353872.jsondeleted file mode 100644index c0f966a225..0000000000--- a/.sqlx/query-29b8ca0e672d412aeeaf19c3f633fb10fb5b41ac6a0ff074eefcc71123353872.json+++ /dev/null@@ -1,21 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO activity_events\n (id, actor_id, subject_id, action, action_payload,\n entity_type, entity_id, occurred_at)\n SELECT * FROM UNNEST(\n $1::uuid[], $2::text[], $3::text[], $4::text[], $5::jsonb[],\n $6::text[], $7::text[], $8::timestamptz[])\n ON CONFLICT (id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "UuidArray",- "TextArray",- "TextArray",- "TextArray",- "JsonbArray",- "TextArray",- "TextArray",- "TimestamptzArray"- ]- },- "nullable": []- },- "hash": "29b8ca0e672d412aeeaf19c3f633fb10fb5b41ac6a0ff074eefcc71123353872"-}diff --git a/.sqlx/query-369c1ecead8f5758fb9e93420d91d9b03e563897f41d8d22539b23199182f0cd.json b/.sqlx/query-369c1ecead8f5758fb9e93420d91d9b03e563897f41d8d22539b23199182f0cd.jsonnew file mode 100644index 0000000000..6336ddfeb9--- /dev/null+++ b/.sqlx/query-369c1ecead8f5758fb9e93420d91d9b03e563897f41d8d22539b23199182f0cd.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO agent_correlations (id, agent_session_id) SELECT $1, id FROM agent_session WHERE id = $2 AND bot_id = $3 RETURNING id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "369c1ecead8f5758fb9e93420d91d9b03e563897f41d8d22539b23199182f0cd"+}diff --git a/.sqlx/query-3141697998b06e7e2f7ef6c8d38260fd5aedb677cf8c2c41a9cfd1eeb5d0f41e.json b/.sqlx/query-3aff1b5fbd91e6eba75622aaea69afa7d1d051b41f530fb8ae6ae9b2b6e2e051.jsonsimilarity index 71%rename from .sqlx/query-3141697998b06e7e2f7ef6c8d38260fd5aedb677cf8c2c41a9cfd1eeb5d0f41e.jsonrename to .sqlx/query-3aff1b5fbd91e6eba75622aaea69afa7d1d051b41f530fb8ae6ae9b2b6e2e051.jsonindex aa54ed680e..349bb120b5 100644--- a/.sqlx/query-3141697998b06e7e2f7ef6c8d38260fd5aedb677cf8c2c41a9cfd1eeb5d0f41e.json+++ b/.sqlx/query-3aff1b5fbd91e6eba75622aaea69afa7d1d051b41f530fb8ae6ae9b2b6e2e051.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id\n FROM email_scheduled_messages\n WHERE message_id = ANY($1) AND sent = false\n ",+ "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id\n FROM email_scheduled_messages\n WHERE message_id = ANY($1) AND sent = false\n ","describe": {"columns": [{@@ -32,6 +32,11 @@"ordinal": 5,"name": "actor_id","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "agent_correlation_id",+ "type_info": "Uuid"}],"parameters": {@@ -45,8 +50,9 @@false,false,false,+ true,true]},- "hash": "3141697998b06e7e2f7ef6c8d38260fd5aedb677cf8c2c41a9cfd1eeb5d0f41e"+ "hash": "3aff1b5fbd91e6eba75622aaea69afa7d1d051b41f530fb8ae6ae9b2b6e2e051"}diff --git a/.sqlx/query-72f271d631f1aed6643a5f5ab371dcc65982ba1efdfd0f9b3c43c3336a965dd5.json b/.sqlx/query-4c33f4243f7f6be0169fb4d43ad0de41bf872c222f1b7be721914499391a2d0a.jsonsimilarity index 65%rename from .sqlx/query-72f271d631f1aed6643a5f5ab371dcc65982ba1efdfd0f9b3c43c3336a965dd5.jsonrename to .sqlx/query-4c33f4243f7f6be0169fb4d43ad0de41bf872c222f1b7be721914499391a2d0a.jsonindex 7b940cb981..696e4a65c0 100644--- a/.sqlx/query-72f271d631f1aed6643a5f5ab371dcc65982ba1efdfd0f9b3c43c3336a965dd5.json+++ b/.sqlx/query-4c33f4243f7f6be0169fb4d43ad0de41bf872c222f1b7be721914499391a2d0a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1\n ORDER BY occurred_at DESC, id DESC\n LIMIT $2\n ",+ "query": "\n SELECT id, agent_correlation_id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1\n ORDER BY occurred_at DESC, id DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -10,36 +10,41 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at","type_info": "Timestamptz"}@@ -52,6 +57,7 @@},"nullable": [false,+ true,false,false,true,@@ -61,5 +67,5 @@false]},- "hash": "72f271d631f1aed6643a5f5ab371dcc65982ba1efdfd0f9b3c43c3336a965dd5"+ "hash": "4c33f4243f7f6be0169fb4d43ad0de41bf872c222f1b7be721914499391a2d0a"}diff --git a/.sqlx/query-63fc3f28c05947dbd7cab2620feb22551c8100ece599cb7ef92de43bc1851480.json b/.sqlx/query-63fc3f28c05947dbd7cab2620feb22551c8100ece599cb7ef92de43bc1851480.jsonnew file mode 100644index 0000000000..07052a21bd--- /dev/null+++ b/.sqlx/query-63fc3f28c05947dbd7cab2620feb22551c8100ece599cb7ef92de43bc1851480.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO activity_events\n (id, actor_id, subject_id, action, action_payload,\n entity_type, entity_id, occurred_at, agent_correlation_id)\n SELECT * FROM UNNEST(\n $1::uuid[], $2::text[], $3::text[], $4::text[], $5::jsonb[],\n $6::text[], $7::text[], $8::timestamptz[], $9::uuid[])\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "TextArray",+ "JsonbArray",+ "TextArray",+ "TextArray",+ "TimestamptzArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63fc3f28c05947dbd7cab2620feb22551c8100ece599cb7ef92de43bc1851480"+}diff --git a/.sqlx/query-283b0b2adabca5459246bb424a01fb7cfa158c6a310ecffd52fbba9ec1ce6694.json b/.sqlx/query-696f790558ba0b27d243b5c9f39cdae05524fbee2a97a1b9a6f3f2e4775e35e0.jsonsimilarity index 67%rename from .sqlx/query-283b0b2adabca5459246bb424a01fb7cfa158c6a310ecffd52fbba9ec1ce6694.jsonrename to .sqlx/query-696f790558ba0b27d243b5c9f39cdae05524fbee2a97a1b9a6f3f2e4775e35e0.jsonindex 4c4b6bdcb8..313990a4f2 100644--- a/.sqlx/query-283b0b2adabca5459246bb424a01fb7cfa158c6a310ecffd52fbba9ec1ce6694.json+++ b/.sqlx/query-696f790558ba0b27d243b5c9f39cdae05524fbee2a97a1b9a6f3f2e4775e35e0.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1 AND (occurred_at, id) < ($2, $3)\n ORDER BY occurred_at DESC, id DESC\n LIMIT $4\n ",+ "query": "SELECT id, agent_correlation_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": [{@@ -10,42 +10,48 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at","type_info": "Timestamptz"}],"parameters": {"Left": [+ "Text","Text","Timestamptz","Uuid",@@ -54,6 +60,7 @@},"nullable": [false,+ true,false,false,true,@@ -63,5 +70,5 @@false]},- "hash": "283b0b2adabca5459246bb424a01fb7cfa158c6a310ecffd52fbba9ec1ce6694"+ "hash": "696f790558ba0b27d243b5c9f39cdae05524fbee2a97a1b9a6f3f2e4775e35e0"}diff --git a/.sqlx/query-2c85606cfd85f04433c60549ff5332d854fa30f8fb472937be7c78d9a8a83290.json b/.sqlx/query-761a2a37df36e4bd3af3b051b8ba1680d509a9e99b21c98ecf8b88aa21800420.jsonsimilarity index 52%rename from .sqlx/query-2c85606cfd85f04433c60549ff5332d854fa30f8fb472937be7c78d9a8a83290.jsonrename to .sqlx/query-761a2a37df36e4bd3af3b051b8ba1680d509a9e99b21c98ecf8b88aa21800420.jsonindex ccab9bf581..33d8836839 100644--- a/.sqlx/query-2c85606cfd85f04433c60549ff5332d854fa30f8fb472937be7c78d9a8a83290.json+++ b/.sqlx/query-761a2a37df36e4bd3af3b051b8ba1680d509a9e99b21c98ecf8b88aa21800420.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT a.id AS \"id!\", a.actor_id AS \"actor_id!\",\n a.action AS \"action!\", a.action_payload,\n a.subject_id AS \"subject_id!\",\n a.entity_type AS \"entity_type!\", a.entity_id AS \"entity_id!\",\n a.occurred_at AS \"occurred_at!\"\n FROM UNNEST($1::text[], $2::text[]) AS k(entity_type, entity_id)\n JOIN LATERAL (\n SELECT * FROM activity_events e\n WHERE e.entity_type = k.entity_type AND e.entity_id = k.entity_id\n ORDER BY e.occurred_at DESC, e.id DESC\n LIMIT $3\n ) a ON TRUE\n ORDER BY a.occurred_at DESC, a.id DESC\n ",+ "query": "\n SELECT a.id AS \"id!\", a.agent_correlation_id, a.actor_id AS \"actor_id!\",\n a.action AS \"action!\", a.action_payload,\n a.subject_id AS \"subject_id!\",\n a.entity_type AS \"entity_type!\", a.entity_id AS \"entity_id!\",\n a.occurred_at AS \"occurred_at!\"\n FROM UNNEST($1::text[], $2::text[]) AS k(entity_type, entity_id)\n JOIN LATERAL (\n SELECT * FROM activity_events e\n WHERE e.entity_type = k.entity_type AND e.entity_id = k.entity_id\n ORDER BY e.occurred_at DESC, e.id DESC\n LIMIT $3\n ) a ON TRUE\n ORDER BY a.occurred_at DESC, a.id DESC\n ","describe": {"columns": [{@@ -10,36 +10,41 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id!","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action!","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id!","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type!","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id!","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at!","type_info": "Timestamptz"}@@ -53,6 +58,7 @@},"nullable": [false,+ true,false,false,true,@@ -62,5 +68,5 @@false]},- "hash": "2c85606cfd85f04433c60549ff5332d854fa30f8fb472937be7c78d9a8a83290"+ "hash": "761a2a37df36e4bd3af3b051b8ba1680d509a9e99b21c98ecf8b88aa21800420"}diff --git a/.sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.json b/.sqlx/query-7dfe9f1ccade84674a6bea7df73b9f8f4e0fca11d23afb42352bdc63cd6c7e74.jsonsimilarity index 65%rename from .sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.jsonrename to .sqlx/query-7dfe9f1ccade84674a6bea7df73b9f8f4e0fca11d23afb42352bdc63cd6c7e74.jsonindex 66e316f1b9..f79ca52016 100644--- a/.sqlx/query-fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c.json+++ b/.sqlx/query-7dfe9f1ccade84674a6bea7df73b9f8f4e0fca11d23afb42352bdc63cd6c7e74.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1\n AND occurred_at >= $2\n AND occurred_at < $3\n ORDER BY occurred_at DESC, id DESC\n LIMIT $4\n ",+ "query": "\n SELECT id, agent_correlation_id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1\n AND occurred_at >= $2\n AND occurred_at < $3\n ORDER BY occurred_at DESC, id DESC\n LIMIT $4\n ","describe": {"columns": [{@@ -10,36 +10,41 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at","type_info": "Timestamptz"}@@ -54,6 +59,7 @@},"nullable": [false,+ true,false,false,true,@@ -63,5 +69,5 @@false]},- "hash": "fc09ef8fa86f4f1a53b37a2811a9ac608dfb92074a4d3bcbd8fb4953ebda4e1c"+ "hash": "7dfe9f1ccade84674a6bea7df73b9f8f4e0fca11d23afb42352bdc63cd6c7e74"}diff --git a/.sqlx/query-7eaa51168e96d69a29f0f25cba8bc29c0d1b8b01a2ed5f0b386c74db5ef69d3e.json b/.sqlx/query-7eaa51168e96d69a29f0f25cba8bc29c0d1b8b01a2ed5f0b386c74db5ef69d3e.jsonnew file mode 100644index 0000000000..11dcda1e7b--- /dev/null+++ b/.sqlx/query-7eaa51168e96d69a29f0f25cba8bc29c0d1b8b01a2ed5f0b386c74db5ef69d3e.json@@ -0,0 +1,74 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT e.id, e.agent_correlation_id, e.actor_id, e.action,\n e.action_payload, e.subject_id, e.entity_type, e.entity_id, e.occurred_at\n FROM agent_correlations c\n CROSS JOIN LATERAL (\n SELECT id, agent_correlation_id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE agent_correlation_id = c.id\n AND (occurred_at, id) < (COALESCE($3::timestamptz, 'infinity'), COALESCE($4::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff'))\n ORDER BY occurred_at DESC, id DESC LIMIT $5\n ) e\n WHERE c.agent_session_id = $1 AND ($2::uuid IS NULL OR c.id = $2)\n ORDER BY e.occurred_at DESC, e.id DESC LIMIT $5",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "actor_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "action",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "action_payload",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 5,+ "name": "subject_id",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "occurred_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ false,+ true,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "7eaa51168e96d69a29f0f25cba8bc29c0d1b8b01a2ed5f0b386c74db5ef69d3e"+}diff --git a/.sqlx/query-ed593bddcc4661e7da5d24e43ba7c33377733274b71a50ecfbdf407d21d58af2.json b/.sqlx/query-97cc3af696916fb83a09c5504f35f15a794dc767fc355dcdfc34f55b2564da48.jsonsimilarity index 84%rename from .sqlx/query-ed593bddcc4661e7da5d24e43ba7c33377733274b71a50ecfbdf407d21d58af2.jsonrename to .sqlx/query-97cc3af696916fb83a09c5504f35f15a794dc767fc355dcdfc34f55b2564da48.jsonindex 53a390d857..ac85fcb300 100644--- a/.sqlx/query-ed593bddcc4661e7da5d24e43ba7c33377733274b71a50ecfbdf407d21d58af2.json+++ b/.sqlx/query-97cc3af696916fb83a09c5504f35f15a794dc767fc355dcdfc34f55b2564da48.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE email_scheduled_messages\n SET processing = true, updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n AND NOT sent AND NOT processing AND send_time <= NOW()\n AND delivery_claim_id IS NULL AND delivery_started_at IS NULL AND delivery_status = 'ready'\n AND NOT EXISTS(SELECT 1 FROM email_attachments_drafts WHERE draft_id=$2 AND upload_pending)\n AND NOT EXISTS(SELECT 1 FROM email_draft_transfers WHERE (destination_id=$2 AND state NOT IN ('ready','retained','preparing')) OR (source_id=$2 AND state<>'preparing'))\n RETURNING link_id, message_id, send_time, sent, processing, actor_id\n ",+ "query": "\n UPDATE email_scheduled_messages\n SET processing = true, updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n AND NOT sent AND NOT processing AND send_time <= NOW()\n AND delivery_claim_id IS NULL AND delivery_started_at IS NULL AND delivery_status = 'ready'\n AND NOT EXISTS(SELECT 1 FROM email_attachments_drafts WHERE draft_id=$2 AND upload_pending)\n AND NOT EXISTS(SELECT 1 FROM email_draft_transfers WHERE (destination_id=$2 AND state NOT IN ('ready','retained','preparing')) OR (source_id=$2 AND state<>'preparing'))\n RETURNING link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id\n ","describe": {"columns": [{@@ -32,6 +32,11 @@"ordinal": 5,"name": "actor_id","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "agent_correlation_id",+ "type_info": "Uuid"}],"parameters": {@@ -46,8 +51,9 @@false,false,false,+ true,true]},- "hash": "ed593bddcc4661e7da5d24e43ba7c33377733274b71a50ecfbdf407d21d58af2"+ "hash": "97cc3af696916fb83a09c5504f35f15a794dc767fc355dcdfc34f55b2564da48"}diff --git a/.sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.json b/.sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.jsondeleted file mode 100644index c8efea155a..0000000000--- a/.sqlx/query-a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081.json+++ /dev/null@@ -1,18 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Timestamptz",- "Bool",- "Text"- ]- },- "nullable": []- },- "hash": "a5caf0d6cb8e0ee23844c0613757cbfc478c4b075641f4ca6947611f6b4cd081"-}diff --git a/.sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.json b/.sqlx/query-a8c1e0c798b91c6d6703431a782ffe7f0d5d9b7490cbe46ca88e76894a3ac496.jsonsimilarity index 62%rename from .sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.jsonrename to .sqlx/query-a8c1e0c798b91c6d6703431a782ffe7f0d5d9b7490cbe46ca88e76894a3ac496.jsonindex 81f3aefda1..0f7911f0fd 100644--- a/.sqlx/query-84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c.json+++ b/.sqlx/query-a8c1e0c798b91c6d6703431a782ffe7f0d5d9b7490cbe46ca88e76894a3ac496.json@@ -1,6 +1,6 @@{"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",+ "query": "\n SELECT id, agent_correlation_id, actor_id, action, action_payload,\n subject_id, entity_type, entity_id, occurred_at\n FROM activity_events\n WHERE subject_id = $1 AND (occurred_at, id) < ($2, $3)\n ORDER BY occurred_at DESC, id DESC\n LIMIT $4\n ","describe": {"columns": [{@@ -10,36 +10,41 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at","type_info": "Timestamptz"}@@ -47,12 +52,14 @@"parameters": {"Left": ["Text",- "Text",+ "Timestamptz",+ "Uuid","Int8"]},"nullable": [false,+ true,false,false,true,@@ -62,5 +69,5 @@false]},- "hash": "84a8e21289de9ec7b6fe8f473b74592dbfc3fcf0abb99b27bf578773c421090c"+ "hash": "a8c1e0c798b91c6d6703431a782ffe7f0d5d9b7490cbe46ca88e76894a3ac496"}diff --git a/.sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.json b/.sqlx/query-b1336aabee750b02e76de05a7496da1d7f45581968b97b1b57eb36280b8c7cf5.jsonsimilarity index 69%rename from .sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.jsonrename to .sqlx/query-b1336aabee750b02e76de05a7496da1d7f45581968b97b1b57eb36280b8c7cf5.jsonindex 51f8bfa3bb..d8896d9e31 100644--- a/.sqlx/query-c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12.json+++ b/.sqlx/query-b1336aabee750b02e76de05a7496da1d7f45581968b97b1b57eb36280b8c7cf5.json@@ -1,6 +1,6 @@{"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",+ "query": "SELECT id, agent_correlation_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": [{@@ -10,36 +10,41 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at","type_info": "Timestamptz"}@@ -48,13 +53,12 @@"Left": ["Text","Text",- "Timestamptz",- "Uuid","Int8"]},"nullable": [false,+ true,false,false,true,@@ -64,5 +68,5 @@false]},- "hash": "c2d43abe5421c305af59278182308864a933094f279095a7da1e313378489e12"+ "hash": "b1336aabee750b02e76de05a7496da1d7f45581968b97b1b57eb36280b8c7cf5"}diff --git a/.sqlx/query-c89d8c0c8c3117242967bd116594cd50151fe74e0065df5b6cb9fa21e9451e70.json b/.sqlx/query-c89d8c0c8c3117242967bd116594cd50151fe74e0065df5b6cb9fa21e9451e70.jsonnew file mode 100644index 0000000000..7d34cd46b6--- /dev/null+++ b/.sqlx/query-c89d8c0c8c3117242967bd116594cd50151fe74e0065df5b6cb9fa21e9451e70.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT c.agent_session_id AS session_id, s.bot_id AS agent_id FROM agent_correlations c JOIN agent_session s ON s.id = c.agent_session_id WHERE c.id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "session_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "agent_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "c89d8c0c8c3117242967bd116594cd50151fe74e0065df5b6cb9fa21e9451e70"+}diff --git a/.sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.json b/.sqlx/query-ca2530e38702a9a7addb9bf670f9b3184fe57953149990b9ff98c4043162f3c2.jsonsimilarity index 69%rename from .sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.jsonrename to .sqlx/query-ca2530e38702a9a7addb9bf670f9b3184fe57953149990b9ff98c4043162f3c2.jsonindex 85214ba5bc..e27cfa0c83 100644--- a/.sqlx/query-c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071.json+++ b/.sqlx/query-ca2530e38702a9a7addb9bf670f9b3184fe57953149990b9ff98c4043162f3c2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "-- One page of the viewer's teammates' activity on entities shared with the\n-- viewer. See `team_feed.rs` for the paging contract.\n--\n-- $1 viewer id, $2/$3 cursor position (NULL for the first page),\n-- $4 rows to return, $5 fewest raw rows one teammate's scan reads,\n-- $6 raw rows one page reads across all teammates.\nWITH viewer_source AS (\n -- The principals an `entity_access` grant can name to reach the viewer:\n -- the viewer, their teams, and the channels they are active in.\n SELECT 'user'::entity_access_source_type AS source_type, $1::text AS source_id\n UNION ALL\n SELECT 'team', tu.team_id::text FROM team_user tu WHERE tu.user_id = $1\n UNION ALL\n SELECT 'channel', cp.channel_id::text\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n),\nviewer_inbox AS (\n -- Inboxes whose threads the viewer owns: their own links and those\n -- delegated to them as primary.\n SELECT l.id AS link_id FROM email_links l WHERE l.macro_id = $1\n UNION\n SELECT mul.link_id FROM macro_user_links mul WHERE mul.primary_macro_id = $1\n),\nteammate AS (\n SELECT DISTINCT member.user_id\n FROM team_user viewer\n JOIN team_user member ON member.team_id = viewer.team_id\n WHERE viewer.user_id = $1 AND member.user_id <> $1\n),\nscan AS (\n SELECT GREATEST($5, $6 / GREATEST(count(*), 1))::bigint AS rows FROM teammate\n),\nscanned AS (\n -- Per teammate, one seek of the subject index that stops at $4 visible\n -- rows or after `scan.rows` raw rows. A scan that stops at that cap\n -- also emits its last raw row (`scan_rank = scan.rows`) as a frontier.\n SELECT s.*\n FROM teammate t\n CROSS JOIN LATERAL (\n SELECT w.*\n FROM (\n SELECT e.*,\n row_number() OVER (ORDER BY e.occurred_at DESC, e.id DESC) AS scan_rank,\n -- Mirrors `EntityAccessService::get_users_by_entity` for\n -- every entity type activity records; anything else is\n -- hidden. Forms are hidden too: their rows name\n -- respondents, so they reach only their subject.\n CASE\n WHEN e.entity_type = 'channel' THEN e.entity_id IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n -- A call's audience is its channel's, or its direct\n -- user grants when it has none.\n WHEN e.entity_type = 'call' THEN EXISTS (\n SELECT 1 FROM call_entities ce\n WHERE ce.id = e.entity_uuid\n AND CASE\n WHEN ce.channel_id IS NULL THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = ce.id AND ea.entity_type = 'call'\n AND ea.source_type = 'user' AND ea.source_id = $1\n AND ea.granted_from_project_id IS NULL\n )\n ELSE ce.channel_id::text IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n END\n )\n WHEN e.entity_type IN (\n 'document', 'project', 'chat', 'initiative', 'database',\n 'crm_company', 'email_thread'\n ) THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id::text = e.entity_id\n AND ea.entity_type = e.entity_type\n AND (ea.source_type, ea.source_id) IN (\n SELECT vs.source_type, vs.source_id FROM viewer_source vs\n )\n ) OR (e.entity_type = 'email_thread' AND EXISTS (\n SELECT 1 FROM email_threads et\n WHERE et.id = e.entity_uuid\n AND et.link_id IN (SELECT vi.link_id FROM viewer_inbox vi)\n ))\n ELSE false\n END AS visible\n FROM (\n SELECT e.id, e.actor_id, e.action, e.action_payload, e.subject_id,\n e.entity_type, e.entity_id, e.occurred_at,\n -- Only these id columns are uuids; a malformed id\n -- must hide its row, not fail the page.\n CASE WHEN e.entity_type IN ('call', 'email_thread') THEN\n CASE WHEN e.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN e.entity_id::uuid\n END\n END AS entity_uuid\n FROM activity_events e\n WHERE e.subject_id = t.user_id\n -- No cursor reads from the top. COALESCE, unlike an\n -- `IS NULL OR` branch, keeps this an index condition in\n -- generic plans.\n AND (e.occurred_at, e.id) < (\n COALESCE($2::timestamptz, 'infinity'),\n COALESCE($3::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff')\n )\n ORDER BY e.occurred_at DESC, e.id DESC\n LIMIT (SELECT rows FROM scan)\n ) e\n ) w\n WHERE w.visible OR w.scan_rank = (SELECT rows FROM scan)\n LIMIT $4\n ) s\n),\nboundary AS (\n -- The newest frontier: below it some teammate's rows were not read.\n SELECT * FROM scanned\n WHERE scan_rank = (SELECT rows FROM scan)\n ORDER BY occurred_at DESC, id DESC\n LIMIT 1\n)\n(\n SELECT s.id AS \"id!\", s.actor_id AS \"actor_id!\", s.action AS \"action!\",\n s.action_payload, s.subject_id AS \"subject_id!\",\n s.entity_type AS \"entity_type!\", s.entity_id AS \"entity_id!\",\n s.occurred_at AS \"occurred_at!\", false AS \"is_boundary!\"\n FROM scanned s\n WHERE s.visible\n AND NOT EXISTS (\n SELECT 1 FROM boundary b WHERE (s.occurred_at, s.id) < (b.occurred_at, b.id)\n )\n ORDER BY s.occurred_at DESC, s.id DESC\n LIMIT $4\n)\nUNION ALL\nSELECT b.id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,\n b.entity_id, b.occurred_at, true\nFROM boundary b\n",+ "query": "-- One page of the viewer's teammates' activity on entities shared with the\n-- viewer. See `team_feed.rs` for the paging contract.\n--\n-- $1 viewer id, $2/$3 cursor position (NULL for the first page),\n-- $4 rows to return, $5 fewest raw rows one teammate's scan reads,\n-- $6 raw rows one page reads across all teammates.\nWITH viewer_source AS (\n -- The principals an `entity_access` grant can name to reach the viewer:\n -- the viewer, their teams, and the channels they are active in.\n SELECT 'user'::entity_access_source_type AS source_type, $1::text AS source_id\n UNION ALL\n SELECT 'team', tu.team_id::text FROM team_user tu WHERE tu.user_id = $1\n UNION ALL\n SELECT 'channel', cp.channel_id::text\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n),\nviewer_inbox AS (\n -- Inboxes whose threads the viewer owns: their own links and those\n -- delegated to them as primary.\n SELECT l.id AS link_id FROM email_links l WHERE l.macro_id = $1\n UNION\n SELECT mul.link_id FROM macro_user_links mul WHERE mul.primary_macro_id = $1\n),\nteammate AS (\n SELECT DISTINCT member.user_id\n FROM team_user viewer\n JOIN team_user member ON member.team_id = viewer.team_id\n WHERE viewer.user_id = $1 AND member.user_id <> $1\n),\nscan AS (\n SELECT GREATEST($5, $6 / GREATEST(count(*), 1))::bigint AS rows FROM teammate\n),\nscanned AS (\n -- Per teammate, one seek of the subject index that stops at $4 visible\n -- rows or after `scan.rows` raw rows. A scan that stops at that cap\n -- also emits its last raw row (`scan_rank = scan.rows`) as a frontier.\n SELECT s.*\n FROM teammate t\n CROSS JOIN LATERAL (\n SELECT w.*\n FROM (\n SELECT e.*,\n row_number() OVER (ORDER BY e.occurred_at DESC, e.id DESC) AS scan_rank,\n -- Mirrors `EntityAccessService::get_users_by_entity` for\n -- every entity type activity records; anything else is\n -- hidden. Forms are hidden too: their rows name\n -- respondents, so they reach only their subject.\n CASE\n WHEN e.entity_type = 'channel' THEN e.entity_id IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n -- A call's audience is its channel's, or its direct\n -- user grants when it has none.\n WHEN e.entity_type = 'call' THEN EXISTS (\n SELECT 1 FROM call_entities ce\n WHERE ce.id = e.entity_uuid\n AND CASE\n WHEN ce.channel_id IS NULL THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = ce.id AND ea.entity_type = 'call'\n AND ea.source_type = 'user' AND ea.source_id = $1\n AND ea.granted_from_project_id IS NULL\n )\n ELSE ce.channel_id::text IN (\n SELECT vs.source_id FROM viewer_source vs\n WHERE vs.source_type = 'channel'\n )\n END\n )\n WHEN e.entity_type IN (\n 'document', 'project', 'chat', 'initiative', 'database',\n 'crm_company', 'email_thread'\n ) THEN EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id::text = e.entity_id\n AND ea.entity_type = e.entity_type\n AND (ea.source_type, ea.source_id) IN (\n SELECT vs.source_type, vs.source_id FROM viewer_source vs\n )\n ) OR (e.entity_type = 'email_thread' AND EXISTS (\n SELECT 1 FROM email_threads et\n WHERE et.id = e.entity_uuid\n AND et.link_id IN (SELECT vi.link_id FROM viewer_inbox vi)\n ))\n ELSE false\n END AS visible\n FROM (\n SELECT e.id, e.agent_correlation_id, e.actor_id, e.action, e.action_payload, e.subject_id,\n e.entity_type, e.entity_id, e.occurred_at,\n -- Only these id columns are uuids; a malformed id\n -- must hide its row, not fail the page.\n CASE WHEN e.entity_type IN ('call', 'email_thread') THEN\n CASE WHEN e.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN e.entity_id::uuid\n END\n END AS entity_uuid\n FROM activity_events e\n WHERE e.subject_id = t.user_id\n -- No cursor reads from the top. COALESCE, unlike an\n -- `IS NULL OR` branch, keeps this an index condition in\n -- generic plans.\n AND (e.occurred_at, e.id) < (\n COALESCE($2::timestamptz, 'infinity'),\n COALESCE($3::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff')\n )\n ORDER BY e.occurred_at DESC, e.id DESC\n LIMIT (SELECT rows FROM scan)\n ) e\n ) w\n WHERE w.visible OR w.scan_rank = (SELECT rows FROM scan)\n LIMIT $4\n ) s\n),\nboundary AS (\n -- The newest frontier: below it some teammate's rows were not read.\n SELECT * FROM scanned\n WHERE scan_rank = (SELECT rows FROM scan)\n ORDER BY occurred_at DESC, id DESC\n LIMIT 1\n)\n(\n SELECT s.id AS \"id!\", s.agent_correlation_id, s.actor_id AS \"actor_id!\", s.action AS \"action!\",\n s.action_payload, s.subject_id AS \"subject_id!\",\n s.entity_type AS \"entity_type!\", s.entity_id AS \"entity_id!\",\n s.occurred_at AS \"occurred_at!\", false AS \"is_boundary!\"\n FROM scanned s\n WHERE s.visible\n AND NOT EXISTS (\n SELECT 1 FROM boundary b WHERE (s.occurred_at, s.id) < (b.occurred_at, b.id)\n )\n ORDER BY s.occurred_at DESC, s.id DESC\n LIMIT $4\n)\nUNION ALL\nSELECT b.id, b.agent_correlation_id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,\n b.entity_id, b.occurred_at, true\nFROM boundary b\n","describe": {"columns": [{@@ -10,41 +10,46 @@},{"ordinal": 1,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "actor_id!","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "action!","type_info": "Text"},{- "ordinal": 3,+ "ordinal": 4,"name": "action_payload","type_info": "Jsonb"},{- "ordinal": 4,+ "ordinal": 5,"name": "subject_id!","type_info": "Text"},{- "ordinal": 5,+ "ordinal": 6,"name": "entity_type!","type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "entity_id!","type_info": "Text"},{- "ordinal": 7,+ "ordinal": 8,"name": "occurred_at!","type_info": "Timestamptz"},{- "ordinal": 8,+ "ordinal": 9,"name": "is_boundary!","type_info": "Bool"}@@ -68,8 +73,9 @@null,null,null,+ null,null]},- "hash": "c5890947b333902d164537b40ed6ae9b774c08eabbfe70bc0473504531ce3071"+ "hash": "ca2530e38702a9a7addb9bf670f9b3184fe57953149990b9ff98c4043162f3c2"}diff --git a/.sqlx/query-ced09018d5b606156e8af888b87fc97276f97459b381181c5b66a2c0fd232cc2.json b/.sqlx/query-ced09018d5b606156e8af888b87fc97276f97459b381181c5b66a2c0fd232cc2.jsonnew file mode 100644index 0000000000..6d16db82b2--- /dev/null+++ b/.sqlx/query-ced09018d5b606156e8af888b87fc97276f97459b381181c5b66a2c0fd232cc2.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id, agent_correlation_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n agent_correlation_id = EXCLUDED.agent_correlation_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Bool",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ced09018d5b606156e8af888b87fc97276f97459b381181c5b66a2c0fd232cc2"+}diff --git a/.sqlx/query-da630564e89c0cacb50e8e4b0ce1e41baf5d0476799f63a46b0b0ea3ee342991.json b/.sqlx/query-da7ef37eacd6afd719ba78d9306e4dcbd8820230fe6fa2fdeec6e6ef00e7b665.jsonsimilarity index 72%rename from .sqlx/query-da630564e89c0cacb50e8e4b0ce1e41baf5d0476799f63a46b0b0ea3ee342991.jsonrename to .sqlx/query-da7ef37eacd6afd719ba78d9306e4dcbd8820230fe6fa2fdeec6e6ef00e7b665.jsonindex 31afc7f26b..7e2db42d09 100644--- a/.sqlx/query-da630564e89c0cacb50e8e4b0ce1e41baf5d0476799f63a46b0b0ea3ee342991.json+++ b/.sqlx/query-da7ef37eacd6afd719ba78d9306e4dcbd8820230fe6fa2fdeec6e6ef00e7b665.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ",+ "query": "\n SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ","describe": {"columns": [{@@ -32,6 +32,11 @@"ordinal": 5,"name": "actor_id","type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "agent_correlation_id",+ "type_info": "Uuid"}],"parameters": {@@ -46,8 +51,9 @@false,false,false,+ true,true]},- "hash": "da630564e89c0cacb50e8e4b0ce1e41baf5d0476799f63a46b0b0ea3ee342991"+ "hash": "da7ef37eacd6afd719ba78d9306e4dcbd8820230fe6fa2fdeec6e6ef00e7b665"}diff --git a/.sqlx/query-dad8f8d91792be0d2ce1ca2f4d0eabfaef9cb1e3ca9c1377d71d919abeae4849.json b/.sqlx/query-dad8f8d91792be0d2ce1ca2f4d0eabfaef9cb1e3ca9c1377d71d919abeae4849.jsonnew file mode 100644index 0000000000..173186d672--- /dev/null+++ b/.sqlx/query-dad8f8d91792be0d2ce1ca2f4d0eabfaef9cb1e3ca9c1377d71d919abeae4849.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO email_scheduled_messages\n (link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id, created_at, updated_at)\n VALUES ($1, $2, $3, false, false, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, agent_correlation_id = EXCLUDED.agent_correlation_id, updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "dad8f8d91792be0d2ce1ca2f4d0eabfaef9cb1e3ca9c1377d71d919abeae4849"+}diff --git a/.sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.json b/.sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.jsondeleted file mode 100644index 894b3435e7..0000000000--- a/.sqlx/query-e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e.json+++ /dev/null@@ -1,18 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent, actor_id,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n actor_id = EXCLUDED.actor_id,\n updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Timestamptz",- "Bool",- "Text"- ]- },- "nullable": []- },- "hash": "e6c349e9f655648df54053a317b6398a3ab84ebeff936a05946e149d899b770e"-}diff --git a/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.json b/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.jsondeleted file mode 100644index 5aed71dc28..0000000000--- a/.sqlx/query-f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae.json+++ /dev/null@@ -1,17 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO email_scheduled_messages\n (link_id, message_id, send_time, sent, processing, actor_id, created_at, updated_at)\n VALUES ($1, $2, $3, false, false, $4, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, updated_at = NOW()\n WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Timestamptz",- "Text"- ]- },- "nullable": []- },- "hash": "f4bb1f5eca769887616e8995f263053651fb3215fef847efc741c7171ec00dae"-}diff --git a/.sqlx/query-fb6f76c6c2c3219934782265478fb9400716dc21b0a2f92b9419bc0b9636dd64.json b/.sqlx/query-fb6f76c6c2c3219934782265478fb9400716dc21b0a2f92b9419bc0b9636dd64.jsonnew file mode 100644index 0000000000..f122574b47--- /dev/null+++ b/.sqlx/query-fb6f76c6c2c3219934782265478fb9400716dc21b0a2f92b9419bc0b9636dd64.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT agent_correlation_id FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "agent_correlation_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "fb6f76c6c2c3219934782265478fb9400716dc21b0a2f92b9419bc0b9636dd64"+}diff --git a/Cargo.lock b/Cargo.lockindex cae6b045e8..501b322c2a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -41,6 +41,7 @@ dependencies = [name = "activity"version = "0.1.0"dependencies = [+ "agent_correlation","ai_toolset","async-trait","bot_id",@@ -352,6 +353,26 @@ dependencies = ["workspace-hack",]+[[package]]+name = "agent_correlation"+version = "0.1.0"+dependencies = [+ "async-trait",+ "axum",+ "macro_auth",+ "macro_db_migrator",+ "rootcause",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]+[[package]]name = "agent_egress"version = "0.1.0"@@ -529,6 +550,7 @@ dependencies = ["agent_api_keys","agent_changes","agent_code_mode",+ "agent_correlation","agent_egress","agent_fold","agent_harness",@@ -839,6 +861,7 @@ dependencies = [name = "agent_session"version = "0.1.0"dependencies = [+ "activity","agent","agent-client-protocol","agent_fold",@@ -2196,6 +2219,7 @@ version = "0.1.0"dependencies = ["aes-gcm 0.10.3","agent_api_keys",+ "agent_correlation","ai_billing","ai_usage","analytics_client",@@ -3939,6 +3963,7 @@ dependencies = [name = "calendar_service"version = "0.1.0"dependencies = [+ "agent_correlation","anyhow","authentication_service_client","aws-sdk-secretsmanager",@@ -4292,6 +4317,7 @@ name = "channels"version = "0.1.0"dependencies = ["activity",+ "agent_correlation","ai_toolset","anyhow","async-trait",@@ -4997,6 +5023,7 @@ dependencies = [name = "connection_gateway"version = "0.1.0"dependencies = [+ "agent_correlation","anyhow","async-trait","aws-sdk-dynamodb",@@ -5196,6 +5223,7 @@ dependencies = [name = "contacts_service"version = "0.1.0"dependencies = [+ "agent_correlation","anyhow","aws-sdk-secretsmanager","aws-sdk-sqs",@@ -6607,6 +6635,7 @@ dependencies = ["access_requests","activity","agent_changes",+ "agent_correlation","agent_session","agent_session_realtime","ai_billing",@@ -6903,6 +6932,7 @@ name = "documents"version = "0.1.0"dependencies = ["activity",+ "agent_correlation","ai_billing","ai_engine","ai_toolset",@@ -7326,6 +7356,7 @@ name = "email"version = "0.1.0"dependencies = ["activity",+ "agent_correlation","ai_toolset","anyhow","async-trait",@@ -7589,6 +7620,7 @@ dependencies = [name = "email_service"version = "0.1.0"dependencies = [+ "agent_correlation","ammonia","anyhow","authentication_service_client",@@ -12587,6 +12619,7 @@ dependencies = [name = "macro_event_broker"version = "0.1.0"dependencies = [+ "agent_correlation","kafka_util","macro_event_topics","rdkafka",@@ -14105,6 +14138,7 @@ dependencies = [name = "notification_service"version = "0.1.0"dependencies = [+ "agent_correlation","anyhow","aws-sdk-secretsmanager","aws-sdk-sesv2",diff --git a/Cargo.toml b/Cargo.tomlindex e77655676f..192d1aa80a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -14,6 +14,7 @@ members = ["crates/trigger_context","crates/agent_preview","crates/agent_code_mode",+ "crates/agent_correlation","crates/code_mode_assets","crates/dynamic_ui","crates/agent_inmem",diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex e3321457e3..ff423c4d7a 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type {+ AgentActivityPage,AgentConversationsDto,AgentModeChoiceRequest,AgentModeChoiceResponse,@@ -46,6 +47,7 @@ import type {ExecutionRecord,ExtractInputRequest,ExtractInputResponse,+ GetAgentSessionActivityParams,ListAgentRepositoryBranchesParams,LoadAgentModelsRequest,LoadAgentModelsResponse,@@ -1480,6 +1482,86 @@ export const deleteAgentSession = async (} as deleteAgentSessionResponse;};+/**+ * @summary Read activity using the same visibility capability as the session transcript.+ */+export type getAgentSessionActivityResponse200 = {+ data: AgentActivityPage;+ status: 200;+};++export type getAgentSessionActivityResponse400 = {+ data: void;+ status: 400;+};++export type getAgentSessionActivityResponse401 = {+ data: void;+ status: 401;+};++export type getAgentSessionActivityResponse403 = {+ data: void;+ status: 403;+};++export type getAgentSessionActivityResponseSuccess =+ getAgentSessionActivityResponse200 & {+ headers: Headers;+ };+export type getAgentSessionActivityResponseError = (+ | getAgentSessionActivityResponse400+ | getAgentSessionActivityResponse401+ | getAgentSessionActivityResponse403+) & {+ headers: Headers;+};++export type getAgentSessionActivityResponse =+ | getAgentSessionActivityResponseSuccess+ | getAgentSessionActivityResponseError;++export const getGetAgentSessionActivityUrl = (+ sessionId: string,+ params?: GetAgentSessionActivityParams+) => {+ const normalizedParams = new URLSearchParams();++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString());+ }+ });++ const stringifiedParams = normalizedParams.toString();++ return stringifiedParams.length > 0+ ? `/agent-sessions/${sessionId}/activity?${stringifiedParams}`+ : `/agent-sessions/${sessionId}/activity`;+};++export const getAgentSessionActivity = async (+ sessionId: string,+ params?: GetAgentSessionActivityParams,+ options?: RequestInit+): Promise<getAgentSessionActivityResponse> => {+ const res = await fetch(getGetAgentSessionActivityUrl(sessionId, params), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getAgentSessionActivityResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getAgentSessionActivityResponse;+};+/*** The harness produces an `app.connected` system event, which the transcriptshows as no prompt; it starts a turn once the session is idle.diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRow.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRow.tsnew file mode 100644index 0000000000..3e2a25cda9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRow.ts@@ -0,0 +1,33 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ActivityWireRowAgentCorrelationId } from './activityWireRowAgentCorrelationId';+import type { EntityType } from './entityType';++/**+ * One activity row on the wire — the realtime projection of an inserted+`activity_events` row.+ */+export interface ActivityWireRow {+ /** The stored action tag. */+ action: string;+ /** The stored action payload, if any. */+ action_payload?: unknown;+ /** Who mechanically acted, as a principal string (`macro|…` / `bot|…`). */+ actor_id: string;+ /** Originating code-mode invocation, absent on older events. */+ agent_correlation_id?: ActivityWireRowAgentCorrelationId;+ /** The entity acted on. */+ entity_id: string;+ /** The kind of entity acted on. */+ entity_type: EntityType;+ /** The stored activity id. */+ id: string;+ /** When it happened. */+ occurred_at: string;+ /** Whose activity this is (a principal string). */+ subject_id: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRowAgentCorrelationId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRowAgentCorrelationId.tsnew file mode 100644index 0000000000..cc90c0b9bc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/activityWireRowAgentCorrelationId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Originating code-mode invocation, absent on older events.+ */+export type ActivityWireRowAgentCorrelationId = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityCursor.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityCursor.tsnew file mode 100644index 0000000000..c659dbddc1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityCursor.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Stable chronological resume position.+ */+export interface AgentActivityCursor {+ /** Tie-breaking activity identity. */+ id: string;+ /** Last stored event time. */+ occurredAt: string;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPage.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPage.tsnew file mode 100644index 0000000000..1b5efc0244--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPage.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ActivityWireRow } from './activityWireRow';+import type { AgentActivityPageNextCursor } from './agentActivityPageNextCursor';++/**+ * One page of the activity caused by this session.+ */+export interface AgentActivityPage {+ /** Original activity rows, also retained in the affected entities' histories. */+ activities: ActivityWireRow[];+ nextCursor?: AgentActivityPageNextCursor;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPageNextCursor.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPageNextCursor.tsnew file mode 100644index 0000000000..13177c047a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActivityPageNextCursor.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AgentActivityCursor } from './agentActivityCursor';++export type AgentActivityPageNextCursor = null | AgentActivityCursor;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/entityType.tsnew file mode 100644index 0000000000..93e55a0e0f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/entityType.ts@@ -0,0 +1,39 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The type of an entity in Macro+ */+export type EntityType = (typeof EntityType)[keyof typeof EntityType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const EntityType = {+ user: 'user',+ chat: 'chat',+ channel: 'channel',+ channel_message: 'channel_message',+ document: 'document',+ project: 'project',+ email_thread: 'email_thread',+ calendar_event: 'calendar_event',+ team: 'team',+ call: 'call',+ foreign_entity: 'foreign_entity',+ static_file: 'static_file',+ crm_company: 'crm_company',+ crm_contact: 'crm_contact',+ crm_pipeline: 'crm_pipeline',+ reminder: 'reminder',+ skill: 'skill',+ agent_session: 'agent_session',+ scheduled_action: 'scheduled_action',+ initiative: 'initiative',+ database: 'database',+ database_row: 'database_row',+ form: 'form',+ external_chat: 'external_chat',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/getAgentSessionActivityParams.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/getAgentSessionActivityParams.tsnew file mode 100644index 0000000000..c23c6d0782--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/getAgentSessionActivityParams.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type GetAgentSessionActivityParams = {+ /**+ * Restrict activity to one code-mode invocation within this session.+ */+ agentCorrelationId?: string | null;+ /**+ * Cursor timestamp from the previous page.+ */+ beforeAt?: string | null;+ /**+ * Cursor activity ID from the previous page.+ */+ beforeId?: string | null;+ /**+ * Page size, from 1 to 100; defaults to 50.+ * @minimum 1+ * @maximum 100+ */+ limit?: number | null;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 0665bcbb4e..53a526471a 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -6,6 +6,8 @@*/export * from './accessLevel';+export * from './activityWireRow';+export * from './activityWireRowAgentCorrelationId';export * from './agentAction';export * from './agentActionId';export * from './agentActionOneOf';@@ -27,6 +29,9 @@ export * from './agentActionOneOfOnezeroType';export * from './agentActionOneOfSeven';export * from './agentActionOneOfSevenAllOf';export * from './agentActionOneOfSevenAllOfType';+export * from './agentActivityCursor';+export * from './agentActivityPage';+export * from './agentActivityPageNextCursor';export * from './agentConfigKindDto';export * from './agentConfigKindDtoOneOf';export * from './agentConfigKindDtoOneOfThree';@@ -222,6 +227,7 @@ export * from './emailSearchSuggestionsQuery';export * from './emailSuggestions';export * from './emailSuggestionsBody';export * from './emailSuggestionsSubject';+export * from './entityType';export * from './executionActivity';export * from './executionId';export * from './executionRecord';@@ -237,6 +243,7 @@ export * from './extractInputRequestSearchType';export * from './extractInputResponse';export * from './extractInputResponseAllOf';export * from './fileChangeKindDto';+export * from './getAgentSessionActivityParams';export * from './gitRefDto';export * from './gitRefDtoName';export * from './gitRefDtoSha';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 1dddeb619c..d8e4ff473a 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -1091,6 +1091,87 @@}}},+ "/agent-sessions/{session_id}/activity": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read activity using the same visibility capability as the session transcript.",+ "operationId": "get_agent_session_activity",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "agentCorrelationId",+ "in": "query",+ "description": "Restrict activity to one code-mode invocation within this session.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "uuid"+ }+ },+ {+ "name": "beforeAt",+ "in": "query",+ "description": "Cursor timestamp from the previous page.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "date-time"+ }+ },+ {+ "name": "beforeId",+ "in": "query",+ "description": "Cursor activity ID from the previous page.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "uuid"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size, from 1 to 100; defaults to 50.",+ "required": false,+ "schema": {+ "type": ["integer", "null"],+ "format": "int32",+ "maximum": 100,+ "minimum": 1+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AgentActivityPage"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "401": {+ "description": ""+ },+ "403": {+ "description": ""+ }+ }+ }+ },"/agent-sessions/{session_id}/app-connections": {"post": {"tags": ["agent-sessions"],@@ -3590,6 +3671,59 @@"description": "Ordered from least to most access top -> bottom","enum": ["view", "comment", "edit", "owner"]},+ "ActivityWireRow": {+ "type": "object",+ "description": "One activity row on the wire — the realtime projection of an inserted\n`activity_events` row.",+ "required": [+ "id",+ "actor_id",+ "subject_id",+ "entity_type",+ "entity_id",+ "action",+ "occurred_at"+ ],+ "properties": {+ "action": {+ "type": "string",+ "description": "The stored action tag."+ },+ "action_payload": {+ "description": "The stored action payload, if any."+ },+ "actor_id": {+ "type": "string",+ "description": "Who mechanically acted, as a principal string (`macro|…` / `bot|…`)."+ },+ "agent_correlation_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Originating code-mode invocation, absent on older events."+ },+ "entity_id": {+ "type": "string",+ "description": "The entity acted on."+ },+ "entity_type": {+ "$ref": "#/components/schemas/EntityType",+ "description": "The kind of entity acted on."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The stored activity id."+ },+ "occurred_at": {+ "type": "string",+ "format": "date-time",+ "description": "When it happened."+ },+ "subject_id": {+ "type": "string",+ "description": "Whose activity this is (a principal string)."+ }+ }+ },"AgentAction": {"oneOf": [{@@ -3717,6 +3851,48 @@"format": "uuid","description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},+ "AgentActivityCursor": {+ "type": "object",+ "description": "Stable chronological resume position.",+ "required": ["occurredAt", "id"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Tie-breaking activity identity."+ },+ "occurredAt": {+ "type": "string",+ "format": "date-time",+ "description": "Last stored event time."+ }+ }+ },+ "AgentActivityPage": {+ "type": "object",+ "description": "One page of the activity caused by this session.",+ "required": ["activities"],+ "properties": {+ "activities": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ActivityWireRow"+ },+ "description": "Original activity rows, also retained in the affected entities' histories."+ },+ "nextCursor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AgentActivityCursor",+ "description": "Resume position, present when more raw rows remain."+ }+ ]+ }+ }+ },"AgentConfigKindDto": {"oneOf": [{@@ -5695,6 +5871,36 @@},"additionalProperties": false},+ "EntityType": {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "crm_pipeline",+ "reminder",+ "skill",+ "agent_session",+ "scheduled_action",+ "initiative",+ "database",+ "database_row",+ "form",+ "external_chat"+ ]+ },"ExecutionActivity": {"type": "object","description": "A bounded SDK operation observed during execution; not an authorization or write receipt.",diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.tsindex 310e5b80ab..c50baae7f2 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts@@ -4,6 +4,7 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { DocumentSyncEditorAgentCorrelationId } from './documentSyncEditorAgentCorrelationId';import type { DocumentSyncEditorOnBehalfOf } from './documentSyncEditorOnBehalfOf';/**@@ -12,5 +13,7 @@ import type { DocumentSyncEditorOnBehalfOf } from './documentSyncEditorOnBehalfOexport interface DocumentSyncEditor {/** User or bot that performed the edit. */actor: string;+ /** Invocation from the editor's signed document grant. */+ agent_correlation_id?: DocumentSyncEditorAgentCorrelationId;on_behalf_of?: DocumentSyncEditorOnBehalfOf;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorAgentCorrelationId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorAgentCorrelationId.tsnew file mode 100644index 0000000000..a5829eec42--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorAgentCorrelationId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Invocation from the editor's signed document grant.+ */+export type DocumentSyncEditorAgentCorrelationId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex fea95e4841..8757c5acc7 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -816,6 +816,7 @@ export * from './documentSyncContentUpdatedMetadataActor';export * from './documentSyncContentUpdatedMetadataDocumentVersionId';export * from './documentSyncContentUpdatedMetadataOnBehalfOf';export * from './documentSyncEditor';+export * from './documentSyncEditorAgentCorrelationId';export * from './documentSyncEditorOnBehalfOf';export * from './documentTeamShareResponse';export * from './documentTeamShareResponseTeamId';diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 3be2d08526..ad5f14e9f2 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -30520,6 +30520,11 @@"type": "string","description": "User or bot that performed the edit."},+ "agent_correlation_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Invocation from the editor's signed document grant."+ },"on_behalf_of": {"oneOf": [{diff --git a/crates/activity/AGENTS.md b/crates/activity/AGENTS.mdindex 60d3a2756d..26a71d9d82 100644--- a/crates/activity/AGENTS.md+++ b/crates/activity/AGENTS.md@@ -59,3 +59,5 @@ distribution.## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`++- Session activity reads preserve `agent_correlation_id` and use session visibility; entity and subject feeds retain their existing authorization.diff --git a/crates/activity/Cargo.toml b/crates/activity/Cargo.tomlindex 3fbf0066b0..f1c63a0e05 100644--- a/crates/activity/Cargo.toml+++ b/crates/activity/Cargo.toml@@ -28,6 +28,7 @@ realtime = [][dependencies]+agent_correlation = { path = "../agent_correlation" }utoipa = { workspace = true, optional = true }ai_toolset = { path = "../ai_toolset", optional = true }async-trait = { workspace = true, optional = true }diff --git a/crates/activity/src/domain/events.rs b/crates/activity/src/domain/events.rsindex 8ca3d2fb59..f1b54eabc8 100644--- a/crates/activity/src/domain/events.rs+++ b/crates/activity/src/domain/events.rs@@ -24,7 +24,11 @@ use super::models::{Activity, ActivityRecord, Actor, RecordedAction};/// One activity row on the wire — the realtime projection of an inserted/// `activity_events` row.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]pub struct ActivityWireRow {+ /// Originating code-mode invocation, absent on older events.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<Uuid>,/// The stored activity id.pub id: Uuid,/// Who mechanically acted, as a principal string (`macro|…` / `bot|…`).@@ -49,6 +53,7 @@ impl ActivityWireRow {let (action, action_payload) = activity.action.to_columns();Self {id: activity.id,+ agent_correlation_id: activity.agent_correlation_id,actor_id: activity.actor.as_ref().to_owned(),subject_id: activity.subject_id.clone(),entity_type: activity.entity_type,@@ -68,6 +73,7 @@ impl ActivityWireRow {RecordedAction::from_columns(self.action, self.action_payload);Some(ActivityRecord {id: self.id,+ agent_correlation_id: self.agent_correlation_id,actor,subject_id: self.subject_id,entity_type: self.entity_type,@@ -142,3 +148,26 @@ impl MacroEvent for ActivityMacroEvent {Self { key, event }}}++impl From<ActivityRecord> for ActivityWireRow {+ fn from(record: ActivityRecord) -> Self {+ let (action, action_payload) = match record.action {+ RecordedAction::Known(action) => {+ let (tag, payload) = action.to_columns();+ (tag.to_owned(), payload)+ }+ RecordedAction::Unknown { tag, payload } => (tag, payload),+ };+ Self {+ id: record.id,+ agent_correlation_id: record.agent_correlation_id,+ actor_id: record.actor.as_ref().to_owned(),+ subject_id: record.subject_id,+ entity_type: record.entity_type,+ entity_id: record.entity_id,+ action,+ action_payload,+ occurred_at: record.occurred_at,+ }+ }+}diff --git a/crates/activity/src/domain/events/test.rs b/crates/activity/src/domain/events/test.rsindex 1c9a7cb324..bcc75bf62b 100644--- a/crates/activity/src/domain/events/test.rs+++ b/crates/activity/src/domain/events/test.rs@@ -44,6 +44,7 @@ fn unknown_action_tags_survive_the_wire() {// A row written by a newer deployment: the tag is preserved raw rather// than dropped, mirroring reads from storage.let row = ActivityWireRow {+ agent_correlation_id: None,id: Uuid::from_u128(1),actor_id: "macro|[email protected]".to_string(),subject_id: "macro|[email protected]".to_string(),@@ -67,6 +68,7 @@ fn unknown_action_tags_survive_the_wire() {#[test]fn corrupt_actor_rows_are_skipped() {let row = ActivityWireRow {+ agent_correlation_id: None,id: Uuid::from_u128(2),actor_id: "not-a-principal".to_string(),subject_id: "macro|[email protected]".to_string(),diff --git a/crates/activity/src/domain/models.rs b/crates/activity/src/domain/models.rsindex 83b72885a8..85aac836b7 100644--- a/crates/activity/src/domain/models.rs+++ b/crates/activity/src/domain/models.rs@@ -418,6 +418,8 @@ impl RecordedAction {/// construction invariants to seal; the row already exists.#[derive(Debug, Clone, PartialEq)]pub struct ActivityRecord {+ /// Originating code-mode invocation; absent for non-agent and historical activity.+ pub agent_correlation_id: Option<Uuid>,/// The stored activity id.pub id: Uuid,/// Who mechanically acted.@@ -491,6 +493,8 @@ pub enum Ingest {#[readonly::make]#[derive(Debug, Clone, PartialEq)]pub struct Activity {+ /// Originating code-mode invocation; absent for non-agent and historical activity.+ pub agent_correlation_id: Option<Uuid>,/// Deterministic id: uuidv5 over (source event id, ordinal), so replays/// of the same broker event re-derive the same activity ids.pub id: Uuid,@@ -510,6 +514,12 @@ pub struct Activity {}impl Activity {+ /// Retain a specific editor's invocation when one event contains multiple editors.+ pub fn with_agent_correlation(mut self, id: Option<Uuid>) -> Self {+ self.agent_correlation_id = id;+ self+ }+/// Builds an activity for a [`CommonAction`] from a resolved/// [`Attribution`].pub fn attributed(@@ -597,6 +607,7 @@ impl Activity {.unwrap_or_else(|| actor.as_ref().to_owned());Self {id: activity_id(source_event_id, ordinal),+ agent_correlation_id: agent_correlation::context::current(),actor,subject_id,entity_type,diff --git a/crates/activity/src/domain/ports.rs b/crates/activity/src/domain/ports.rsindex b493a7bf94..4f6d024324 100644--- a/crates/activity/src/domain/ports.rs+++ b/crates/activity/src/domain/ports.rs@@ -242,3 +242,18 @@ pub trait EntityActivityReads: Send + Sync + 'static {limit: NonZeroU32,) -> impl Future<Output = Result<ActivityFeedPage, Self::Err>> + Send;}++/// Reads activity caused by one agent session. Its owning domain supplies access.+pub trait AgentActivityReads: Send + Sync + 'static {+ /// Persistence failure.+ type Err: std::error::Error + Send + Sync + 'static;++ /// A stable page across the session's invocations, optionally narrowed to one.+ fn agent_activity(+ &self,+ session_id: Uuid,+ correlation_id: Option<Uuid>,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ limit: NonZeroU32,+ ) -> impl Future<Output = Result<ActivityFeedPage, Self::Err>> + Send;+}diff --git a/crates/activity/src/domain/realtime/test.rs b/crates/activity/src/domain/realtime/test.rsindex 132e11b856..a72f2c76eb 100644--- a/crates/activity/src/domain/realtime/test.rs+++ b/crates/activity/src/domain/realtime/test.rs@@ -32,6 +32,7 @@ fn user(local: &str) -> MacroUserIdStr<'static> {fn wire_row(subject: &MacroUserIdStr<'static>, entity_id: &str) -> ActivityWireRow {ActivityWireRow {+ agent_correlation_id: None,id: Uuid::new_v4(),actor_id: subject.as_ref().to_owned(),subject_id: subject.as_ref().to_owned(),diff --git a/crates/activity/src/domain/service/test.rs b/crates/activity/src/domain/service/test.rsindex 23d8b1ca69..dcca699ba5 100644--- a/crates/activity/src/domain/service/test.rs+++ b/crates/activity/src/domain/service/test.rs@@ -109,6 +109,7 @@ fn time(value: &str) -> DateTime<Utc> {fn property_record(id: u128) -> ActivityRecord {ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(id),actor: Actor::new_from_user(user()),subject_id: user().to_string(),diff --git a/crates/activity/src/inbound/toolset/test.rs b/crates/activity/src/inbound/toolset/test.rsindex cb6d44974b..0bb6c8884f 100644--- a/crates/activity/src/inbound/toolset/test.rs+++ b/crates/activity/src/inbound/toolset/test.rs@@ -124,6 +124,7 @@ fn user(value: &str) -> MacroUserIdStr<'static> {fn record() -> ActivityRecord {ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(1),actor: Actor::new_from_user(user("macro|[email protected]")),subject_id: "macro|[email protected]".to_string(),diff --git a/crates/activity/src/outbound/pg_activity_repo.rs b/crates/activity/src/outbound/pg_activity_repo.rsindex 76272e010a..e9417eceab 100644--- a/crates/activity/src/outbound/pg_activity_repo.rs+++ b/crates/activity/src/outbound/pg_activity_repo.rs@@ -5,6 +5,7 @@ mod team_feed;mod test;mod timeline;+mod agent_activity;mod entity_history;use std::collections::HashMap;@@ -44,6 +45,7 @@ impl ActivityRepo for PgActivityRepo {}let mut ids = Vec::with_capacity(activities.len());+ let mut correlations = Vec::with_capacity(activities.len());let mut actor_ids = Vec::with_capacity(activities.len());let mut subject_ids = Vec::with_capacity(activities.len());let mut actions = Vec::with_capacity(activities.len());@@ -54,6 +56,7 @@ impl ActivityRepo for PgActivityRepo {for activity in activities {let (action, payload) = activity.action.to_columns();ids.push(activity.id);+ correlations.push(activity.agent_correlation_id);actor_ids.push(activity.actor.as_ref().to_owned());subject_ids.push(activity.subject_id.clone());actions.push(action.to_owned());@@ -67,10 +70,10 @@ impl ActivityRepo for PgActivityRepo {r#"INSERT INTO activity_events(id, actor_id, subject_id, action, action_payload,- entity_type, entity_id, occurred_at)+ entity_type, entity_id, occurred_at, agent_correlation_id)SELECT * FROM UNNEST($1::uuid[], $2::text[], $3::text[], $4::text[], $5::jsonb[],- $6::text[], $7::text[], $8::timestamptz[])+ $6::text[], $7::text[], $8::timestamptz[], $9::uuid[])ON CONFLICT (id) DO NOTHING"#,&ids,@@ -81,6 +84,7 @@ impl ActivityRepo for PgActivityRepo {&entity_types,&entity_ids,&occurred_ats,+ correlations.as_slice() as &[Option<Uuid>],).execute(&self.pool).await?;@@ -115,6 +119,7 @@ impl ActivityRepo for PgActivityRepo {/// One `activity_events` row as fetched, before decoding.struct StoredRow {+ agent_correlation_id: Option<Uuid>,id: Uuid,actor_id: String,action: String,@@ -163,6 +168,7 @@ impl StoredRow {}Some(ActivityRecord {id: self.id,+ agent_correlation_id: self.agent_correlation_id,actor,subject_id: self.subject_id,entity_type,@@ -194,7 +200,7 @@ impl ActivityReads for PgActivityRepo {sqlx::query_as!(StoredRow,r#"- SELECT id, actor_id, action, action_payload,+ SELECT id, agent_correlation_id, actor_id, action, action_payload,subject_id, entity_type, entity_id, occurred_atFROM activity_eventsWHERE subject_id = $1@@ -211,7 +217,7 @@ impl ActivityReads for PgActivityRepo {sqlx::query_as!(StoredRow,r#"- SELECT id, actor_id, action, action_payload,+ SELECT id, agent_correlation_id, actor_id, action, action_payload,subject_id, entity_type, entity_id, occurred_atFROM activity_eventsWHERE subject_id = $1 AND (occurred_at, id) < ($2, $3)@@ -273,7 +279,7 @@ impl ActivityReads for PgActivityRepo {let rows = sqlx::query_as!(StoredRow,r#"- SELECT a.id AS "id!", a.actor_id AS "actor_id!",+ SELECT a.id AS "id!", a.agent_correlation_id, a.actor_id AS "actor_id!",a.action AS "action!", a.action_payload,a.subject_id AS "subject_id!",a.entity_type AS "entity_type!", a.entity_id AS "entity_id!",@@ -410,7 +416,7 @@ impl ActivityReads for PgActivityRepo {let mut rows = sqlx::query_as!(StoredRow,r#"- SELECT id, actor_id, action, action_payload,+ SELECT id, agent_correlation_id, actor_id, action, action_payload,subject_id, entity_type, entity_id, occurred_atFROM activity_eventsWHERE subject_id = $1diff --git a/crates/activity/src/outbound/pg_activity_repo/agent_activity.rs b/crates/activity/src/outbound/pg_activity_repo/agent_activity.rsnew file mode 100644index 0000000000..50f4ff7b8b--- /dev/null+++ b/crates/activity/src/outbound/pg_activity_repo/agent_activity.rs@@ -0,0 +1,55 @@+//! Session-correlated history; session visibility is enforced by its caller.+use super::{PgActivityRepo, StoredRow};+use crate::domain::ports::{ActivityFeedPage, AgentActivityReads};+use chrono::{DateTime, Utc};+use std::num::NonZeroU32;+use uuid::Uuid;++impl AgentActivityReads for PgActivityRepo {+ type Err = sqlx::Error;++ async fn agent_activity(+ &self,+ session_id: Uuid,+ correlation_id: Option<Uuid>,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ limit: NonZeroU32,+ ) -> Result<ActivityFeedPage, Self::Err> {+ let (before_at, before_id) = cursor.unzip();+ let limit = limit.get() as usize;+ let fetch = limit as i64 + 1;+ // Bound each invocation's index scan before merging the session page.+ let mut rows = sqlx::query_as!(+ StoredRow,+ r#"SELECT e.id, e.agent_correlation_id, e.actor_id, e.action,+ e.action_payload, e.subject_id, e.entity_type, e.entity_id, e.occurred_at+ FROM agent_correlations c+ CROSS JOIN LATERAL (+ SELECT id, agent_correlation_id, actor_id, action, action_payload,+ subject_id, entity_type, entity_id, occurred_at+ FROM activity_events+ WHERE agent_correlation_id = c.id+ AND (occurred_at, id) < (COALESCE($3::timestamptz, 'infinity'), COALESCE($4::uuid, 'ffffffff-ffff-ffff-ffff-ffffffffffff'))+ ORDER BY occurred_at DESC, id DESC LIMIT $5+ ) e+ WHERE c.agent_session_id = $1 AND ($2::uuid IS NULL OR c.id = $2)+ ORDER BY e.occurred_at DESC, e.id DESC LIMIT $5"#,+ session_id,+ correlation_id,+ before_at,+ before_id,+ fetch,+ )+ .fetch_all(&self.pool)+ .await?;+ let more = rows.len() > limit;+ rows.truncate(limit);+ let next = 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/entity_history.rs b/crates/activity/src/outbound/pg_activity_repo/entity_history.rsindex 325e631fd8..d0b607f25e 100644--- a/crates/activity/src/outbound/pg_activity_repo/entity_history.rs+++ b/crates/activity/src/outbound/pg_activity_repo/entity_history.rs@@ -22,13 +22,13 @@ impl EntityActivityReads for PgActivityRepo {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+ r#"SELECT id, agent_correlation_id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_atFROM activity_events WHERE entity_type = $1 AND entity_id = $2ORDER 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+ r#"SELECT id, agent_correlation_id, actor_id, action, action_payload, subject_id, entity_type, entity_id, occurred_atFROM 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,diff --git a/crates/activity/src/outbound/pg_activity_repo/team_feed.rs b/crates/activity/src/outbound/pg_activity_repo/team_feed.rsindex 1599339157..fd3f7c6690 100644--- a/crates/activity/src/outbound/pg_activity_repo/team_feed.rs+++ b/crates/activity/src/outbound/pg_activity_repo/team_feed.rs@@ -38,6 +38,7 @@ pub(super) const TEAM_SCAN: TeamScan = TeamScan {/// One row of the team feed query: a visible row, or the frontier.struct TeamFeedRow {+ agent_correlation_id: Option<Uuid>,id: Uuid,actor_id: String,action: String,@@ -56,6 +57,7 @@ impl TeamFeedRow {fn into_stored(self) -> StoredRow {StoredRow {+ agent_correlation_id: self.agent_correlation_id,id: self.id,actor_id: self.actor_id,action: self.action,diff --git a/crates/activity/src/outbound/pg_activity_repo/team_feed.sql b/crates/activity/src/outbound/pg_activity_repo/team_feed.sqlindex 9935d7b354..20fa6cf327 100644--- a/crates/activity/src/outbound/pg_activity_repo/team_feed.sql+++ b/crates/activity/src/outbound/pg_activity_repo/team_feed.sql@@ -87,7 +87,7 @@ scanned AS (ELSE falseEND AS visibleFROM (- SELECT e.id, e.actor_id, e.action, e.action_payload, e.subject_id,+ SELECT e.id, e.agent_correlation_id, e.actor_id, e.action, e.action_payload, e.subject_id,e.entity_type, e.entity_id, e.occurred_at,-- Only these id columns are uuids; a malformed id-- must hide its row, not fail the page.@@ -121,7 +121,7 @@ boundary AS (LIMIT 1)(- SELECT s.id AS "id!", s.actor_id AS "actor_id!", s.action AS "action!",+ SELECT s.id AS "id!", s.agent_correlation_id, s.actor_id AS "actor_id!", s.action AS "action!",s.action_payload, s.subject_id AS "subject_id!",s.entity_type AS "entity_type!", s.entity_id AS "entity_id!",s.occurred_at AS "occurred_at!", false AS "is_boundary!"@@ -134,6 +134,6 @@ boundary AS (LIMIT $4)UNION ALL-SELECT b.id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,+SELECT b.id, b.agent_correlation_id, b.actor_id, b.action, b.action_payload, b.subject_id, b.entity_type,b.entity_id, b.occurred_at, trueFROM boundary bdiff --git a/crates/activity/src/outbound/pg_activity_repo/test.rs b/crates/activity/src/outbound/pg_activity_repo/test.rsindex 21b0c9dd10..ee01c9b0f3 100644--- a/crates/activity/src/outbound/pg_activity_repo/test.rs+++ b/crates/activity/src/outbound/pg_activity_repo/test.rs@@ -944,3 +944,107 @@ async fn timeline_index_skips_exactly_the_unindexed_actions(pool: PgPool) {format!("(action <> ALL (ARRAY[{}]))", tags.join(", ")));}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn session_activity_preserves_invocations_and_paginates_without_entity_grants(pool: PgPool) {+ use crate::domain::ports::AgentActivityReads;+ let session = Uuid::now_v7();+ let other = Uuid::now_v7();+ let first_run = Uuid::now_v7();+ let second_run = Uuid::now_v7();+ let foreign_run = Uuid::now_v7();+ for id in [session, other] {+ sqlx::query!("INSERT INTO agent_session (id, owner_id, bot_id, model, harness, workspace) VALUES ($1, 'macro|[email protected]', $2, 'test', 'test', '/workspace')", id, Uuid::now_v7()).execute(&pool).await.unwrap();+ }+ for (id, parent) in [+ (first_run, session),+ (second_run, session),+ (foreign_run, other),+ ] {+ sqlx::query!(+ "INSERT INTO agent_correlations (id, agent_session_id) VALUES ($1, $2)",+ id,+ parent+ )+ .execute(&pool)+ .await+ .unwrap();+ }+ let repo = PgActivityRepo::new(pool.clone());+ let timestamp = Utc::now();+ let rows: Vec<_> = [+ Some(first_run),+ Some(second_run),+ Some(first_run),+ Some(foreign_run),+ None,+ ]+ .into_iter()+ .enumerate()+ .map(|(index, correlation)| {+ Activity::common(+ Uuid::from_u128(100 + index as u128),+ 0,+ Actor::new_from_user(user("macro|[email protected]")),+ None,+ EntityType::Document,+ "private-document",+ CommonAction::Edited,+ timestamp,+ )+ .with_agent_correlation(correlation)+ })+ .collect();+ repo.insert_activities(&rows).await.unwrap();+ repo.insert_activities(&rows).await.unwrap();+ let page = repo+ .agent_activity(session, None, None, nz(2))+ .await+ .unwrap();+ assert_eq!(page.records.len(), 2);+ let next = repo+ .agent_activity(session, None, page.next, nz(2))+ .await+ .unwrap();+ assert_eq!(next.records.len(), 1);+ assert!(next.next.is_none());+ assert!(page.records.iter().all(|row| row.id != next.records[0].id));+ let filtered = repo+ .agent_activity(session, Some(first_run), None, nz(10))+ .await+ .unwrap();+ assert_eq!(filtered.records.len(), 2);+ assert!(+ filtered+ .records+ .iter()+ .all(|row| row.agent_correlation_id == Some(first_run))+ );+ assert!(+ repo.agent_activity(session, Some(foreign_run), None, nz(10))+ .await+ .unwrap()+ .records+ .is_empty()+ );+ // Session deletion removes its mapping, never the entity's existing history.+ sqlx::query!("DELETE FROM agent_session WHERE id = $1", session)+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ repo.agent_activity(session, None, None, nz(10))+ .await+ .unwrap()+ .records+ .is_empty()+ );+ assert_eq!(+ repo.entity_feed(EntityType::Document, "private-document", None, nz(10))+ .await+ .unwrap()+ .records+ .len(),+ 5+ );+}diff --git a/crates/agent_code_mode/AGENTS.md b/crates/agent_code_mode/AGENTS.mdindex 5022c29118..da6947d405 100644--- a/crates/agent_code_mode/AGENTS.md+++ b/crates/agent_code_mode/AGENTS.md@@ -112,3 +112,5 @@ The web and SDK review types are generated from these Rust types with specta(`src/bin/export_review_types.rs`, `just gen-agent-review-types` in `apps/web`).Regenerate after changing a review type or a type a draft or result reuses; CIfails on stale output.++- Create fresh invocation attribution in the credential issuer; managed MCP session provenance comes only from verified request context.diff --git a/crates/agent_code_mode/src/domain/user.rs b/crates/agent_code_mode/src/domain/user.rsindex 74eb36c1f1..6a9568dd35 100644--- a/crates/agent_code_mode/src/domain/user.rs+++ b/crates/agent_code_mode/src/domain/user.rs@@ -1,4 +1,4 @@-//! Code execution for an authenticated user outside any agent session.+//! Authenticated MCP code execution, optionally attributed to a managed session.use super::{CodeModeError, ExecutionActivity, ExecutionStatus,service::{Reviews, settle, validate_request},@@ -22,10 +22,11 @@ pub trait UserExecutionCredentials: Send + Sync + 'static {&self,user: &MacroUserIdStr<'static>,caller: &ToolCaller,+ session: Option<uuid::Uuid>,) -> Result<RunEnvironment, CodeModeError>;}-/// Outcome returned straight to the caller; nothing is persisted.+/// Outcome returned to the caller without a saved execution journal.#[derive(Clone, Serialize, Deserialize, JsonSchema)]#[serde(rename_all = "camelCase")]pub struct UserExecutionReceipt {@@ -41,7 +42,8 @@ pub struct UserExecutionReceipt {pub error: Option<String>,}-/// Run a program as the authenticated user, with no session, journal or reviews.+/// Run a program as the authenticated user, with optional session attribution+/// but no execution journal or reviews.#[async_trait]pub trait UserCodeMode: Send + Sync + 'static {/// Execute and wait for the outcome. Cancelling stops the process; completed@@ -50,6 +52,7 @@ pub trait UserCodeMode: Send + Sync + 'static {&self,user: &MacroUserIdStr<'static>,caller: &ToolCaller,+ session: Option<uuid::Uuid>,request: ExecuteRequest,cancel: CancellationToken,) -> Result<UserExecutionReceipt, CodeModeError>;@@ -91,11 +94,12 @@ impl UserCodeMode for UserCodeModeService {&self,user: &MacroUserIdStr<'static>,caller: &ToolCaller,+ session: Option<uuid::Uuid>,request: ExecuteRequest,cancel: CancellationToken,) -> Result<UserExecutionReceipt, CodeModeError> {validate_request(&request)?;- let environment = self.credentials.issue(user, caller).await?;+ let environment = self.credentials.issue(user, caller, session).await?;let (progress, mut updates) = tokio::sync::mpsc::channel(512);let execution = self.executor.execute_program_with_progress(request,diff --git a/crates/agent_code_mode/src/domain/user/test.rs b/crates/agent_code_mode/src/domain/user/test.rsindex 87dfc490f7..a00248f0b4 100644--- a/crates/agent_code_mode/src/domain/user/test.rs+++ b/crates/agent_code_mode/src/domain/user/test.rs@@ -11,6 +11,7 @@ impl UserExecutionCredentials for Credentials {&self,user: &MacroUserIdStr<'static>,caller: &ToolCaller,+ _session: Option<uuid::Uuid>,) -> Result<RunEnvironment, CodeModeError> {self.0.lock()@@ -79,7 +80,7 @@ async fn runs_as_the_authenticated_user_and_returns_data_with_activity() {0xA1,)));let receipt = service- .execute(&user(), &caller, request(), CancellationToken::new())+ .execute(&user(), &caller, None, request(), CancellationToken::new()).await.unwrap();@@ -111,6 +112,7 @@ async fn review_references_fail_outside_a_session() {.execute(&user(),&ToolCaller::ApiKey,+ None,request(),CancellationToken::new(),)@@ -142,6 +144,7 @@ async fn invalid_requests_are_rejected_before_minting_a_credential() {.execute(&user(),&ToolCaller::ApiKey,+ None,request,CancellationToken::new())@@ -163,6 +166,7 @@ async fn an_empty_reviews_list_is_dropped() {.execute(&user(),&ToolCaller::ApiKey,+ None,request(),CancellationToken::new(),)diff --git a/crates/agent_code_mode/src/inbound/toolset.rs b/crates/agent_code_mode/src/inbound/toolset.rsindex ba43ce504b..8719817273 100644--- a/crates/agent_code_mode/src/inbound/toolset.rs+++ b/crates/agent_code_mode/src/inbound/toolset.rs@@ -49,6 +49,8 @@ pub struct UserCodeModeToolContext {/// Who the authenticated request came from; the adapter builds a context/// per call, so there is no default.pub caller: ai_toolset::ToolCaller,+ /// Session provenance verified by the managed MCP bearer middleware.+ pub session: Option<uuid::Uuid>,}/// Code mode for clients outside agent sessions, such as the public MCP.@@ -188,6 +190,7 @@ impl AsyncTool<UserCodeModeToolContext> for UserExecuteCode {.execute(&request.user_id,&context.caller,+ context.session,ExecuteRequest {source: self.source.clone(),timeout_ms: self.timeout_ms,diff --git a/crates/agent_correlation/AGENTS.md b/crates/agent_correlation/AGENTS.mdnew file mode 100644index 0000000000..601f33f64c--- /dev/null+++ b/crates/agent_correlation/AGENTS.md@@ -0,0 +1,29 @@+# agent_correlation++## What it is++Durable attribution of each code-mode invocation to its agent session. Correlation+does not grant access or change the JWT's acting user.++## Start here++- `src/domain.rs`: repository contract and agent-binding validation.+- `src/context.rs`: async context; capture before spawning, scope each message.+- `src/inbound.rs`: optional signed-claim extractor and HTTP propagation.+- `src/outbound.rs`: invocation mappings and session-agent lookup on the primary.++## Boundaries++- Owns `agent_correlations`; reads the session's bound agent for validation.+- Depends on `macro_auth` only for the HTTP adapter.+- Used by code-mode credential minting, HTTP services, and the event broker.++## Checks++- `cargo test -p agent_correlation --all-features`.++## Gotchas++- Never read correlation from an unsigned header or use it as authority.+- Do not check session state: accepted work can complete after a session ends.+- Session deletion cascades mappings; activity retains its existing entity lifecycle.diff --git a/crates/agent_correlation/CLAUDE.md b/crates/agent_correlation/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/agent_correlation/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/agent_correlation/Cargo.toml b/crates/agent_correlation/Cargo.tomlnew file mode 100644index 0000000000..f66e93d383--- /dev/null+++ b/crates/agent_correlation/Cargo.toml@@ -0,0 +1,30 @@+[package]+name = "agent_correlation"+version = "0.1.0"+edition = "2024"+publish = false++[features]+default = []+http = ["dep:axum", "dep:macro_auth", "dep:serde_urlencoded"]+postgres = ["dep:sqlx"]++[dependencies]+async-trait = { workspace = true }+axum = { workspace = true, optional = true }+macro_auth = { path = "../macro_auth", optional = true }+rootcause = { workspace = true }+serde = { workspace = true }+serde_urlencoded = { workspace = true, optional = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["rt", "macros"] }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_auth = { path = "../macro_auth", features = ["testing"] }+macro_db_migrator = { path = "../macro_db_migrator" }+serde_json = { workspace = true }+diff --git a/crates/agent_correlation/src/context.rs b/crates/agent_correlation/src/context.rsnew file mode 100644index 0000000000..f7b21c331a--- /dev/null+++ b/crates/agent_correlation/src/context.rs@@ -0,0 +1,50 @@+//! Explicit async propagation, independent of trace sampling and subscribers.++use uuid::Uuid;++tokio::task_local! {+ static CORRELATION: Option<Uuid>;+}++/// The invocation accepted at the current request or message boundary.+pub fn current() -> Option<Uuid> {+ CORRELATION.try_with(|id| *id).ok().flatten()+}++/// Run work with the correlation accepted at its boundary. `None` clears any+/// surrounding context, preventing uncorrelated work from inheriting attribution.+pub async fn scope<F: Future>(id: Option<Uuid>, future: F) -> F::Output {+ CORRELATION.scope(id, future).await+}++/// Capture attribution before handing a future to another task.+pub fn capture<F: Future>(future: F) -> impl Future<Output = F::Output> {+ scope(current(), future)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn concurrent_scopes_and_captured_tasks_do_not_leak() {+ let first = Uuid::now_v7();+ let second = Uuid::now_v7();+ let (a, b) = tokio::join!(+ scope(Some(first), async {+ tokio::task::yield_now().await;+ let child = tokio::spawn(capture(async { current() }));+ scope(None, async { assert_eq!(current(), None) }).await;+ assert_eq!(current(), Some(first));+ child.await.unwrap()+ }),+ scope(Some(second), async {+ tokio::task::yield_now().await;+ current()+ }),+ );+ assert_eq!(a, Some(first));+ assert_eq!(b, Some(second));+ assert_eq!(current(), None);+ }+}diff --git a/crates/agent_correlation/src/domain.rs b/crates/agent_correlation/src/domain.rsnew file mode 100644index 0000000000..08e7296c61--- /dev/null+++ b/crates/agent_correlation/src/domain.rs@@ -0,0 +1,102 @@+//! Correlation storage contract and validation, separate from authorization.++use async_trait::async_trait;+use uuid::Uuid;++/// The session and its bound agent, resolved from durable state.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Correlation {+ /// Originating agent session.+ pub session_id: Uuid,+ /// Agent bound to that session.+ pub agent_id: Uuid,+}++/// Durable mappings owned by agent correlation.+#[async_trait]+pub trait CorrelationRepository: Send + Sync {+ /// Record a fresh invocation only if the session belongs to the given agent.+ async fn create(&self, session: Uuid, agent: Uuid) -> Result<Uuid, CorrelationError>;+ /// Resolve the invocation and the session's bound agent, without a state check.+ async fn find(&self, id: Uuid) -> Result<Option<Correlation>, CorrelationError>;+}++/// Invalid attribution or an unavailable attribution store.+#[derive(Debug, thiserror::Error)]+pub enum CorrelationError {+ /// Signed correlation must also identify the executing agent.+ #[error("agent_correlation_id requires a signed agent_id")]+ MissingAgent,+ /// The mapping or its session no longer exists.+ #[error("agent_correlation_id does not identify an agent session")]+ NotFound,+ /// The signed agent does not match the session's agent.+ #[error("agent_correlation_id belongs to a different agent")]+ AgentMismatch,+ /// Storage failure; never report as invalid caller input.+ #[error("agent correlation storage is unavailable")]+ Unavailable(rootcause::Report),+}++/// Validate attribution without changing the request's acting user or access.+#[tracing::instrument(skip(repository), err)]+pub async fn validate<R: CorrelationRepository + ?Sized>(+ repository: &R,+ id: Uuid,+ agent: Option<Uuid>,+) -> Result<Correlation, CorrelationError> {+ let agent = agent.ok_or(CorrelationError::MissingAgent)?;+ let correlation = repository+ .find(id)+ .await?+ .ok_or(CorrelationError::NotFound)?;+ if correlation.agent_id != agent {+ return Err(CorrelationError::AgentMismatch);+ }+ Ok(correlation)+}++#[cfg(test)]+mod tests {+ use super::*;++ struct Repository(Option<Correlation>);++ #[async_trait]+ impl CorrelationRepository for Repository {+ async fn create(&self, _: Uuid, _: Uuid) -> Result<Uuid, CorrelationError> {+ unreachable!()+ }+ async fn find(&self, _: Uuid) -> Result<Option<Correlation>, CorrelationError> {+ Ok(self.0)+ }+ }++ #[tokio::test]+ async fn attribution_requires_an_existing_mapping_for_the_signed_agent() {+ let correlation = Correlation {+ session_id: Uuid::now_v7(),+ agent_id: Uuid::now_v7(),+ };+ let repo = Repository(Some(correlation));+ let id = Uuid::now_v7();+ assert_eq!(+ validate(&repo, id, Some(correlation.agent_id))+ .await+ .unwrap(),+ correlation+ );+ assert!(matches!(+ validate(&repo, id, None).await,+ Err(CorrelationError::MissingAgent)+ ));+ assert!(matches!(+ validate(&repo, id, Some(Uuid::now_v7())).await,+ Err(CorrelationError::AgentMismatch)+ ));+ assert!(matches!(+ validate(&Repository(None), id, Some(correlation.agent_id)).await,+ Err(CorrelationError::NotFound)+ ));+ }+}diff --git a/crates/agent_correlation/src/inbound.rs b/crates/agent_correlation/src/inbound.rsnew file mode 100644index 0000000000..9f6bec7c68--- /dev/null+++ b/crates/agent_correlation/src/inbound.rs@@ -0,0 +1,149 @@+//! Optional attribution extraction and request-scoped propagation.++use crate::domain::{CorrelationError, CorrelationRepository, validate};+use axum::{+ Json,+ extract::{FromRef, FromRequestParts, Request, State},+ http::{StatusCode, request::Parts},+ middleware::Next,+ response::{IntoResponse, Response},+};+use macro_auth::{+ headers::AccessTokenExtractor,+ middleware::decode_jwt::{JwtToken, JwtValidationArgs},+};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tracing::Instrument;+use uuid::Uuid;++/// Resources used exclusively for verifying optional attribution.+#[derive(Clone)]+pub struct CorrelationState {+ /// Existing JWT verifier configuration.+ pub jwt: JwtValidationArgs,+ /// Primary-database mapping lookup.+ pub repository: Arc<dyn CorrelationRepository>,+}++#[cfg(feature = "postgres")]+impl CorrelationState {+ /// Compose attribution validation from an existing primary pool and verifier.+ pub fn new(pool: sqlx::PgPool, jwt: JwtValidationArgs) -> Self {+ Self {+ jwt,+ repository: Arc::new(crate::outbound::PgCorrelationRepository(pool)),+ }+ }+}++/// An optional signed and validated invocation ID. It grants no authorization.+pub struct AgentCorrelationExtractor(pub Option<Uuid>);++#[derive(Deserialize)]+struct QueryToken {+ #[serde(rename = "macro-api-token")]+ token: Option<String>,+}++impl<S: Send + Sync> FromRequestParts<S> for AgentCorrelationExtractor+where+ CorrelationState: FromRef<S>,+{+ type Rejection = CorrelationRejection;++ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {+ let state = CorrelationState::from_ref(state);+ let query = parts+ .uri+ .query()+ .and_then(|q| serde_urlencoded::from_str::<QueryToken>(q).ok())+ .and_then(|q| q.token);+ let token = match query {+ Some(token) => Some(token),+ None => AccessTokenExtractor::from_request_parts(parts, &())+ .await+ .ok()+ .map(|token| token.as_ref().to_owned()),+ };+ let Some(token) = token else {+ return Ok(Self(None));+ };+ // Authentication remains the route's responsibility. Public webhooks and+ // non-Macro credentials may share the listener; only a verified Macro+ // JWT can introduce attribution, never an unsigned header or claim.+ let Ok(JwtToken::MacroApiToken(token)) =+ macro_auth::middleware::decode_jwt::handler(&state.jwt, &token)+ else {+ return Ok(Self(None));+ };+ let Some(id) = token.agent_correlation_id else {+ return Ok(Self(None));+ };+ let correlation = validate(state.repository.as_ref(), id, token.agent_id)+ .await+ .map_err(CorrelationRejection)?;+ tracing::info!(agent_correlation_id = %id, agent_session_id = %correlation.session_id, "accepted agent attribution");+ Ok(Self(Some(id)))+ }+}++/// A client-safe attribution failure, separate from authorization failures.+#[derive(Debug)]+pub struct CorrelationRejection(CorrelationError);++impl IntoResponse for CorrelationRejection {+ fn into_response(self) -> Response {+ #[derive(Serialize)]+ struct ErrorBody {+ message: String,+ }+ let status = match &self.0 {+ CorrelationError::MissingAgent => StatusCode::BAD_REQUEST,+ CorrelationError::NotFound => StatusCode::NOT_FOUND,+ CorrelationError::AgentMismatch => StatusCode::FORBIDDEN,+ CorrelationError::Unavailable(error) => {+ tracing::error!(?error, "agent correlation lookup failed");+ StatusCode::SERVICE_UNAVAILABLE+ }+ };+ (+ status,+ Json(ErrorBody {+ message: self.0.to_string(),+ }),+ )+ .into_response()+ }+}++/// Validate before invoking any handler, then isolate correlation to this request.+pub fn propagate(+ state: State<CorrelationState>,+ request: Request,+ next: Next,+) -> impl Future<Output = Response> + Send {+ propagate_request(state, request, next)+}++async fn propagate_request(+ State(state): State<CorrelationState>,+ request: Request,+ next: Next,+) -> Response {+ let (mut parts, body) = request.into_parts();+ match AgentCorrelationExtractor::from_request_parts(&mut parts, &state).await {+ Ok(AgentCorrelationExtractor(id)) => {+ crate::context::scope(id, next.run(Request::from_parts(parts, body)))+ .instrument(tracing::info_span!(+ "agent_sdk_request",+ agent_correlation_id = id.map(|id| id.to_string())+ ))+ .await+ }+ Err(error) => error.into_response(),+ }+}++#[cfg(test)]+mod test;diff --git a/crates/agent_correlation/src/inbound/test.rs b/crates/agent_correlation/src/inbound/test.rsnew file mode 100644index 0000000000..ad40d0c8df--- /dev/null+++ b/crates/agent_correlation/src/inbound/test.rs@@ -0,0 +1,95 @@+use super::*;+use crate::domain::Correlation;+use async_trait::async_trait;+use axum::http::Request;+use macro_auth::macro_api_token::{EncodeMacroApiTokenArgs, encode_macro_api_token};+use std::sync::atomic::{AtomicUsize, Ordering};++const PRIVATE: &str = include_str!(+ "../../../../tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.private.pem"+);+const PUBLIC: &str = include_str!(+ "../../../../tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.public.pem"+);++struct Repository {+ calls: AtomicUsize,+}+#[async_trait]+impl CorrelationRepository for Repository {+ async fn create(&self, _: Uuid, _: Uuid) -> Result<Uuid, CorrelationError> {+ unreachable!()+ }+ async fn find(&self, id: Uuid) -> Result<Option<Correlation>, CorrelationError> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Ok((id == Uuid::from_u128(1)).then_some(Correlation {+ session_id: Uuid::from_u128(2),+ agent_id: Uuid::from_u128(3),+ }))+ }+}+fn token(correlation: Option<Uuid>, agent: Option<Uuid>) -> String {+ encode_macro_api_token(EncodeMacroApiTokenArgs {+ fusionauth_id: "fixture".into(),+ macro_user_id: "macro|[email protected]".into(),+ organization_id: None,+ issuer: "fixture".into(),+ private_key: PRIVATE.into(),+ expiry_seconds: 60,+ agent_id: agent,+ agent_via: None,+ agent_correlation_id: correlation,+ agent_session_id: None,+ })+ .unwrap()+}++#[tokio::test]+async fn optional_claim_is_validated_before_a_handler_can_use_it() {+ let repository = Arc::new(Repository {+ calls: AtomicUsize::new(0),+ });+ let state = CorrelationState {+ jwt: JwtValidationArgs::testing_macro_token("fixture", PUBLIC),+ repository: repository.clone(),+ };+ for bearer in [None, Some(token(None, None))] {+ let mut request = Request::builder()+ .uri("/")+ .header("x-agent-correlation-id", Uuid::from_u128(1).to_string());+ if let Some(bearer) = bearer {+ request = request.header("authorization", format!("Bearer {bearer}"));+ }+ let (mut parts, _) = request.body(()).unwrap().into_parts();+ assert!(+ AgentCorrelationExtractor::from_request_parts(&mut parts, &state)+ .await+ .unwrap()+ .0+ .is_none()+ );+ }+ assert_eq!(repository.calls.load(Ordering::SeqCst), 0);+ for (id, agent, expected) in [+ (1, Some(3), StatusCode::OK),+ (1, Some(4), StatusCode::FORBIDDEN),+ (5, Some(3), StatusCode::NOT_FOUND),+ (1, None, StatusCode::BAD_REQUEST),+ ] {+ let bearer = token(Some(Uuid::from_u128(id)), agent.map(Uuid::from_u128));+ let (mut parts, _) = Request::builder()+ .uri("/")+ .header("authorization", format!("Bearer {bearer}"))+ .body(())+ .unwrap()+ .into_parts();+ let status = match AgentCorrelationExtractor::from_request_parts(&mut parts, &state).await {+ Ok(AgentCorrelationExtractor(found)) => {+ assert_eq!(found, Some(Uuid::from_u128(id)));+ StatusCode::OK+ }+ Err(error) => error.into_response().status(),+ };+ assert_eq!(status, expected);+ }+}diff --git a/crates/agent_correlation/src/lib.rs b/crates/agent_correlation/src/lib.rsnew file mode 100644index 0000000000..af324c9452--- /dev/null+++ b/crates/agent_correlation/src/lib.rs@@ -0,0 +1,13 @@+#![deny(missing_docs)]+//! Attribution of code-mode work to its originating agent session.+//!+//! This context grants no access. HTTP validates the signed claim once, before+//! application work; durable events retain the accepted ID independently of the+//! lifetime of the originating request or session.++pub mod context;+pub mod domain;+#[cfg(feature = "http")]+pub mod inbound;+#[cfg(feature = "postgres")]+pub mod outbound;diff --git a/crates/agent_correlation/src/outbound.rs b/crates/agent_correlation/src/outbound.rsnew file mode 100644index 0000000000..ccd721e9b1--- /dev/null+++ b/crates/agent_correlation/src/outbound.rs@@ -0,0 +1,67 @@+//! Postgres persistence for invocation-to-session mappings.++use crate::domain::{Correlation, CorrelationError, CorrelationRepository};+use async_trait::async_trait;+use uuid::Uuid;++/// Shared primary-database correlation repository.+#[derive(Clone)]+pub struct PgCorrelationRepository(pub sqlx::PgPool);++#[async_trait]+impl CorrelationRepository for PgCorrelationRepository {+ #[tracing::instrument(skip(self), err)]+ async fn create(&self, session: Uuid, agent: Uuid) -> Result<Uuid, CorrelationError> {+ let id = Uuid::now_v7();+ let inserted = sqlx::query_scalar!(+ "INSERT INTO agent_correlations (id, agent_session_id) SELECT $1, id FROM agent_session WHERE id = $2 AND bot_id = $3 RETURNING id",+ id, session, agent,+ ).fetch_optional(&self.0).await+ .map_err(|error| CorrelationError::Unavailable(rootcause::report!(error).into_dynamic()))?;+ inserted.ok_or(CorrelationError::AgentMismatch)+ }++ #[tracing::instrument(skip(self), err)]+ async fn find(&self, id: Uuid) -> Result<Option<Correlation>, CorrelationError> {+ sqlx::query_as!(Correlation,+ "SELECT c.agent_session_id AS session_id, s.bot_id AS agent_id FROM agent_correlations c JOIN agent_session s ON s.id = c.agent_session_id WHERE c.id = $1",+ id,+ ).fetch_optional(&self.0).await+ .map_err(|error| CorrelationError::Unavailable(rootcause::report!(error).into_dynamic()))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use macro_db_migrator::MACRO_DB_MIGRATIONS;++ #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+ async fn invocations_are_fresh_bound_to_agent_and_independent_of_session_state(+ pool: sqlx::PgPool,+ ) {+ let session = Uuid::now_v7();+ let agent = Uuid::now_v7();+ sqlx::query!("INSERT INTO agent_session (id, owner_id, bot_id, model, harness, workspace, status) VALUES ($1, 'macro|[email protected]', $2, 'test', 'test', '/workspace', 'disconnected')", session, agent).execute(&pool).await.unwrap();+ let repo = PgCorrelationRepository(pool.clone());+ let first = repo.create(session, agent).await.unwrap();+ let second = repo.create(session, agent).await.unwrap();+ assert_ne!(first, second);+ assert_eq!(+ repo.find(first).await.unwrap(),+ Some(Correlation {+ session_id: session,+ agent_id: agent+ })+ );+ assert!(matches!(+ repo.create(session, Uuid::now_v7()).await,+ Err(CorrelationError::AgentMismatch)+ ));+ sqlx::query!("DELETE FROM agent_session WHERE id = $1", session)+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(repo.find(first).await.unwrap(), None);+ }+}diff --git a/crates/agent_egress/AGENTS.md b/crates/agent_egress/AGENTS.mdindex d497f2d022..a7bd1f3ff2 100644--- a/crates/agent_egress/AGENTS.md+++ b/crates/agent_egress/AGENTS.md@@ -67,11 +67,13 @@ retain their existing session/repository identities.Session-egress Macro API tokens (`MacroApiTokens::mint`) carry the session'sbound agent (`agent_session.bot_id`, read off the row as `SessionGrant.agent`) as-their signed `agent_id` claim, so Macro's tools write as that agent. The bot+their signed `agent_id` claim and retain `agent_session_id` provenance, so+code mode can mint a fresh invocation correlation. Cache credentials by owner,+agent, and session. The botnever comes from the request. `MacroApiTokenSigner::mint_for_agent` callers(code mode) choose the claim themselves, plus an optional signed `agent_via`client label (public MCP code mode signs the MCP client's name); `mint_for`-signs neither.+signs none of these claims.## Gotchasdiff --git a/crates/agent_egress/Cargo.toml b/crates/agent_egress/Cargo.tomlindex b366137d01..13f14a2ee3 100644--- a/crates/agent_egress/Cargo.toml+++ b/crates/agent_egress/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+uuid = { workspace = true }# `AgentSessionId` only. `default-features = false` drops the crate's CLI# binaries (clap, tokio), which the vocabulary does not need.agent_fold = { path = "../folds/agent_fold", default-features = false }@@ -74,5 +75,4 @@ futures = { workspace = true }# Building the stored OAuth grants the custom-server resolver reads.rmcp = { workspace = true, features = ["auth"] }tokio = { workspace = true, features = ["macros", "rt"] }-uuid = { workspace = true }tower = { workspace = true }diff --git a/crates/agent_egress/src/domain/ports.rs b/crates/agent_egress/src/domain/ports.rsindex 58d8d01cdb..f1cd1700b1 100644--- a/crates/agent_egress/src/domain/ports.rs+++ b/crates/agent_egress/src/domain/ports.rs@@ -61,6 +61,7 @@ pub trait McpCredentials: Send + Sync {&self,owner: &MacroUserIdStr<'static>,agent: bot_id::BotId,+ session: uuid::Uuid,destination: &McpDestination,) -> impl Future<Output = Result<McpResolution, EgressError>> + Send;}diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rsindex 7e4e97f0d9..74f1fe521e 100644--- a/crates/agent_egress/src/domain/service.rs+++ b/crates/agent_egress/src/domain/service.rs@@ -268,7 +268,12 @@ where) => {let (call, answer): (UpstreamCall, Option<Answer>) = match self.credentials- .resolve(&grant.owner, grant.agent, destination)+ .resolve(+ &grant.owner,+ grant.agent,+ grant.session.as_uuid(),+ destination,+ ).await?{McpResolution::Connected(call) => (call, None),diff --git a/crates/agent_egress/src/domain/service/actor.rs b/crates/agent_egress/src/domain/service/actor.rsindex 677afed485..cbbe2cea13 100644--- a/crates/agent_egress/src/domain/service/actor.rs+++ b/crates/agent_egress/src/domain/service/actor.rs@@ -116,7 +116,7 @@ wheredestination: &McpDestination,listing: bool,) -> Result<Result<UpstreamCall, String>, EgressError> {- let resolution = match self.credentials.resolve(user, grant.agent, destination).await {+ let resolution = match self.credentials.resolve(user, grant.agent, grant.session.as_uuid(), destination).await {Ok(resolution) => resolution,Err(EgressError::UnknownCustomServer(_)) if !listing => return Ok(Err("This custom MCP server is not connected for the selected actor. Ask them to add or reconnect that server in Agents → Connections. Do not switch accounts unless they requested it.".into())),diff --git a/crates/agent_egress/src/domain/service/test.rs b/crates/agent_egress/src/domain/service/test.rsindex 72b934f2b8..e5c88d9519 100644--- a/crates/agent_egress/src/domain/service/test.rs+++ b/crates/agent_egress/src/domain/service/test.rs@@ -186,6 +186,7 @@ impl McpCredentials for SpyCredentials {&self,owner: &MacroUserIdStr<'static>,agent: BotId,+ _session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {self.agents.lock().expect("lock").push(agent);diff --git a/crates/agent_egress/src/outbound/custom_mcp.rs b/crates/agent_egress/src/outbound/custom_mcp.rsindex 9eef249abc..716cc7b217 100644--- a/crates/agent_egress/src/outbound/custom_mcp.rs+++ b/crates/agent_egress/src/outbound/custom_mcp.rs@@ -88,10 +88,11 @@ where&self,owner: &MacroUserIdStr<'static>,agent: bot_id::BotId,+ session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {let McpDestination::Custom(key) = destination else {- return self.inner.resolve(owner, agent, destination).await;+ return self.inner.resolve(owner, agent, session, destination).await;};// Unlike a Pipedream slug there is nothing to address without a row:diff --git a/crates/agent_egress/src/outbound/custom_mcp/test.rs b/crates/agent_egress/src/outbound/custom_mcp/test.rsindex 2807c3f1ee..206aa81906 100644--- a/crates/agent_egress/src/outbound/custom_mcp/test.rs+++ b/crates/agent_egress/src/outbound/custom_mcp/test.rs@@ -29,6 +29,7 @@ impl McpCredentials for &SpyInner {&self,_owner: &MacroUserIdStr<'static>,_agent: BotId,+ _session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {let McpDestination::Connected(slug) = destination else {@@ -138,7 +139,7 @@ async fn a_connected_server_resolves_to_its_url_with_the_owners_bearer() {let credentials = WithCustomMcp::new(&inner, Arc::clone(&servers));let McpResolution::Connected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &custom(WIKI))+ .resolve(&owner(), BotId::TEST_A, uuid::Uuid::nil(), &custom(WIKI)).await.expect("resolved")else {@@ -167,7 +168,7 @@ async fn a_server_with_no_account_resolves_anonymously() {let credentials = WithCustomMcp::new(&inner, servers);let McpResolution::Connected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &custom(WIKI))+ .resolve(&owner(), BotId::TEST_A, uuid::Uuid::nil(), &custom(WIKI)).await.expect("resolved")else {@@ -186,7 +187,7 @@ async fn a_dead_grant_is_reported_disconnected_by_name() {let credentials = WithCustomMcp::new(&inner, servers);let McpResolution::Disconnected { call, name } = credentials- .resolve(&owner(), BotId::TEST_A, &custom(WIKI))+ .resolve(&owner(), BotId::TEST_A, uuid::Uuid::nil(), &custom(WIKI)).await.expect("resolved")else {@@ -209,7 +210,7 @@ async fn an_unknown_or_disabled_key_is_refused() {let credentials = WithCustomMcp::new(&inner, servers);let refusal = credentials- .resolve(&owner(), BotId::TEST_A, &custom(WIKI))+ .resolve(&owner(), BotId::TEST_A, uuid::Uuid::nil(), &custom(WIKI)).await.expect_err("disabled");assert!(@@ -220,6 +221,7 @@ async fn an_unknown_or_disabled_key_is_refused() {.resolve(&owner(),BotId::TEST_A,+ uuid::Uuid::nil(),&custom("https://nobody.example.com/mcp"),).await@@ -237,7 +239,7 @@ async fn a_cleartext_server_is_refused() {let credentials = WithCustomMcp::new(&inner, servers);let refusal = credentials- .resolve(&owner(), BotId::TEST_A, &custom(PLAIN))+ .resolve(&owner(), BotId::TEST_A, uuid::Uuid::nil(), &custom(PLAIN)).await.expect_err("cleartext");assert!(matches!(refusal, EgressError::InsecureUpstream(_)));@@ -250,7 +252,12 @@ async fn every_other_destination_delegates_to_the_inner_resolver() {let credentials = WithCustomMcp::new(&inner, Arc::clone(&servers));let refusal = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect_err("the spy refuses everything");diff --git a/crates/agent_egress/src/outbound/macro_mcp.rs b/crates/agent_egress/src/outbound/macro_mcp.rsindex e5a8353752..ab576e9062 100644--- a/crates/agent_egress/src/outbound/macro_mcp.rs+++ b/crates/agent_egress/src/outbound/macro_mcp.rs@@ -45,6 +45,7 @@ pub trait MacroApiTokens: Send + Sync {&self,owner: &MacroUserIdStr<'static>,agent: BotId,+ session: uuid::Uuid,) -> impl Future<Output = Result<String, EgressError>> + Send;}@@ -60,11 +61,11 @@ pub struct WithMacroMcp<Inner, Tokens> {/// Whether [`UpstreamCall::bearer_over_local_cleartext`] is permitted./// Set only by a composition root that has checked `ENVIRONMENT=local`.local_cleartext: bool,- /// Keyed by owner and agent: the token *is* both identities, so a cache- /// hit for one owner or agent can never answer for another. Bounded, so+ /// Keyed by owner, agent, and session: a cached credential cannot attribute+ /// another session's code-mode invocation to this one. Bounded, so/// the map cannot grow with every owner ever seen; freshness still comes/// from each token's own expiry, never from cache residency.- cached: Mutex<LruCache<(MacroUserIdStr<'static>, BotId), CachedToken>>,+ cached: Mutex<LruCache<(MacroUserIdStr<'static>, BotId, uuid::Uuid), CachedToken>>,}/// How many owners' tokens are kept at once. Far past any real concurrency;@@ -117,8 +118,9 @@ where&self,owner: &MacroUserIdStr<'static>,agent: BotId,+ session: uuid::Uuid,) -> Result<String, EgressError> {- let key = (owner.clone(), agent);+ let key = (owner.clone(), agent, session);{let mut cached = self.cached.lock().expect("token cache poisoned");match usable(cached.get(&key).cloned()) {@@ -135,7 +137,7 @@ where}}- let token = self.tokens.mint(owner, agent).await?;+ let token = self.tokens.mint(owner, agent, session).await?;let expires_at = token_expiry(&token)?;self.cached.lock().expect("token cache poisoned").put(key,@@ -159,13 +161,14 @@ where&self,owner: &MacroUserIdStr<'static>,agent: BotId,+ session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {if *destination != McpDestination::Macro {- return self.inner.resolve(owner, agent, destination).await;+ return self.inner.resolve(owner, agent, session, destination).await;}- let token = BearerToken::new(self.token(owner, agent).await?);+ let token = BearerToken::new(self.token(owner, agent, session).await?);// Every session has Macro's own server; there is no grant to lack.let call = if self.local_cleartext && self.url.scheme() != "https" {UpstreamCall::bearer_over_local_cleartext(self.url.clone(), token)@@ -264,7 +267,7 @@ impl MacroApiTokenSigner {owner: &MacroUserIdStr<'static>,lifetime_seconds: usize,) -> Result<String, EgressError> {- self.mint_for_agent(owner, lifetime_seconds, None, None)+ self.mint_for_agent(owner, lifetime_seconds, None, None, None, None).await}@@ -277,6 +280,8 @@ impl MacroApiTokenSigner {lifetime_seconds: usize,agent_id: Option<macro_uuid::Uuid>,agent_via: Option<String>,+ agent_session_id: Option<uuid::Uuid>,+ agent_correlation_id: Option<uuid::Uuid>,) -> Result<String, EgressError> {if !(1..=MINTED_TOKEN_LIFETIME_SECONDS).contains(&lifetime_seconds) {return Err(EgressError::Internal(rootcause::report!(@@ -311,6 +316,8 @@ impl MacroApiTokenSigner {})?;encode_macro_api_token(EncodeMacroApiTokenArgs {+ agent_correlation_id,+ agent_session_id,fusionauth_id: fusion_root_id.to_string(),macro_user_id,organization_id,@@ -333,12 +340,15 @@ impl MacroApiTokens for MacroApiTokenSigner {&self,owner: &MacroUserIdStr<'static>,agent: BotId,+ session: uuid::Uuid,) -> Result<String, EgressError> {self.mint_for_agent(owner,MINTED_TOKEN_LIFETIME_SECONDS,Some(agent.as_uuid()),None,+ Some(session),+ None,).await}diff --git a/crates/agent_egress/src/outbound/macro_mcp/test.rs b/crates/agent_egress/src/outbound/macro_mcp/test.rsindex 8af6efdc00..c94aba0fdf 100644--- a/crates/agent_egress/src/outbound/macro_mcp/test.rs+++ b/crates/agent_egress/src/outbound/macro_mcp/test.rs@@ -51,6 +51,7 @@ impl MacroApiTokens for &CountingTokens {&self,_owner: &MacroUserIdStr<'static>,agent: BotId,+ _session: uuid::Uuid,) -> Result<String, EgressError> {self.agents.lock().expect("lock").push(agent);let count = self.minted.fetch_add(1, Ordering::SeqCst) + 1;@@ -72,6 +73,7 @@ impl McpCredentials for &SpyInner {&self,_owner: &MacroUserIdStr<'static>,_agent: BotId,+ _session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {let McpDestination::Connected(slug) = destination else {@@ -93,7 +95,12 @@ async fn answers_macros_own_destination_with_a_minted_token() {let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");let McpResolution::Connected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &McpDestination::Macro,+ ).await.expect("resolved")else {@@ -117,7 +124,12 @@ async fn reuses_a_token_until_it_nears_expiry() {for _ in 0..3 {credentials- .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &McpDestination::Macro,+ ).await.expect("resolved");}@@ -136,7 +148,7 @@ async fn each_agent_of_one_owner_gets_its_own_token() {for agent in [BotId::TEST_A, BotId::TEST_B, BotId::TEST_A] {credentials- .resolve(&owner(), agent, &McpDestination::Macro)+ .resolve(&owner(), agent, uuid::Uuid::nil(), &McpDestination::Macro).await.expect("resolved");}@@ -156,7 +168,12 @@ async fn a_token_about_to_expire_is_replaced() {for _ in 0..2 {credentials- .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &McpDestination::Macro,+ ).await.expect("resolved");}@@ -171,7 +188,12 @@ async fn every_other_slug_delegates_to_the_inner_resolver() {let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).expect("constructed");let refusal = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect_err("the spy refuses everything");@@ -195,7 +217,12 @@ async fn refuses_a_cleartext_url_unless_local_dev_permits_it() {let inner = SpyInner::default();let permitted = WithMacroMcp::new(&inner, &tokens, url, true).expect("constructed");let McpResolution::Connected(call) = permitted- .resolve(&owner(), BotId::TEST_A, &McpDestination::Macro)+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &McpDestination::Macro,+ ).await.expect("resolved")else {@@ -218,3 +245,19 @@ fn an_unreadable_token_is_an_upstream_error() {assert!(matches!(refusal, EgressError::Upstream(_)), "{garbage}");}}++#[tokio::test]+async fn sessions_of_the_same_agent_never_share_mcp_credentials() {+ let tokens = CountingTokens::fresh();+ let inner = SpyInner::default();+ let credentials = WithMacroMcp::new(&inner, &tokens, macro_url(), false).unwrap();+ let first = uuid::Uuid::now_v7();+ let second = uuid::Uuid::now_v7();+ for session in [first, second, first] {+ credentials+ .resolve(&owner(), BotId::TEST_A, session, &McpDestination::Macro)+ .await+ .unwrap();+ }+ assert_eq!(tokens.minted.load(Ordering::SeqCst), 2);+}diff --git a/crates/agent_egress/src/outbound/mcp_credentials.rs b/crates/agent_egress/src/outbound/mcp_credentials.rsindex 4443800e0d..bf28c6b4c9 100644--- a/crates/agent_egress/src/outbound/mcp_credentials.rs+++ b/crates/agent_egress/src/outbound/mcp_credentials.rs@@ -89,6 +89,7 @@ where&self,owner: &MacroUserIdStr<'static>,_agent: bot_id::BotId,+ _session: uuid::Uuid,destination: &McpDestination,) -> Result<McpResolution, EgressError> {// Macro's own server is the composition root's to layer on withdiff --git a/crates/agent_egress/src/outbound/mcp_credentials/test.rs b/crates/agent_egress/src/outbound/mcp_credentials/test.rsindex 65e7a502e1..4255ad17c9 100644--- a/crates/agent_egress/src/outbound/mcp_credentials/test.rs+++ b/crates/agent_egress/src/outbound/mcp_credentials/test.rs@@ -110,7 +110,12 @@ async fn resolves_an_app_slug_verbatim() {);let McpResolution::Connected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &connected("google_sheets"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("google_sheets"),+ ).await.expect("resolved")else {@@ -132,7 +137,12 @@ async fn carries_the_scoping_headers_next_to_the_bearer() {);let McpResolution::Connected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect("resolved")else {@@ -166,7 +176,12 @@ async fn a_disabled_connection_resolves_as_unconnected() {);let resolution = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect("resolved");@@ -192,7 +207,12 @@ async fn a_slug_nobody_connected_resolves_as_unconnected_for_the_owner() {PipedreamMcpCredentials::new(Arc::new(FixedConnections(Vec::new())), upstream.clone());let McpResolution::Unconnected(call) = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect("resolved")else {@@ -221,7 +241,12 @@ async fn refuses_a_cleartext_upstream() {);let refusal = credentials- .resolve(&owner(), BotId::TEST_A, &connected("linear"))+ .resolve(+ &owner(),+ BotId::TEST_A,+ uuid::Uuid::nil(),+ &connected("linear"),+ ).await.expect_err("refused");diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.mdindex 9bca45cd1c..5e1f1c4f84 100644--- a/crates/agent_session/AGENTS.md+++ b/crates/agent_session/AGENTS.md@@ -153,3 +153,5 @@ through `set_name` clears it, so a name a person chose is never replaced.## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`++- The activity route requires session view access, including for rows affecting other entities; its optional invocation filter stays scoped to the session.diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 4e62e1bf4e..4e501d3c48 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -43,11 +43,12 @@ outbound = []# OpenAPI schemas for the vocabulary that reaches an HTTP boundary: the# router's DTOs, and the lifecycle events the webhook union carries.-schema = ["dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema"]+schema = ["activity/schema", "dep:utoipa", "agent_runtime_protocol/utoipa", "macro_user_id/schema"]# Mock and in-memory port implementations, for crates that test against this one.test-utils = ["dep:mockall", "agent_fold/test-utils"][dependencies]+activity = { path = "../activity", default-features = false }ai_billing = { path = "../ai_billing", optional = true }lazy-regex = { workspace = true }ai_toolset = { path = "../ai_toolset", optional = true }diff --git a/crates/agent_session/src/domain/activity.rs b/crates/agent_session/src/domain/activity.rsnew file mode 100644index 0000000000..43f18ee5b1--- /dev/null+++ b/crates/agent_session/src/domain/activity.rs@@ -0,0 +1,61 @@+//! Session-view-authorized activity, without narrowing to affected-entity access.+use super::error::AgentSessionError;+use activity::domain::ports::AgentActivityReads;+use chrono::{DateTime, Utc};+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use serde::{Deserialize, Serialize};+use std::num::NonZeroU32;+use uuid::Uuid;++/// Stable chronological resume position.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct AgentActivityCursor {+ /// Last stored event time.+ pub occurred_at: DateTime<Utc>,+ /// Tie-breaking activity identity.+ pub id: Uuid,+}++/// One page of the activity caused by this session.+#[derive(Debug, Serialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct AgentActivityPage {+ /// Original activity rows, also retained in the affected entities' histories.+ pub activities: Vec<activity::ActivityWireRow>,+ /// Resume position, present when more raw rows remain.+ pub next_cursor: Option<AgentActivityCursor>,+}++/// Read using the session capability, never permission on the affected entities.+pub async fn read<R: AgentActivityReads>(+ repository: &R,+ access: &EntityAccessReceipt<ViewAccessLevel>,+ correlation_id: Option<Uuid>,+ cursor: Option<AgentActivityCursor>,+ limit: NonZeroU32,+) -> Result<AgentActivityPage, AgentSessionError> {+ let session_id = Uuid::parse_str(&access.entity().entity_id)+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;+ let page = repository+ .agent_activity(+ session_id,+ correlation_id,+ cursor.map(|c| (c.occurred_at, c.id)),+ limit,+ )+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;+ Ok(AgentActivityPage {+ activities: page+ .records+ .into_iter()+ .map(activity::ActivityWireRow::from)+ .collect(),+ next_cursor: page+ .next+ .map(|(occurred_at, id)| AgentActivityCursor { occurred_at, id }),+ })+}diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rsindex f7277c4f39..8d31a52b7c 100644--- a/crates/agent_session/src/domain/error.rs+++ b/crates/agent_session/src/domain/error.rs@@ -10,6 +10,9 @@ pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;#[derive(Error, Debug)]pub enum AgentSessionError {+ /// Invalid session activity paging input.+ #[error("{0}")]+ InvalidActivityQuery(&'static str),/// Speculative sessions cannot belong to a conversation or a message.#[error("a warm session cannot have conversation or message provenance")]InvalidSessionPurpose,diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rsindex dc74d9bd1b..1227112c75 100644--- a/crates/agent_session/src/domain/mod.rs+++ b/crates/agent_session/src/domain/mod.rs@@ -1,4 +1,5 @@pub mod action_history;+pub mod activity;pub mod agent_conversation;/// Current authorization for agent session streams.pub mod audience;diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex ead257156b..7a8d8949bb 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -80,6 +80,9 @@ pub mod work_registration;mod owned_purge;+/// Session-correlated activity read surface.+pub mod activity;+/// Shared state for the agent session router: the agent session service plus/// the authorization state the request extractors authenticate against.pub struct AgentSessionRouterState<T, Access, Auth> {@@ -376,9 +379,10 @@ impl IntoResponse for AgentSessionApiError {Self::Domain(AgentSessionError::Forbidden) => {(StatusCode::FORBIDDEN, "forbidden").into_response()}- Self::Domain(AgentSessionError::InvalidSharing(message)) => {- (StatusCode::BAD_REQUEST, message).into_response()- }+ Self::Domain(+ AgentSessionError::InvalidSharing(message)+ | AgentSessionError::InvalidActivityQuery(message),+ ) => (StatusCode::BAD_REQUEST, message).into_response(),Self::Domain(AgentSessionError::SharingChanged) => (StatusCode::CONFLICT,"sharing changed; reload and try again",diff --git a/crates/agent_session/src/inbound/axum_router/activity.rs b/crates/agent_session/src/inbound/axum_router/activity.rsnew file mode 100644index 0000000000..b143373cd5--- /dev/null+++ b/crates/agent_session/src/inbound/axum_router/activity.rs@@ -0,0 +1,145 @@+//! Paginated agent activity, authorized through session visibility alone.+use super::AgentSessionApiError;+use crate::domain::activity::{AgentActivityCursor, AgentActivityPage};+use activity::domain::ports::AgentActivityReads;+use axum::{+ Json, Router,+ extract::{FromRef, Query, State},+ routing::get,+};+use chrono::{DateTime, Utc};+use entity_access::{+ domain::{models::ViewAccessLevel, ports::EntityAccessService},+ inbound::axum_extractors::AgentSessionAccessLevelExtractor,+};+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};+use serde::Deserialize;+use std::{num::NonZeroU32, sync::Arc};+use utoipa::IntoParams;+use uuid::Uuid;++/// Repository and the existing session access boundary.+pub struct AgentActivityState<R, Access, Auth> {+ repository: Arc<R>,+ access: Arc<Access>,+ authorization: MacroAuthorizationState<Auth>,+}++impl<R, Access, Auth> AgentActivityState<R, Access, Auth> {+ /// Compose the session activity reader.+ pub fn new(+ repository: R,+ access: Arc<Access>,+ authorization: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ repository: Arc::new(repository),+ access,+ authorization,+ }+ }+}++impl<R, Access, Auth> Clone for AgentActivityState<R, Access, Auth> {+ fn clone(&self) -> Self {+ Self {+ repository: self.repository.clone(),+ access: self.access.clone(),+ authorization: self.authorization.clone(),+ }+ }+}++impl<R, Access, Auth> FromRef<AgentActivityState<R, Access, Auth>> for Arc<Access> {+ fn from_ref(state: &AgentActivityState<R, Access, Auth>) -> Self {+ state.access.clone()+ }+}++impl<R, Access, Auth> FromRef<AgentActivityState<R, Access, Auth>>+ for MacroAuthorizationState<Auth>+{+ fn from_ref(state: &AgentActivityState<R, Access, Auth>) -> Self {+ state.authorization.clone()+ }+}++/// Filters and chronological cursor. Both cursor components must be supplied together.+#[derive(Deserialize, IntoParams)]+#[serde(rename_all = "camelCase")]+#[into_params(rename_all = "camelCase")]+pub struct AgentActivityQuery {+ /// Restrict activity to one code-mode invocation within this session.+ pub agent_correlation_id: Option<Uuid>,+ /// Cursor timestamp from the previous page.+ pub before_at: Option<DateTime<Utc>>,+ /// Cursor activity ID from the previous page.+ pub before_id: Option<Uuid>,+ /// Page size, from 1 to 100; defaults to 50.+ #[param(value_type = Option<u32>, minimum = 1, maximum = 100)]+ pub limit: Option<NonZeroU32>,+}++/// Mount alongside the session API at the application root.+pub fn router<+ R: AgentActivityReads,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ state: AgentActivityState<R, Access, Auth>,+) -> Router {+ Router::new()+ .route(+ "/agent-sessions/{session_id}/activity",+ get(get_agent_session_activity::<R, Access, Auth>),+ )+ .with_state(state)+}++/// Read activity using the same visibility capability as the session transcript.+#[utoipa::path(get, path = "/agent-sessions/{session_id}/activity", tag = "agent-sessions", operation_id = "get_agent_session_activity",+ params(("session_id" = Uuid, Path), AgentActivityQuery),+ responses((status = 200, body = AgentActivityPage), (status = 400), (status = 401), (status = 403)))]+pub async fn get_agent_session_activity<+ R: AgentActivityReads,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,+ State(state): State<AgentActivityState<R, Access, Auth>>,+ Query(query): Query<AgentActivityQuery>,+) -> Result<Json<AgentActivityPage>, AgentSessionApiError> {+ let cursor = match (query.before_at, query.before_id) {+ (Some(occurred_at), Some(id)) => Some(AgentActivityCursor { occurred_at, id }),+ (None, None) => None,+ _ => {+ return Err(+ crate::domain::error::AgentSessionError::InvalidActivityQuery(+ "both activity cursor components are required",+ )+ .into(),+ );+ }+ };+ let limit = query+ .limit+ .unwrap_or(NonZeroU32::new(50).expect("nonzero default"));+ if limit.get() > 100 {+ return Err(+ crate::domain::error::AgentSessionError::InvalidActivityQuery(+ "activity limit must not exceed 100",+ )+ .into(),+ );+ }+ crate::domain::activity::read(+ state.repository.as_ref(),+ &access.entity_access_receipt,+ query.agent_correlation_id,+ cursor,+ limit,+ )+ .await+ .map(Json)+ .map_err(Into::into)+}diff --git a/crates/agent_session/src/inbound/axum_router/test/tool_actions.rs b/crates/agent_session/src/inbound/axum_router/test/tool_actions.rsindex 335069c60f..02781ffa18 100644--- a/crates/agent_session/src/inbound/axum_router/test/tool_actions.rs+++ b/crates/agent_session/src/inbound/axum_router/test/tool_actions.rs@@ -342,3 +342,72 @@ async fn tools_cannot_approve_requests_or_supply_another_actor() {}assert!(controls.controls.lock().unwrap().is_empty());}++#[derive(Clone)]+struct ActivityReads(Arc<std::sync::atomic::AtomicUsize>);+impl ::activity::domain::ports::AgentActivityReads for ActivityReads {+ type Err = std::io::Error;+ async fn agent_activity(+ &self,+ session: Uuid,+ _: Option<Uuid>,+ _: Option<(chrono::DateTime<Utc>, Uuid)>,+ _: std::num::NonZeroU32,+ ) -> Result<::activity::ActivityFeedPage, Self::Err> {+ assert_eq!(session, AgentSessionId::TEST_A.as_uuid());+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(::activity::ActivityFeedPage {+ records: Vec::new(),+ next: None,+ })+ }+}++#[tokio::test]+async fn session_activity_requires_view_access_and_valid_pagination_before_reading() {+ use std::sync::atomic::{AtomicUsize, Ordering};+ let reads = Arc::new(AtomicUsize::new(0));+ for (level, query, expected) in [+ (None, "", StatusCode::UNAUTHORIZED),+ (Some(AccessLevel::View), "", StatusCode::OK),+ (+ Some(AccessLevel::View),+ "?limit=101",+ StatusCode::BAD_REQUEST,+ ),+ (+ Some(AccessLevel::View),+ "?beforeId=00000000-0000-0000-0000-000000000001",+ StatusCode::BAD_REQUEST,+ ),+ ] {+ let auth = MacroAuthorizationServiceImpl::new(+ FakeJwtValidator,+ InternalAuthConfig {+ api_key: "test-key".into(),+ default_user_id: None,+ },+ SelfBotAuthorizer,+ NoUserApiKeyAuthorizer,+ );+ let router =+ super::super::activity::router(super::super::activity::AgentActivityState::new(+ ActivityReads(reads.clone()),+ Arc::new(FakeEntityAccessService {+ access_level: level,+ }),+ MacroAuthorizationState::new(Arc::new(auth)),+ ));+ let request = Request::builder()+ .uri(format!(+ "/agent-sessions/{}/activity{query}",+ AgentSessionId::TEST_A+ ))+ .header(INTERNAL_API_KEY_HEADER, "test-key")+ .header(INTERNAL_MACRO_USER_ID_HEADER, OWNER)+ .body(Body::empty())+ .unwrap();+ assert_eq!(router.oneshot(request).await.unwrap().status(), expected);+ }+ assert_eq!(reads.load(Ordering::SeqCst), 1);+}diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.mdindex 368aab6d8d..60a988fb70 100644--- a/crates/channels/AGENTS.md+++ b/crates/channels/AGENTS.md@@ -108,3 +108,5 @@ DMs, and the shared message store other domains discuss things on.## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`++- Capture agent correlation when spawning mutation side effects and restore it when team events create direct-message channels.diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.tomlindex f81ad198be..5755385ddd 100644--- a/crates/channels/Cargo.toml+++ b/crates/channels/Cargo.toml@@ -96,6 +96,7 @@ schema = [][dependencies]+agent_correlation = { path = "../agent_correlation" }activity = { path = "../activity", default-features = false }anyhow = { workspace = true }attachment = { path = "../attachment", optional = true }diff --git a/crates/channels/src/domain/message_delivery.rs b/crates/channels/src/domain/message_delivery.rsindex a517105b44..3e0e795a7d 100644--- a/crates/channels/src/domain/message_delivery.rs+++ b/crates/channels/src/domain/message_delivery.rs@@ -230,7 +230,7 @@ where.collect();if !pending.is_empty() {let pending_count = pending.len();- tokio::spawn(+ tokio::spawn(agent_correlation::context::capture(recheck_agent_creations(self.creations.clone(),self.permissions.clone(),@@ -249,7 +249,7 @@ whereshared = tracing::field::Empty,not_permitted = tracing::field::Empty,)),- );+ ));}if !created.is_empty() {let results = selfdiff --git a/crates/channels/src/domain/side_effects.rs b/crates/channels/src/domain/side_effects.rsindex ca2d4b719c..e2ec60d756 100644--- a/crates/channels/src/domain/side_effects.rs+++ b/crates/channels/src/domain/side_effects.rs@@ -330,12 +330,12 @@ where{fn dispatch(&self, event: ChannelEvent) {let handler = self.handler.clone();- tokio::spawn(+ tokio::spawn(agent_correlation::context::capture(async move {handler.handle(event).await;}.instrument(tracing::info_span!("channel.side_effects")),- );+ ));}}diff --git a/crates/channels/src/inbound/teammate_dms_consumer.rs b/crates/channels/src/inbound/teammate_dms_consumer.rsindex c2a062be07..2978365966 100644--- a/crates/channels/src/inbound/teammate_dms_consumer.rs+++ b/crates/channels/src/inbound/teammate_dms_consumer.rs@@ -256,12 +256,12 @@ wherelet kafka_message = message.inner();match message.decode_payload() {Ok(DeclaredMacroEvent::TeamsMacroEventForDms(event)) => {- handle_with_retry(+ agent_correlation::context::scope(event.event().agent_correlation_id, handle_with_retry(&channels,&event.event().event,kafka_message.partition(),kafka_message.offset(),- )+ )).await?;}Err(e) => tracing::error!(diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 4a0ffcae7c..85e5ee670b 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -2008,6 +2008,7 @@ async fn activity_updates_subscribes_as_the_authenticated_user() {chrono::Utc::now(),);activity::ActivityRecord {+ agent_correlation_id: activity.agent_correlation_id,id: activity.id,actor: activity.actor.clone(),subject_id: activity.subject_id.clone(),@@ -2609,6 +2610,7 @@ fn activity_record(occurred_at_secs: i64,) -> activity::ActivityRecord {activity::ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(id),actor: activity::Actor::new_from_user(MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),diff --git a/crates/complete_graph/src/schema/test/form_activity.rs b/crates/complete_graph/src/schema/test/form_activity.rsindex 8d8d67cd45..2a0b38a651 100644--- a/crates/complete_graph/src/schema/test/form_activity.rs+++ b/crates/complete_graph/src/schema/test/form_activity.rs@@ -10,6 +10,7 @@ const OTHER_RESPONDENT_ID: &str = "macro|[email protected]";/// Another respondent's response, as ingestion records it.fn someone_elses_response(id: u128, form_id: &str) -> activity::ActivityRecord {activity::ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(id),actor: activity::Actor::new_from_user(MacroUserIdStr::parse_from_str(OTHER_RESPONDENT_ID).unwrap(),diff --git a/crates/complete_graph/src/schema/test/team_activity.rs b/crates/complete_graph/src/schema/test/team_activity.rsindex dacc821855..1c9b955d1a 100644--- a/crates/complete_graph/src/schema/test/team_activity.rs+++ b/crates/complete_graph/src/schema/test/team_activity.rs@@ -5,6 +5,7 @@ const TEAMMATE_ID: &str = "macro|[email protected]";/// A teammate's edit, as ingestion records it.fn teammates_edit(id: u128) -> activity::ActivityRecord {activity::ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(id),actor: activity::Actor::new_from_user(MacroUserIdStr::parse_from_str(TEAMMATE_ID).unwrap()),subject_id: TEAMMATE_ID.to_owned(),diff --git a/crates/documents/AGENTS.md b/crates/documents/AGENTS.mdindex 7b3a81552a..9ae777b434 100644--- a/crates/documents/AGENTS.md+++ b/crates/documents/AGENTS.md@@ -115,3 +115,5 @@ word docs, Illustrator/Photoshop files).- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md` ·Skill: `collab-surface-core`++- Signed document grants carry agent correlation into Sync; editor deduplication and activity debounce include the invocation ID.diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.tomlindex c4d42d1dc6..c7a403507d 100644--- a/crates/documents/Cargo.toml+++ b/crates/documents/Cargo.toml@@ -104,6 +104,7 @@ service = [][dependencies]+agent_correlation = { path = "../agent_correlation" }macro_db_client = { path = "../macro_db_client", optional = true }macro_sha_count_client = { path = "../macro_sha_count_client", optional = true }sqs_client = { path = "../sqs_client", optional = true }diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rsindex 681b0b7824..11b9114452 100644--- a/crates/documents/src/domain/activity.rs+++ b/crates/documents/src/domain/activity.rs@@ -129,6 +129,7 @@ impl ActivitySource for DocumentTopicEvent {DocumentTopicEvent::ContentUploaded(_) => Ingest::Ignore,DocumentTopicEvent::SyncContentUpdated(metadata) => {let legacy = metadata.actor.clone().map(|actor| DocumentSyncEditor {+ agent_correlation_id: None,actor,on_behalf_of: metadata.on_behalf_of.clone(),});@@ -149,6 +150,7 @@ impl ActivitySource for DocumentTopicEvent {CommonAction::Edited,event_time(event_id),)+ .with_agent_correlation(editor.agent_correlation_id)}).collect();if activities.is_empty() {@@ -163,10 +165,11 @@ impl ActivitySource for DocumentTopicEvent {}}-fn editor_key(editor: &DocumentSyncEditor) -> (&str, Option<&str>) {+fn editor_key(editor: &DocumentSyncEditor) -> (&str, Option<&str>, Option<Uuid>) {(editor.actor.as_ref(),editor.on_behalf_of.as_ref().map(|user| user.as_ref()),+ editor.agent_correlation_id,)}diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rsindex c77e31b0b0..b2553e0f73 100644--- a/crates/documents/src/domain/activity/test.rs+++ b/crates/documents/src/domain/activity/test.rs@@ -422,6 +422,7 @@ fn editor_event(editors: &[(&str, Option<&str>)]) -> DocumentTopicEvent {.iter().map(|(actor, subject)| crate::domain::events::DocumentSyncEditor {+ agent_correlation_id: None,actor: Actor::try_from((*actor).to_owned()).unwrap(),on_behalf_of: subject.map(user),},@@ -544,3 +545,26 @@ async fn unavailable_debounce_is_best_effort_and_does_not_stall_other_activity());}}++#[test]+fn batched_edits_from_the_same_actor_keep_each_invocation() {+ let mut event = editor_event(&[+ ("macro|[email protected]", None),+ ("macro|[email protected]", None),+ ]);+ let DocumentTopicEvent::SyncContentUpdated(metadata) = &mut event else {+ unreachable!()+ };+ let first = Uuid::from_u128(1);+ let second = Uuid::from_u128(2);+ metadata.editors[0].agent_correlation_id = Some(first);+ metadata.editors[1].agent_correlation_id = Some(second);+ metadata.editors.push(metadata.editors[0].clone());+ let Ingest::Insert(rows) = event.ingest(Uuid::now_v7()) else {+ panic!("expected activity")+ };+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0].agent_correlation_id, Some(first));+ assert_eq!(rows[1].agent_correlation_id, Some(second));+ assert_ne!(rows[0].id, rows[1].id);+}diff --git a/crates/documents/src/domain/create/upload.rs b/crates/documents/src/domain/create/upload.rsindex 0921fbeb70..cd0d389484 100644--- a/crates/documents/src/domain/create/upload.rs+++ b/crates/documents/src/domain/create/upload.rs@@ -126,7 +126,7 @@ wherelet bytes_uploader = self.bytes_uploader.clone();// Own the entire write so dropping the caller cannot interrupt metadata// creation before we know its ID, the upload, or failure cleanup.- tokio::spawn(+ tokio::spawn(agent_correlation::context::capture(async move {let response = document_service.create_document(&principal, document, None)@@ -176,7 +176,7 @@ whereOk(created)}.in_current_span(),- )+ )).await.map_err(|error| DocumentError::Internal(rootcause::report!(error).into_anyhow()))?}diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rsindex 64d5cba3d3..ee320020e0 100644--- a/crates/documents/src/domain/events.rs+++ b/crates/documents/src/domain/events.rs@@ -132,6 +132,9 @@ pub struct DocumentContentUploadedMetadata {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]pub struct DocumentSyncEditor {+ /// Invocation from the editor's signed document grant.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<uuid::Uuid>,/// User or bot that performed the edit.#[cfg_attr(feature = "schema", schema(value_type = String))]pub actor: Actor<'static>,diff --git a/crates/documents/src/domain/permission_token.rs b/crates/documents/src/domain/permission_token.rsindex 79e91d2ee3..68fa3a90ca 100644--- a/crates/documents/src/domain/permission_token.rs+++ b/crates/documents/src/domain/permission_token.rs@@ -15,6 +15,8 @@ use std::time::{SystemTime, UNIX_EPOCH};/// document-permissions token type so the OpenAPI validate API stays unchanged.#[derive(serde::Serialize, serde::Deserialize)]pub(crate) struct PermissionTokenClaims {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub(crate) agent_correlation_id: Option<uuid::Uuid>,#[serde(default, skip_serializing_if = "Option::is_none")]pub(crate) user_id: Option<MacroUserIdStr<'static>>,document_id: String,@@ -45,6 +47,7 @@ pub fn encode_permission_token(Ok(macro_sync_service_jwt::encode(&PermissionTokenClaims {+ agent_correlation_id: agent_correlation::context::current(),user_id,document_id,access_level,diff --git a/crates/documents/src/domain/permission_token/test.rs b/crates/documents/src/domain/permission_token/test.rsindex 01d83536ac..3e9788a698 100644--- a/crates/documents/src/domain/permission_token/test.rs+++ b/crates/documents/src/domain/permission_token/test.rs@@ -66,3 +66,42 @@ fn team_bot_token_names_the_bot_actor_without_a_user() {),);}++#[tokio::test]+async fn signed_document_grant_retains_invocation_attribution() {+ let id = Uuid::now_v7();+ let principal = CreationPrincipal::BotForUser {+ bot: MACRO_AI_BOT_ID,+ user: user(),+ };+ let token = agent_correlation::context::scope(Some(id), async {+ encode_principal_permission_token(+ &principal,+ "doc-fixture".into(),+ AccessLevel::Edit,+ SECRET,+ )+ .unwrap()+ })+ .await;+ assert_eq!(+ decode_permission_token(&token, SECRET)+ .unwrap()+ .agent_correlation_id,+ Some(id)+ );+ assert!(decode_permission_token(&token, "wrong-fixture-key").is_err());+ let ordinary = encode_principal_permission_token(+ &principal,+ "doc-fixture".into(),+ AccessLevel::Edit,+ SECRET,+ )+ .unwrap();+ assert_eq!(+ decode_permission_token(&ordinary, SECRET)+ .unwrap()+ .agent_correlation_id,+ None+ );+}diff --git a/crates/documents/src/domain/service/tests/sync_content.rs b/crates/documents/src/domain/service/tests/sync_content.rsindex ea9d2dc6df..b5e1d2dc12 100644--- a/crates/documents/src/domain/service/tests/sync_content.rs+++ b/crates/documents/src/domain/service/tests/sync_content.rs@@ -19,6 +19,7 @@ async fn notifications_resolve_the_stored_type_and_preserve_attribution() {.publish_sync_content_updated("doc-1",vec![crate::domain::events::DocumentSyncEditor {+ agent_correlation_id: None,actor: activity::Actor::try_from(actor.to_owned()).unwrap(),on_behalf_of: Some(macro_user_id::user_id::MacroUserIdStr::try_from(user.to_owned()).unwrap(),@@ -82,6 +83,7 @@ async fn a_batch_of_editors_still_publishes_only_one_search_event() {let editors = ["macro|[email protected]", "macro|[email protected]"].into_iter().map(|actor| crate::domain::events::DocumentSyncEditor {+ agent_correlation_id: None,actor: activity::Actor::try_from(actor.to_owned()).unwrap(),on_behalf_of: None,})diff --git a/crates/documents/src/inbound/axum_router/sync_content_updated.rs b/crates/documents/src/inbound/axum_router/sync_content_updated.rsindex bcabb332a8..f6bdaa0f9c 100644--- a/crates/documents/src/inbound/axum_router/sync_content_updated.rs+++ b/crates/documents/src/inbound/axum_router/sync_content_updated.rs@@ -46,6 +46,7 @@ pub async fn sync_content_updated_handler<// legacy ids are dropped, as they always were, so search still extracts.if let Some(actor) = request.actor.and_then(|actor| Actor::try_from(actor).ok()) {editors.push(DocumentSyncEditor {+ agent_correlation_id: None,actor,on_behalf_of: request.on_behalf_ofdiff --git a/crates/documents/src/inbound/axum_router/tests/sync_content.rs b/crates/documents/src/inbound/axum_router/tests/sync_content.rsindex e737c97af9..81f1a46a82 100644--- a/crates/documents/src/inbound/axum_router/tests/sync_content.rs+++ b/crates/documents/src/inbound/axum_router/tests/sync_content.rs@@ -30,6 +30,7 @@ async fn sync_notifications_require_internal_auth_and_forward_only_identity_and_[SyncContentCall {document_id: "doc-1".into(),editors: vec![crate::domain::events::DocumentSyncEditor {+ agent_correlation_id: None,actor: activity::Actor::try_from("bot|00000000-0000-0000-0000-00000000a1a1".to_owned())diff --git a/crates/documents/src/outbound/editing_activity.rs b/crates/documents/src/outbound/editing_activity.rsindex 9eea25f066..4e9c1a75cd 100644--- a/crates/documents/src/outbound/editing_activity.rs+++ b/crates/documents/src/outbound/editing_activity.rs@@ -25,11 +25,15 @@ impl RedisEditingActivityStore {fn session_key(activity: &Activity) -> Result<String, Report> {// Encoding a tuple keeps separators within identifiers unambiguous.- let identity = serde_json::to_string(&(+ let legacy_identity = (activity.actor.as_ref(),&activity.subject_id,&activity.entity_id,- ))?;+ );+ let identity = match activity.agent_correlation_id {+ Some(id) => serde_json::to_string(&(legacy_identity, id))?,+ None => serde_json::to_string(&legacy_identity)?,+ };Ok(format!("documents:editing:{identity}"))}diff --git a/crates/documents/src/outbound/editing_activity/test.rs b/crates/documents/src/outbound/editing_activity/test.rsindex d0b629f378..f283b509c8 100644--- a/crates/documents/src/outbound/editing_activity/test.rs+++ b/crates/documents/src/outbound/editing_activity/test.rs@@ -169,3 +169,27 @@ async fn an_empty_batch_does_not_connect_to_redis() {.is_empty());}++#[tokio::test]+async fn distinct_invocations_are_not_debounced_together() {+ let store = store();+ let document = Uuid::now_v7().to_string();+ let first = edit(&document, "macro|[email protected]", None)+ .with_agent_correlation(Some(Uuid::now_v7()));+ let second = edit(&document, "macro|[email protected]", None)+ .with_agent_correlation(Some(Uuid::now_v7()));+ assert_eq!(+ store+ .refresh_editing_sessions(std::slice::from_ref(&first), Uuid::now_v7(), TEST_IDLE)+ .await+ .unwrap(),+ vec![true]+ );+ assert_eq!(+ store+ .refresh_editing_sessions(&[first, second], Uuid::now_v7(), TEST_IDLE)+ .await+ .unwrap(),+ vec![false, true]+ );+}diff --git a/crates/documents/src/outbound/markdown_init.rs b/crates/documents/src/outbound/markdown_init.rsindex 2592d3d85e..06d2fc105b 100644--- a/crates/documents/src/outbound/markdown_init.rs+++ b/crates/documents/src/outbound/markdown_init.rs@@ -182,13 +182,13 @@ wherelet sync_service_client = Arc::clone(&self.sync_service_client);let document_id = document_id.to_owned();let snapshot = loro_snapshot.to_vec();- tokio::spawn(async move {+ tokio::spawn(agent_correlation::context::capture(async move {if let Err(error) =initialize_with_retry(&*sync_service_client, &document_id, &snapshot).await{tracing::error!(error=?error, %document_id, "failed to initialize sync service from snapshot");}- });+ }));}}diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 76bb24652d..68c7207827 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -198,3 +198,5 @@ tools — hexagonal, heavily feature-gated.## Related- Rules: `.agents/rules/rust/architecture.md`++- Persist agent correlation with scheduled delivery and organization projection payloads, then restore it when publishing delayed activity.diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.tomlindex 185c6ef7c6..871371de65 100644--- a/crates/email/Cargo.toml+++ b/crates/email/Cargo.toml@@ -51,6 +51,7 @@ ports = ["crm/ports", "dep:chrono-tz", "dep:tokio", "frecency/ports"]s3 = ["dep:aws-sdk-s3", "ports"][dependencies]+agent_correlation = { path = "../agent_correlation" }subtle = { workspace = true, optional = true }calendar_events = { path = "../calendar_events", optional = true }ical = { version = "0.11", default-features = false, features = ["ical"], optional = true }diff --git a/crates/email/src/domain/mailbox/projection.rs b/crates/email/src/domain/mailbox/projection.rsindex 88010affe6..5c172a07da 100644--- a/crates/email/src/domain/mailbox/projection.rs+++ b/crates/email/src/domain/mailbox/projection.rs@@ -30,6 +30,8 @@ pub enum ProjectionEvent {self_photo: bool,},Message {+ #[serde(default)]+ agent_correlation_id: Option<Uuid>,#[serde(default)]actor: Option<MacroUserIdStr<'static>>,message_id: Uuid,@@ -51,6 +53,8 @@ pub enum ProjectionEvent {thread_id: Uuid,},Organization {+ #[serde(default)]+ agent_correlation_id: Option<Uuid>,thread_id: Uuid,#[serde(default)]actor: Option<MacroUserIdStr<'static>>,@@ -63,6 +67,22 @@ pub enum ProjectionEvent {},}+impl ProjectionEvent {+ fn agent_correlation_id(&self) -> Option<Uuid> {+ match self {+ Self::Message {+ agent_correlation_id,+ ..+ }+ | Self::Organization {+ agent_correlation_id,+ ..+ } => *agent_correlation_id,+ _ => None,+ }+ }+}+pub struct ProjectionLease {pub id: Uuid,pub lease_id: Uuid,@@ -230,7 +250,9 @@ impl<R: MailboxProjectionRepository, E: MailboxProjectionEffects> MailboxProjectoutlook.defer_seconds = tracing::field::Empty,otel.status_description = tracing::field::Empty,);- self.project_leased(&lease).instrument(span).await+ let correlation = lease.event.agent_correlation_id();+ agent_correlation::context::scope(correlation, self.project_leased(&lease).instrument(span))+ .await}async fn project_leased(&self, lease: &ProjectionLease) -> Result<bool, MailboxError> {@@ -363,6 +385,7 @@ impl<R: MailboxProjectionRepository, E: MailboxProjectionEffects> MailboxProjectthread_id,actor,action,+ ..} => {if let (Some(actor), Some(action)) = (actor, action) {self.effectsdiff --git a/crates/email/src/domain/mailbox/projection/test.rs b/crates/email/src/domain/mailbox/projection/test.rsindex d17dabf9f0..fe168a4aba 100644--- a/crates/email/src/domain/mailbox/projection/test.rs+++ b/crates/email/src/domain/mailbox/projection/test.rs@@ -126,3 +126,35 @@ fn user_category_keeps_its_event_type_and_publication_identity() {EmailTopicEvent::ThreadLabelsUpdated(_)));}++#[tokio::test]+async fn persisted_projection_restores_invocation_when_publishing_later() {+ use macro_event_broker::MacroEvent;+ let context = context();+ let id = Uuid::now_v7();+ let event: ProjectionEvent = serde_json::from_value(serde_json::json!({+ "kind": "organization", "thread_id": Uuid::now_v7(),+ "agent_correlation_id": id,+ }))+ .unwrap();+ let persisted = serde_json::to_vec(&event).unwrap();+ let restored: ProjectionEvent = serde_json::from_slice(&persisted).unwrap();+ let published = agent_correlation::context::scope(restored.agent_correlation_id(), async {+ organization_event(+ &context.link,+ Uuid::now_v7(),+ context.link.macro_id.clone(),+ &crate::domain::models::mailbox_action::MailboxAction::Category {+ name: "TRASH".into(),+ present: true,+ },+ )+ })+ .await;+ assert_eq!(published.event().agent_correlation_id, Some(id));+ let legacy: ProjectionEvent = serde_json::from_value(+ serde_json::json!({"kind": "organization", "thread_id": Uuid::now_v7()}),+ )+ .unwrap();+ assert_eq!(legacy.agent_correlation_id(), None);+}diff --git a/crates/email/src/outbound/email_pg_repo/mailbox_action.rs b/crates/email/src/outbound/email_pg_repo/mailbox_action.rsindex d91d14ecf0..26038bce32 100644--- a/crates/email/src/outbound/email_pg_repo/mailbox_action.rs+++ b/crates/email/src/outbound/email_pg_repo/mailbox_action.rs@@ -106,7 +106,7 @@ pub(super) async fn enqueue(for thread_id in threads {email_db_client::threads::update::recompute_thread_metadata(&mut tx, thread_id, link_id).await?;- let payload = serde_json::json!({"kind":"organization","thread_id":thread_id,"actor":actor.as_ref(),"action":action});+ let payload = serde_json::json!({"kind":"organization","thread_id":thread_id,"actor":actor.as_ref(),"action":action,"agent_correlation_id":agent_correlation::context::current()});sqlx::query!(r#"INSERT INTO email_projection_outbox (id,link_id,generation,payload) VALUES ($1,$2,$3,$4)diff --git a/crates/email/src/outbound/email_pg_repo/message.rs b/crates/email/src/outbound/email_pg_repo/message.rsindex 2081e2beb7..7d2a9c11bf 100644--- a/crates/email/src/outbound/email_pg_repo/message.rs+++ b/crates/email/src/outbound/email_pg_repo/message.rs@@ -561,13 +561,14 @@ pub(super) async fn process_scheduled_message(sqlx::query!(r#"INSERT INTO email_scheduled_messages (- link_id, message_id, send_time, sent, actor_id,+ link_id, message_id, send_time, sent, actor_id, agent_correlation_id,created_at, updated_at)- VALUES ($1, $2, $3, $4, $5, NOW(), NOW())+ VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())ON CONFLICT (link_id, message_id) DO UPDATE SETsend_time = EXCLUDED.send_time,actor_id = EXCLUDED.actor_id,+ agent_correlation_id = EXCLUDED.agent_correlation_id,updated_at = NOW()WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing"#,@@ -576,6 +577,7 @@ pub(super) async fn process_scheduled_message(send_time,false,actor_id,+ agent_correlation::context::current(),).execute(&mut *tx).await?;diff --git a/crates/email/src/outbound/email_pg_repo/scheduled.rs b/crates/email/src/outbound/email_pg_repo/scheduled.rsindex bc48db243e..51c328fd2e 100644--- a/crates/email/src/outbound/email_pg_repo/scheduled.rs+++ b/crates/email/src/outbound/email_pg_repo/scheduled.rs@@ -97,12 +97,12 @@ async fn change_schedule(}let updated = sqlx::query!(r#"INSERT INTO email_scheduled_messages- (link_id, message_id, send_time, sent, processing, actor_id, created_at, updated_at)- VALUES ($1, $2, $3, false, false, $4, NOW(), NOW())+ (link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id, created_at, updated_at)+ VALUES ($1, $2, $3, false, false, $4, $5, NOW(), NOW())ON CONFLICT (link_id, message_id) DO UPDATE SET- send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, updated_at = NOW()+ send_time = EXCLUDED.send_time, actor_id = EXCLUDED.actor_id, agent_correlation_id = EXCLUDED.agent_correlation_id, updated_at = NOW()WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing"#,- link_id, message_id, send_time, actor.as_ref(),+ link_id, message_id, send_time, actor.as_ref(), agent_correlation::context::current(),).execute(&mut *tx).await.map_err(anyhow::Error::from)?;if updated.rows_affected() != 1 {return Err(EmailErr::MessageDeliveryConflict(message_id));diff --git a/crates/email/src/outbound/email_pg_repo/test/scheduled.rs b/crates/email/src/outbound/email_pg_repo/test/scheduled.rsindex 783407b842..ec1b72ec1a 100644--- a/crates/email/src/outbound/email_pg_repo/test/scheduled.rs+++ b/crates/email/src/outbound/email_pg_repo/test/scheduled.rs@@ -794,3 +794,38 @@ async fn late_provider_upload_cannot_change_a_committed_schedule();Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn scheduled_delivery_keeps_the_latest_invocation_after_request_completion(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());+ let (link, message) = identity();+ let first = Uuid::now_v7();+ let second = Uuid::now_v7();+ for id in [first, second] {+ agent_correlation::context::scope(+ Some(id),+ repo.change_schedule(link, message, &actor(), future(), None, 0),+ )+ .await?;+ }+ assert_eq!(agent_correlation::context::current(), None);+ let scheduled =+ email_db_client::messages::scheduled::get::get_scheduled_message(&pool, link, message)+ .await?+ .unwrap();+ assert_eq!(scheduled.agent_correlation_id, Some(second));+ // A later ordinary SDK schedule must not retain an earlier agent attribution.+ repo.change_schedule(link, message, &actor(), future(), None, 0)+ .await?;+ let scheduled =+ email_db_client::messages::scheduled::get::get_scheduled_message(&pool, link, message)+ .await?+ .unwrap();+ assert_eq!(scheduled.agent_correlation_id, None);+ Ok(())+}diff --git a/crates/email/src/outbound/mailbox_pg/drafts.rs b/crates/email/src/outbound/mailbox_pg/drafts.rsindex ff17cc5a70..16ca194851 100644--- a/crates/email/src/outbound/mailbox_pg/drafts.rs+++ b/crates/email/src/outbound/mailbox_pg/drafts.rs@@ -337,7 +337,8 @@ impl DraftRepository for PgMailboxSync {"#,lease.message_id).fetch_one(&mut *tx).await.map_err(db_error)?;sqlx::query!("UPDATE email_scheduled_messages SET sent = true,processing = false,updated_at = now() WHERE message_id = $1 AND link_id = $2",lease.message_id,lease.mailbox.link_id).execute(&mut *tx).await.map_err(db_error)?;sqlx::query!("UPDATE email_mailbox_drafts SET state = 'sent',base_version = $2,error_code = NULL,lease_id = NULL,lease_until = NULL,updated_at = now() WHERE message_id = $1",lease.message_id,draft.version).execute(&mut *tx).await.map_err(db_error)?;- let payload = serde_json::json!({"kind":"message","message_id":lease.message_id,"thread_id":message.thread_id,"provider_id":draft.id.as_str(),"is_import":false,"is_new":false,"is_new_thread":false,"was_draft":true,"is_draft":false,"is_sent":true,"version":draft.version,"calendar_parts":[],"actor":checkpoint.submission_started.then_some(&checkpoint.actor_id)});+ let correlation = sqlx::query_scalar!("SELECT agent_correlation_id FROM email_scheduled_messages WHERE message_id = $1 AND link_id = $2", lease.message_id, lease.mailbox.link_id).fetch_optional(&mut *tx).await.map_err(db_error)?.flatten();+ let payload = serde_json::json!({"kind":"message","message_id":lease.message_id,"thread_id":message.thread_id,"provider_id":draft.id.as_str(),"is_import":false,"is_new":false,"is_new_thread":false,"was_draft":true,"is_draft":false,"is_sent":true,"version":draft.version,"calendar_parts":[],"actor":checkpoint.submission_started.then_some(&checkpoint.actor_id),"agent_correlation_id":correlation});let dedupe = format!("send/{}/{}", lease.mailbox.link_id, lease.message_id);sqlx::query!("INSERT INTO email_projection_outbox (id,link_id,generation,payload,dedupe_key) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (dedupe_key) DO NOTHING",macro_uuid::generate_uuid_v7(),lease.mailbox.link_id,lease.mailbox.sync_generation,payload,dedupe).execute(&mut *tx).await.map_err(db_error)?;// Reconcile attachments and the provider's authoritative sent timestamp.diff --git a/crates/email_db_client/AGENTS.md b/crates/email_db_client/AGENTS.mdindex b124d1e251..8926bffad4 100644--- a/crates/email_db_client/AGENTS.md+++ b/crates/email_db_client/AGENTS.md@@ -91,3 +91,5 @@ Parsed message responses expose the draft generation captured in the same SQL sn## Related- Rules: `.agents/rules/rust/db.md` · Docs: `docs/development/database.md`++- Scheduled-message reads and upserts preserve nullable agent correlation across delivery claims and retries.diff --git a/crates/email_db_client/src/messages/scheduled/delivery.rs b/crates/email_db_client/src/messages/scheduled/delivery.rsindex 624bd067a2..4510604fac 100644--- a/crates/email_db_client/src/messages/scheduled/delivery.rs+++ b/crates/email_db_client/src/messages/scheduled/delivery.rs@@ -46,7 +46,7 @@ pub async fn claim_delivery(return Ok(None);}let schedule = sqlx::query!(- r#"SELECT send_time, sent, processing, actor_id, delivery_claim_id,+ r#"SELECT send_time, sent, processing, actor_id, agent_correlation_id, delivery_claim_id,delivery_started_at, delivery_message_id, delivery_status, approved_attachments,(send_time <= NOW() AND NOT sent AND delivery_status <> 'failed'AND (CASE WHEN processing THEN@@ -94,6 +94,7 @@ pub async fn claim_delivery(sent: false,processing: true,actor_id: schedule.actor_id,+ agent_correlation_id: schedule.agent_correlation_id,},token,message_id_header: header,diff --git a/crates/email_db_client/src/messages/scheduled/get.rs b/crates/email_db_client/src/messages/scheduled/get.rsindex 36d703c138..1138b9be4f 100644--- a/crates/email_db_client/src/messages/scheduled/get.rs+++ b/crates/email_db_client/src/messages/scheduled/get.rs@@ -17,7 +17,7 @@ wherelet record = sqlx::query_as!(service::message::ScheduledMessage,r#"- SELECT link_id, message_id, send_time, sent, processing, actor_id+ SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_idFROM email_scheduled_messagesWHERE link_id = $1 AND message_id = $2"#,@@ -60,7 +60,7 @@ pub async fn get_and_start_processing_scheduled_message(AND delivery_claim_id IS NULL AND delivery_started_at IS NULL AND delivery_status = 'ready'AND NOT EXISTS(SELECT 1 FROM email_attachments_drafts WHERE draft_id=$2 AND upload_pending)AND NOT EXISTS(SELECT 1 FROM email_draft_transfers WHERE (destination_id=$2 AND state NOT IN ('ready','retained','preparing')) OR (source_id=$2 AND state<>'preparing'))- RETURNING link_id, message_id, send_time, sent, processing, actor_id+ RETURNING link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_id"#,link_id,message_id,@@ -81,7 +81,7 @@ pub async fn get_scheduled_message_no_auth(let record = sqlx::query_as!(db::message::ScheduledMessage,r#"- SELECT link_id, message_id, send_time, sent, processing, actor_id+ SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_idFROM email_scheduled_messagesWHERE message_id = $1 and sent = false"#,@@ -123,7 +123,7 @@ pub async fn fetch_scheduled_messages_in_bulk(let records = sqlx::query_as!(db::message::ScheduledMessage,r#"- SELECT link_id, message_id, send_time, sent, processing, actor_id+ SELECT link_id, message_id, send_time, sent, processing, actor_id, agent_correlation_idFROM email_scheduled_messagesWHERE message_id = ANY($1) AND sent = false"#,diff --git a/crates/email_db_client/src/messages/scheduled/upsert.rs b/crates/email_db_client/src/messages/scheduled/upsert.rsindex 3f5f95355c..1a86ac05c6 100644--- a/crates/email_db_client/src/messages/scheduled/upsert.rs+++ b/crates/email_db_client/src/messages/scheduled/upsert.rs@@ -10,13 +10,14 @@ pub async fn upsert_scheduled_message(let result = sqlx::query!(r#"INSERT INTO email_scheduled_messages (- link_id, message_id, send_time, sent, actor_id,+ link_id, message_id, send_time, sent, actor_id, agent_correlation_id,created_at, updated_at)- VALUES ($1, $2, $3, $4, $5, NOW(), NOW())+ VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())ON CONFLICT (link_id, message_id) DO UPDATE SETsend_time = EXCLUDED.send_time,actor_id = EXCLUDED.actor_id,+ agent_correlation_id = EXCLUDED.agent_correlation_id,updated_at = NOW()WHERE NOT email_scheduled_messages.sent AND NOT email_scheduled_messages.processing"#,@@ -25,6 +26,7 @@ pub async fn upsert_scheduled_message(db_message.send_time,db_message.sent,db_message.actor_id,+ db_message.agent_correlation_id,).execute(&mut *tx).await?;diff --git a/crates/graphql_activity/src/objects/test.rs b/crates/graphql_activity/src/objects/test.rsindex 4e6df4f11b..d23cb2fc12 100644--- a/crates/graphql_activity/src/objects/test.rs+++ b/crates/graphql_activity/src/objects/test.rs@@ -14,6 +14,7 @@ fn actor() -> activity::Actor<'static> {fn record(action: RecordedAction) -> ActivityRecord {ActivityRecord {+ agent_correlation_id: None,id: Uuid::from_u128(1),actor: actor(),subject_id: "macro|[email protected]".to_string(),diff --git a/crates/graphql_activity/src/subscriptions/test.rs b/crates/graphql_activity/src/subscriptions/test.rsindex 7d3c86e0c5..67ed3ea924 100644--- a/crates/graphql_activity/src/subscriptions/test.rs+++ b/crates/graphql_activity/src/subscriptions/test.rs@@ -64,6 +64,7 @@ fn record(user_id: &MacroUserIdStr<'static>) -> ActivityRecord {Utc::now(),);ActivityRecord {+ agent_correlation_id: activity.agent_correlation_id,id: activity.id,actor: activity.actor.clone(),subject_id: activity.subject_id.clone(),diff --git a/crates/local_e2e_test_support/src/jwt.rs b/crates/local_e2e_test_support/src/jwt.rsindex 5b11404261..9322a65804 100644--- a/crates/local_e2e_test_support/src/jwt.rs+++ b/crates/local_e2e_test_support/src/jwt.rs@@ -94,6 +94,8 @@ pub fn encode_local_jwt_claims_with(};encode_macro_api_token(EncodeMacroApiTokenArgs {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: None,agent_via: None,fusionauth_id: claims.fusion_user_id.to_owned(),diff --git a/crates/macro_auth/AGENTS.md b/crates/macro_auth/AGENTS.mdindex b5cae8be84..67ea0bb0f1 100644--- a/crates/macro_auth/AGENTS.md+++ b/crates/macro_auth/AGENTS.md@@ -45,3 +45,5 @@ producers leave both absent.## Related- Rules: `.agents/rules/rust/security.md`++- SDK JWTs optionally carry signed `agent_correlation_id` and managed-MCP `agent_session_id`; these are attribution, never additional authorization.diff --git a/crates/macro_auth/src/macro_api_token.rs b/crates/macro_auth/src/macro_api_token.rsindex 5c530a50d9..dec8aef011 100644--- a/crates/macro_auth/src/macro_api_token.rs+++ b/crates/macro_auth/src/macro_api_token.rs@@ -25,6 +25,12 @@ pub struct MacroApiToken {/// such as "Claude Code"; a display label signed with `agent_id`.#[serde(default, skip_serializing_if = "Option::is_none")]pub agent_via: Option<String>,+ /// Invocation attribution, signed by the code-mode host.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<Uuid>,+ /// Session provenance for managed MCP callers; not an access grant.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_session_id: Option<Uuid>,}pub struct EncodeMacroApiTokenArgs {@@ -44,6 +50,10 @@ pub struct EncodeMacroApiTokenArgs {pub agent_id: Option<Uuid>,/// Optional client label for `agent_id`; never supplied by an API caller.pub agent_via: Option<String>,+ /// Optional signed invocation attribution.+ pub agent_correlation_id: Option<Uuid>,+ /// Optional managed MCP session provenance.+ pub agent_session_id: Option<Uuid>,}#[tracing::instrument(skip(args))]@@ -57,6 +67,8 @@ pub fn encode_macro_api_token(args: EncodeMacroApiTokenArgs) -> anyhow::Result<Sexp: now + args.expiry_seconds,agent_id: args.agent_id,agent_via: args.agent_via,+ agent_correlation_id: args.agent_correlation_id,+ agent_session_id: args.agent_session_id,iss: args.issuer.clone(),fusion_user_id: args.fusionauth_id.clone(),macro_user_id: args.macro_user_id.clone(),diff --git a/crates/macro_auth/src/middleware/decode_jwt.rs b/crates/macro_auth/src/middleware/decode_jwt.rsindex a886de9e5e..5ea495c94a 100644--- a/crates/macro_auth/src/middleware/decode_jwt.rs+++ b/crates/macro_auth/src/middleware/decode_jwt.rs@@ -60,6 +60,18 @@ impl JwtValidationArgs {})}+ /// Build an isolated Macro JWT verifier with fixture keys.+ #[cfg(feature = "testing")]+ pub fn testing_macro_token(issuer: &'static str, public_key: &'static str) -> Self {+ Self {+ macro_api_token_issuer: MacroApiTokenIssuer::Comptime(issuer),+ macro_api_token_public_key: LocalOrRemoteSecret::Local(+ MacroApiTokenPublicKey::Comptime(public_key),+ ),+ ..Self::new_testing()+ }+ }+#[cfg(feature = "testing")]#[allow(dead_code)]/// create a new instance of Self with all empty values@@ -431,6 +443,8 @@ CwIDAQAB});let claims = MacroApiToken {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: None,agent_via: None,exp: now + 3600, // Token expires in 1 hourdiff --git a/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs b/crates/macro_auth/src/middleware/decode_jwt/agent_test.rsindex ec84f88b1b..c626ba950f 100644--- a/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs+++ b/crates/macro_auth/src/middleware/decode_jwt/agent_test.rs@@ -5,6 +5,8 @@ use crate::macro_api_token::{EncodeMacroApiTokenArgs, encode_macro_api_token};fn signed_execution_token_preserves_owner_agent_and_lifetime() {let agent = uuid::Uuid::from_u128(0xa2a2);let token = encode_macro_api_token(EncodeMacroApiTokenArgs {+ agent_correlation_id: Some(uuid::Uuid::from_u128(123)),+ agent_session_id: Some(uuid::Uuid::from_u128(456)),fusionauth_id: "fusion-owner".into(),macro_user_id: "macro|[email protected]".into(),organization_id: Some(42),@@ -28,6 +30,11 @@ fn signed_execution_token_preserves_owner_agent_and_lifetime() {panic!("expected Macro API token");};assert_eq!(claims.agent_id, Some(agent));+ assert_eq!(+ claims.agent_correlation_id,+ Some(uuid::Uuid::from_u128(123))+ );+ assert_eq!(claims.agent_session_id, Some(uuid::Uuid::from_u128(456)));assert_eq!(claims.agent_via.as_deref(), Some("Claude Code"));assert_eq!(claims.macro_user_id, "macro|[email protected]");assert_eq!(claims.macro_organization_id, Some(42));@@ -40,7 +47,7 @@ fn signed_execution_token_preserves_owner_agent_and_lifetime() {// An edited attribution cannot be signed with a user's HMAC credential.let mut forged = claims;- forged.agent_id = Some(uuid::Uuid::from_u128(0xb0b));+ forged.agent_correlation_id = Some(uuid::Uuid::from_u128(0xb0b));let mut header = jsonwebtoken::Header::new(Algorithm::HS256);header.kid = Some("macro".into());let token = jsonwebtoken::encode(@@ -61,4 +68,6 @@ fn legacy_user_token_has_no_agent_attribution() {.unwrap();assert_eq!(claims.agent_id, None);assert_eq!(claims.agent_via, None);+ assert_eq!(claims.agent_correlation_id, None);+ assert_eq!(claims.agent_session_id, None);}diff --git a/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rsindex 426deff6df..d9d67ff794 100644--- a/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs+++ b/crates/macro_auth/src/middleware/decode_jwt/fusionauth_access_token_test.rs@@ -92,6 +92,8 @@ fn tokens_not_issued_by_fusionauth_for_this_application_are_rejected() {);let other_payload = other_user.split('.').nth(1).unwrap();let macro_api_token = encode_macro_api_token(EncodeMacroApiTokenArgs {+ agent_correlation_id: None,+ agent_session_id: None,fusionauth_id: "fusion-user".into(),macro_user_id: "macro|[email protected]".into(),organization_id: None,diff --git a/crates/macro_authorization/src/outbound/macro_auth/test.rs b/crates/macro_authorization/src/outbound/macro_auth/test.rsindex 59df728f0e..58cad5ef06 100644--- a/crates/macro_authorization/src/outbound/macro_auth/test.rs+++ b/crates/macro_authorization/src/outbound/macro_auth/test.rs@@ -142,6 +142,8 @@ fn preserves_access_token_organization_id() {#[test]fn maps_macro_api_token_claims() {let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: None,agent_via: None,exp: unix_timestamp() + 3_600,@@ -164,6 +166,8 @@ fn maps_macro_api_token_claims() {fn maps_signed_agent_without_changing_owner_identity() {let agent = bot_id::MACRO_NEW_BOT_ID;let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: Some(agent.as_uuid()),agent_via: Some("Claude Code".into()),exp: unix_timestamp() + 60,@@ -183,6 +187,8 @@ fn maps_signed_agent_without_changing_owner_identity() {#[test]fn ignores_a_client_label_without_a_signed_agent() {let credential = identity_from_token(JwtToken::MacroApiToken(MacroApiToken {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: None,agent_via: Some("Claude Code".into()),exp: unix_timestamp() + 60,diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.mdindex 7e2bf18bb7..8715166b2b 100644--- a/crates/macro_db_client/AGENTS.md+++ b/crates/macro_db_client/AGENTS.md@@ -123,3 +123,5 @@ foreign keys; the broker deletes expired rows.- Spam/Trash candidate indexes cover `email_messages(link_id, id)` only for the corresponding positive `mailbox_state` JSON containment predicate; keep query literals aligned with the partial-index predicates.- If either concurrent folder-index migration is interrupted, inspect `pg_index.indisvalid` and drop only its invalid index before retrying; `CREATE INDEX IF NOT EXISTS` would silently preserve an unusable index.++- `agent_correlation` owns invocation mappings; activity and scheduled-email correlation columns remain nullable for older writers. Build the activity correlation index concurrently, outside a transaction.diff --git a/crates/macro_db_client/migrations/20261105221539_agent_activity_correlation.sql b/crates/macro_db_client/migrations/20261105221539_agent_activity_correlation.sqlnew file mode 100644index 0000000000..09f41cb14d--- /dev/null+++ b/crates/macro_db_client/migrations/20261105221539_agent_activity_correlation.sql@@ -0,0 +1,10 @@+-- New metadata is nullable for existing writers and historical activity.+SET lock_timeout = '5s';+CREATE TABLE agent_correlations (+ id uuid PRIMARY KEY,+ agent_session_id uuid NOT NULL REFERENCES agent_session(id) ON DELETE CASCADE+);+CREATE INDEX agent_correlations_session_idx ON agent_correlations(agent_session_id, id);+ALTER TABLE activity_events ADD COLUMN agent_correlation_id uuid;+-- Deliberately no activity FK: deleting a session removes its mappings without+-- deleting or rewriting the affected entities' existing activity history.diff --git a/crates/macro_db_client/migrations/20261105222103_agent_correlation_scheduled_email.sql b/crates/macro_db_client/migrations/20261105222103_agent_correlation_scheduled_email.sqlnew file mode 100644index 0000000000..e38155fc4a--- /dev/null+++ b/crates/macro_db_client/migrations/20261105222103_agent_correlation_scheduled_email.sql@@ -0,0 +1,3 @@+SET lock_timeout = '5s';++ALTER TABLE email_scheduled_messages ADD COLUMN agent_correlation_id uuid;diff --git a/crates/macro_db_client/migrations/20261105222608_index_agent_activity_correlation.sql b/crates/macro_db_client/migrations/20261105222608_index_agent_activity_correlation.sqlnew file mode 100644index 0000000000..b603c94c8b--- /dev/null+++ b/crates/macro_db_client/migrations/20261105222608_index_agent_activity_correlation.sql@@ -0,0 +1,5 @@+-- no-transaction++CREATE INDEX CONCURRENTLY IF NOT EXISTS activity_events_agent_correlation_idx+ ON activity_events(agent_correlation_id, occurred_at DESC, id DESC)+ WHERE agent_correlation_id IS NOT NULL;diff --git a/crates/macro_event_broker/AGENTS.md b/crates/macro_event_broker/AGENTS.mdindex b79c0bdb7c..a9458be57d 100644--- a/crates/macro_event_broker/AGENTS.md+++ b/crates/macro_event_broker/AGENTS.md@@ -47,3 +47,5 @@ Macro's event topics.## Related- Rules: `.agents/rules/rust/architecture.md` (CS-51/CS-52 hexagonal layering)++- Event constructors capture request-local agent correlation into the envelope; restore it before downstream mutations and capture it before spawning work.diff --git a/crates/macro_event_broker/Cargo.toml b/crates/macro_event_broker/Cargo.tomlindex f1229ebddc..a5d7df95c4 100644--- a/crates/macro_event_broker/Cargo.toml+++ b/crates/macro_event_broker/Cargo.toml@@ -9,6 +9,7 @@ default = ["outbound"]outbound = ["dep:kafka_util", "dep:rdkafka", "dep:tokio-util"][dependencies]+agent_correlation = { path = "../agent_correlation" }kafka_util = { path = "../kafka_util", optional = true }rootcause = { workspace = true }rdkafka = { workspace = true, optional = true }diff --git a/crates/macro_event_broker/src/domain/models.rs b/crates/macro_event_broker/src/domain/models.rsindex a5e6141bd8..2a62c70f71 100644--- a/crates/macro_event_broker/src/domain/models.rs+++ b/crates/macro_event_broker/src/domain/models.rs@@ -30,6 +30,9 @@ pub trait TopicEvent: Serialize + DeserializeOwned + Send + Sync {pub struct Event<E> {/// Unique identifier for this event instance.pub event_id: Uuid,+ /// Accepted originating code-mode invocation, retained across delivery.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<Uuid>,/// Version of the event payload schema.pub schema_version: u8,/// Topic-specific event variant and strongly typed metadata.@@ -58,6 +61,7 @@ impl<E: TopicEvent> Event<E> {pub fn with_event_id_and_schema_version(event_id: Uuid, schema_version: u8, event: E) -> Self {Self {event_id,+ agent_correlation_id: agent_correlation::context::current(),schema_version,event,}@@ -210,6 +214,15 @@ macro_rules! declare_topics {)+}+ impl $collection {+ /// The originating code-mode invocation, if any.+ pub fn agent_correlation_id(&self) -> Option<$crate::EventUuid> {+ match self {+ $(Self::$event(event) => $crate::MacroEvent::event(event).agent_correlation_id,)++ }+ }+ }+impl $crate::MacroEventCollection for $collection {fn decode<T: $crate::MessageParts>(message: &T,diff --git a/crates/macro_event_broker/src/domain/models/test.rs b/crates/macro_event_broker/src/domain/models/test.rsindex b54198ec62..dc488ab7ef 100644--- a/crates/macro_event_broker/src/domain/models/test.rs+++ b/crates/macro_event_broker/src/domain/models/test.rs@@ -186,14 +186,19 @@ fn exposes_each_declared_topic_in_order() {#[test]fn decodes_each_declared_topic_into_its_enum_variant() {- let example_payload = serde_json::to_vec(&example_event()).unwrap();+ let correlation_id = Uuid::from_u128(42);+ let mut event = example_event();+ event.agent_correlation_id = Some(correlation_id);+ let example_payload = serde_json::to_vec(&event).unwrap();let example_message = MessageWrapper::<_, DeclaredMacroEvent>::new(TestMessage {topic: MacroExampleTopic::TOPIC_STR,key: Some("example-key"),payload: Some(example_payload),});- match example_message.decode_payload().unwrap() {+ let decoded = example_message.decode_payload().unwrap();+ assert_eq!(decoded.agent_correlation_id(), Some(correlation_id));+ match decoded {DeclaredMacroEvent::ExampleMacroEvent(event) => {assert_eq!(event.key(), "example-key");}@@ -207,7 +212,9 @@ fn decodes_each_declared_topic_into_its_enum_variant() {payload: Some(documents_payload),});- match documents_message.decode_payload().unwrap() {+ let decoded = documents_message.decode_payload().unwrap();+ assert_eq!(decoded.agent_correlation_id(), None);+ match decoded {DeclaredMacroEvent::DocumentsMacroEvent(event) => {assert_eq!(event.key(), "documents-key");}@@ -282,3 +289,23 @@ fn rejects_an_unsupported_schema_version() {}) if topic == MacroExampleTopic::TOPIC_STR));}++#[tokio::test]+async fn envelope_round_trip_preserves_correlation_and_legacy_events_default_to_none() {+ let id = Uuid::now_v7();+ let event = agent_correlation::context::scope(Some(id), async { example_event() }).await;+ let decoded: Event<ExampleTopicEvent> =+ serde_json::from_slice(&serde_json::to_vec(&event).unwrap()).unwrap();+ assert_eq!(decoded.agent_correlation_id, Some(id));+ let mut legacy = serde_json::to_value(event).unwrap();+ legacy+ .as_object_mut()+ .unwrap()+ .remove("agent_correlation_id");+ assert_eq!(+ serde_json::from_value::<Event<ExampleTopicEvent>>(legacy)+ .unwrap()+ .agent_correlation_id,+ None+ );+}diff --git a/crates/macro_event_broker/src/domain/service/test.rs b/crates/macro_event_broker/src/domain/service/test.rsindex fc252c272e..e79371a0e3 100644--- a/crates/macro_event_broker/src/domain/service/test.rs+++ b/crates/macro_event_broker/src/domain/service/test.rs@@ -224,7 +224,9 @@ fn example_event() -> ExampleMacroEvent {#[tokio::test]async fn consumer_service_receives_and_decodes_typed_event() {- let event = example_event();+ let correlation_id = Uuid::from_u128(42);+ let mut event = example_event();+ event.event.agent_correlation_id = Some(correlation_id);let consumer = TestEventConsumer {topic: MacroExampleTopic::TOPIC_STR,key: "msg-123",@@ -234,6 +236,7 @@ async fn consumer_service_receives_and_decodes_typed_event() {let message = service.recv().await.expect("message is received");let decoded = message.decode_payload().expect("associated topic decodes");+ assert_eq!(decoded.agent_correlation_id(), Some(correlation_id));let DeclaredMacroEvent::ExampleMacroEvent(decoded) = decoded;assert_eq!(decoded.key(), "msg-123");assert_eq!(decoded.event(), event.event());diff --git a/crates/macro_event_broker/src/lib.rs b/crates/macro_event_broker/src/lib.rsindex fe63f4064c..8bd275706b 100644--- a/crates/macro_event_broker/src/lib.rs+++ b/crates/macro_event_broker/src/lib.rs@@ -17,6 +17,9 @@/// Domain layer: models, ports, and service.pub mod domain;+#[doc(hidden)]+pub use uuid::Uuid as EventUuid;+pub use domain::models::{Event, EventBrokerError, MacroEvent, MessageWrapper, TopicEvent};pub use macro_event_topics::{MacroChannelsTopic, MacroDocumentsTopic, MacroEmailTopic, MacroExampleTopic,diff --git a/crates/models_email/AGENTS.md b/crates/models_email/AGENTS.mdindex 1c569ade31..2538106f52 100644--- a/crates/models_email/AGENTS.md+++ b/crates/models_email/AGENTS.md@@ -39,3 +39,5 @@ the email domain and use normalized mailbox facts, not Gmail-only label names.## Related- Rules: `.agents/rules/rust/architecture.md`++- Scheduled-message models retain optional agent correlation for delayed delivery; older rows decode without attribution.diff --git a/crates/models_email/src/email/db/message.rs b/crates/models_email/src/email/db/message.rsindex 51a7490f66..94800f7cd0 100644--- a/crates/models_email/src/email/db/message.rs+++ b/crates/models_email/src/email/db/message.rs@@ -78,6 +78,9 @@ pub struct ScheduledMessage {/// The authenticated user who initiated the send, as a principal string/// (`macro|…`). `None` for rows created before actor tracking existed.pub actor_id: Option<String>,+ /// Code-mode invocation that scheduled this delivery.+ #[serde(default)]+ pub agent_correlation_id: Option<Uuid>,}impl From<service::message::ScheduledMessage> for ScheduledMessage {@@ -89,6 +92,7 @@ impl From<service::message::ScheduledMessage> for ScheduledMessage {sent: other.sent,processing: other.processing,actor_id: other.actor_id,+ agent_correlation_id: other.agent_correlation_id,}}}diff --git a/crates/models_email/src/email/service/message.rs b/crates/models_email/src/email/service/message.rsindex 73e65bb7e9..2bc3971bfe 100644--- a/crates/models_email/src/email/service/message.rs+++ b/crates/models_email/src/email/service/message.rs@@ -330,6 +330,9 @@ pub struct ScheduledMessage {/// The authenticated user who initiated the send, as a principal string/// (`macro|…`). `None` for rows created before actor tracking existed.pub actor_id: Option<String>,+ /// Code-mode invocation that scheduled this delivery.+ #[serde(default)]+ pub agent_correlation_id: Option<Uuid>,}impl From<db::message::ScheduledMessage> for ScheduledMessage {@@ -341,6 +344,7 @@ impl From<db::message::ScheduledMessage> for ScheduledMessage {sent: other.sent,processing: other.processing,actor_id: other.actor_id,+ agent_correlation_id: other.agent_correlation_id,}}}diff --git a/docs/README.md b/docs/README.mdindex 620faeb973..433ead0a77 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,3 +21,5 @@ Agent guidance per SDK area: [`@routing` and `@agent`](architecture/agent-sdk-guBots: [building a bot](guides/bots.md) (set one up in the app, then search andpost from the TypeScript SDK).++Agent session activity: [correlation and visibility](architecture/agent-activity-correlation.md).diff --git a/docs/architecture/agent-activity-correlation.md b/docs/architecture/agent-activity-correlation.mdnew file mode 100644index 0000000000..c7ecd158e5--- /dev/null+++ b/docs/architecture/agent-activity-correlation.md@@ -0,0 +1,47 @@+# Agent activity correlation++Each managed agent code-mode invocation creates a UUIDv7 `agent_correlation_id`.+`agent_correlations` maps it to the originating session. The credential issuer+checks the session's bound agent before inserting the mapping and signs the ID+into the short-lived SDK JWT. HTTP retries inside one invocation reuse that JWT+and ID. Separate invocations get separate IDs.++Managed MCP credentials carry signed `agent_session_id` provenance so code mode+can create the same mapping for macrod sessions. The MCP credential cache includes+the session. External MCP callers and ordinary SDK credentials omit correlation.+Neither claim grants access: the JWT's existing user and agent authorization is+unchanged.++Activity-producing HTTP services run the optional correlation extractor before+their handlers. A signed correlation requires a signed agent, an existing mapping,+and a session bound to that agent. Failures return descriptive 400, 404 or 403+responses; storage failures return 503. Session state is deliberately not checked.+Uncorrelated traffic does not query the mapping table. Unsigned correlation headers+are not accepted. Public read-only and asset services retain their existing auth;+they do not produce activity-history events.++The accepted ID lives in request-local async context, independent of trace+sampling. Event constructors copy it into the Kafka envelope. Spawned mutation+work explicitly captures context. Consumers restore it before producing activity.+Email scheduling and mailbox projection payloads persist attribution for delayed+work. Signed document grants carry it through Sync, whose editor batches retain+separate attribution per invocation. Editing-session debounce keys include it.++Activity materialization stores the nullable ID on the existing `activity_events`+row. This is attribution for the existing activity vocabulary, not a log of every+SDK read, failed request or network attempt. Existing rows are not backfilled.+Activity remains in entity histories; session deletion removes correlation+mappings but does not change those histories' retention.++`GET /agent-sessions/{session_id}/activity` checks session view permission and+returns the original recorded rows across its invocations. It does not apply+additional permissions for the affected entities. The optional+`agentCorrelationId` filter is always constrained to that session. `limit` is+1–100 (default 50); `beforeAt` and `beforeId` must be supplied together. Results+sort by event time and ID descending; `nextCursor` resumes even if a corrupt row+was skipped. Indexed correlation scans support this feed.++The SDK exposes `session.activity()` and+`session.invocations.byId(id).activity()` as lazy iterators. There is no UI in this+change. Correlation IDs also appear in backend tracing for log investigation;+durable history does not depend on observability retention or sampling.diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.mdindex 34434cf42b..8b3b6b6876 100644--- a/packages/sdk/AGENTS.md+++ b/packages/sdk/AGENTS.md@@ -169,3 +169,5 @@ the existing gateway prefixes.- Workspace-import report/cancel endpoints remain app-only review plumbing,explicitly classified alongside the existing Notion routes in coverage skips.++- `AgentSession.activity()` and invocation handles iterate durable agent-correlated history lazily; session visibility controls the feed.diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex 7b6058b270..e81dd9bfb1 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsError, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponse, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkError, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponse, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkError, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponse, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId, WorkRegistrationResponse } from './types.gen';+export type { AccessLevel, ActivityWireRow, AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponse, AddConnectedMcpServerResponses, AgentAction, AgentActionId, AgentActivityCursor, AgentActivityPage, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentMode, AgentModeChoiceRequest, AgentModeChoiceResponse, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AiSuggestions, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, AppConnectedRequest, ArchiveCause, AutoArchiveOverridesBody, AutoArchivePreferencesBody, BotId, CalendarSuggestions, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponse, CallConnectedAppToolResponses, CallConnectedTool, CallSearchSuggestions, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSearchSuggestions, ChannelSharePermission, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponse, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyInputRequest, ClassifyInputResponse, ClassifyResponse, ClassifyResponses, ClientOptions, CodingPreferencesBody, ConnectedApp, ConnectedAppKind, ConnectedTool, ConnectedToolMatch, ConnectedToolResult, ConnectedToolSearch, ConnectMcpServer, ConnectMcpServerResponse, ConnectorTool, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DecisionVia, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponse, DiscoverConnectedAppsResponses, DiscoverConnectorsResponse, DiscoveredApp, DiscoveryRequest, DiscoveryResult, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmailSearchSuggestions, EmailSuggestions, EntityType, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, ExtractData, ExtractErrors, ExtractInputRequest, ExtractInputResponse, ExtractResponse, ExtractResponses, FileChangeKindDto, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesError, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponse, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionActivityData, GetAgentSessionActivityErrors, GetAgentSessionActivityResponse, GetAgentSessionActivityResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveError, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponse, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, InputIntent, InputPropertyDefinition, InputPropertySuggestion, InputSuggestions, IntentScore, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsError, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponse, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponse, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponse, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, MessageSuggestions, ModelHarnessDto, MonthlyWeekday, NoteSuggestions, PermissionAnswer, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponse, PresentSessionViewResponses, PresentView, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesError, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponse, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveError, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponse, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QuerySearchSuggestions, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RecurrenceEnd, RecurrenceFrequency, RecurrenceSuggestion, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkError, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponse, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedError, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewDecisionContext, ReviewId, ReviewRecord, SandboxSize, SandboxSizeBody, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponse, SearchConnectedAppToolsResponses, SearchSuggestions, SearchType, SessionAutoArchiveResponse, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, TaskSearchSuggestions, TaskSuggestions, ToolActor, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkError, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponse, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WeekdayCode, WithAgentSessionId, WorkRegistrationResponse } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex d0c0ece5c6..863ed030dc 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponses, AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';+import type { AddConnectedMcpServerData, AddConnectedMcpServerErrors, AddConnectedMcpServerResponses, AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CallConnectedAppToolData, CallConnectedAppToolErrors, CallConnectedAppToolResponses, ChooseAgentModeData, ChooseAgentModeErrors, ChooseAgentModeResponses, ClassifyData, ClassifyErrors, ClassifyResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, DiscoverConnectedAppsData, DiscoverConnectedAppsErrors, DiscoverConnectedAppsResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, ExtractData, ExtractErrors, ExtractResponses, GetAgentAutoArchivePreferencesData, GetAgentAutoArchivePreferencesErrors, GetAgentAutoArchivePreferencesResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionActivityData, GetAgentSessionActivityErrors, GetAgentSessionActivityResponses, GetAgentSessionAutoArchiveData, GetAgentSessionAutoArchiveErrors, GetAgentSessionAutoArchiveResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListAgentWorkRegistrationsData, ListAgentWorkRegistrationsErrors, ListAgentWorkRegistrationsResponses, ListConnectedAppToolsData, ListConnectedAppToolsErrors, ListConnectedAppToolsResponses, ListExecutionConnectedAppsData, ListExecutionConnectedAppsErrors, ListExecutionConnectedAppsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PresentSessionViewData, PresentSessionViewErrors, PresentSessionViewResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentAutoArchivePreferencesData, PutAgentAutoArchivePreferencesErrors, PutAgentAutoArchivePreferencesResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionAutoArchiveData, PutAgentSessionAutoArchiveErrors, PutAgentSessionAutoArchiveResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RegisterAgentSessionWorkData, RegisterAgentSessionWorkErrors, RegisterAgentSessionWorkResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, ReportAgentSessionAppConnectedData, ReportAgentSessionAppConnectedErrors, ReportAgentSessionAppConnectedResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SearchConnectedAppToolsData, SearchConnectedAppToolsErrors, SearchConnectedAppToolsResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UnregisterAgentSessionWorkData, UnregisterAgentSessionWorkErrors, UnregisterAgentSessionWorkResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -330,6 +330,13 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).get<GetAgentSessionResponses, GetAgentSessionErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}', ...options });}+ /**+ * Read activity using the same visibility capability as the session transcript.+ */+ public getAgentSessionActivity<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionActivityData, ThrowOnError>): RequestResult<GetAgentSessionActivityResponses, GetAgentSessionActivityErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetAgentSessionActivityResponses, GetAgentSessionActivityErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/activity', ...options });+ }+/*** Continue the session now that its owner connected an app it asked for.*diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex a713513783..1f11592494 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -9,6 +9,49 @@ export type ClientOptions = {*/export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';+/**+ * One activity row on the wire — the realtime projection of an inserted+ * `activity_events` row.+ */+export type ActivityWireRow = {+ /**+ * The stored action tag.+ */+ action: string;+ /**+ * The stored action payload, if any.+ */+ action_payload?: unknown;+ /**+ * Who mechanically acted, as a principal string (`macro|…` / `bot|…`).+ */+ actor_id: string;+ /**+ * Originating code-mode invocation, absent on older events.+ */+ agent_correlation_id?: string | null;+ /**+ * The entity acted on.+ */+ entity_id: string;+ /**+ * The kind of entity acted on.+ */+ entity_type: EntityType;+ /**+ * The stored activity id.+ */+ id: string;+ /**+ * When it happened.+ */+ occurred_at: string;+ /**+ * Whose activity this is (a principal string).+ */+ subject_id: string;+};+/*** One thing a caller wants an agent to do.*/@@ -43,6 +86,31 @@ export type AgentAction = (AgentPromptAction & {*/export type AgentActionId = string;+/**+ * Stable chronological resume position.+ */+export type AgentActivityCursor = {+ /**+ * Tie-breaking activity identity.+ */+ id: string;+ /**+ * Last stored event time.+ */+ occurredAt: string;+};++/**+ * One page of the activity caused by this session.+ */+export type AgentActivityPage = {+ /**+ * Original activity rows, also retained in the affected entities' histories.+ */+ activities: Array<ActivityWireRow>;+ nextCursor?: null | AgentActivityCursor;+};+/*** Type-specific state for one agent session setting.*/@@ -1586,6 +1654,11 @@ export type EmailSuggestions = {subject?: string | null;};+/**+ * The type of an entity in Macro+ */+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form' | 'external_chat';+/*** A bounded SDK operation observed during execution; not an authorization or write receipt.*/@@ -3309,6 +3382,44 @@ export type GetAgentSessionResponses = {export type GetAgentSessionResponse = GetAgentSessionResponses[keyof GetAgentSessionResponses];+export type GetAgentSessionActivityData = {+ body?: never;+ path: {+ session_id: string;+ };+ query?: {+ /**+ * Restrict activity to one code-mode invocation within this session.+ */+ agentCorrelationId?: string | null;+ /**+ * Cursor timestamp from the previous page.+ */+ beforeAt?: string | null;+ /**+ * Cursor activity ID from the previous page.+ */+ beforeId?: string | null;+ /**+ * Page size, from 1 to 100; defaults to 50.+ */+ limit?: number | null;+ };+ url: '/agent-sessions/{session_id}/activity';+};++export type GetAgentSessionActivityErrors = {+ 400: unknown;+ 401: unknown;+ 403: unknown;+};++export type GetAgentSessionActivityResponses = {+ 200: AgentActivityPage;+};++export type GetAgentSessionActivityResponse = GetAgentSessionActivityResponses[keyof GetAgentSessionActivityResponses];+export type ReportAgentSessionAppConnectedData = {body: AppConnectedRequest;path: {diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex da969b07a4..81960d67ac 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -6163,6 +6163,10 @@ export type DocumentSyncEditor = {* User or bot that performed the edit.*/actor: string;+ /**+ * Invocation from the editor's signed document grant.+ */+ agent_correlation_id?: string | null;on_behalf_of?: null | MacroUserIdStr;};diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 1dddeb619c..d8e4ff473a 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -1091,6 +1091,87 @@}}},+ "/agent-sessions/{session_id}/activity": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read activity using the same visibility capability as the session transcript.",+ "operationId": "get_agent_session_activity",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "agentCorrelationId",+ "in": "query",+ "description": "Restrict activity to one code-mode invocation within this session.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "uuid"+ }+ },+ {+ "name": "beforeAt",+ "in": "query",+ "description": "Cursor timestamp from the previous page.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "date-time"+ }+ },+ {+ "name": "beforeId",+ "in": "query",+ "description": "Cursor activity ID from the previous page.",+ "required": false,+ "schema": {+ "type": ["string", "null"],+ "format": "uuid"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size, from 1 to 100; defaults to 50.",+ "required": false,+ "schema": {+ "type": ["integer", "null"],+ "format": "int32",+ "maximum": 100,+ "minimum": 1+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AgentActivityPage"+ }+ }+ }+ },+ "400": {+ "description": ""+ },+ "401": {+ "description": ""+ },+ "403": {+ "description": ""+ }+ }+ }+ },"/agent-sessions/{session_id}/app-connections": {"post": {"tags": ["agent-sessions"],@@ -3590,6 +3671,59 @@"description": "Ordered from least to most access top -> bottom","enum": ["view", "comment", "edit", "owner"]},+ "ActivityWireRow": {+ "type": "object",+ "description": "One activity row on the wire — the realtime projection of an inserted\n`activity_events` row.",+ "required": [+ "id",+ "actor_id",+ "subject_id",+ "entity_type",+ "entity_id",+ "action",+ "occurred_at"+ ],+ "properties": {+ "action": {+ "type": "string",+ "description": "The stored action tag."+ },+ "action_payload": {+ "description": "The stored action payload, if any."+ },+ "actor_id": {+ "type": "string",+ "description": "Who mechanically acted, as a principal string (`macro|…` / `bot|…`)."+ },+ "agent_correlation_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Originating code-mode invocation, absent on older events."+ },+ "entity_id": {+ "type": "string",+ "description": "The entity acted on."+ },+ "entity_type": {+ "$ref": "#/components/schemas/EntityType",+ "description": "The kind of entity acted on."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "The stored activity id."+ },+ "occurred_at": {+ "type": "string",+ "format": "date-time",+ "description": "When it happened."+ },+ "subject_id": {+ "type": "string",+ "description": "Whose activity this is (a principal string)."+ }+ }+ },"AgentAction": {"oneOf": [{@@ -3717,6 +3851,48 @@"format": "uuid","description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},+ "AgentActivityCursor": {+ "type": "object",+ "description": "Stable chronological resume position.",+ "required": ["occurredAt", "id"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Tie-breaking activity identity."+ },+ "occurredAt": {+ "type": "string",+ "format": "date-time",+ "description": "Last stored event time."+ }+ }+ },+ "AgentActivityPage": {+ "type": "object",+ "description": "One page of the activity caused by this session.",+ "required": ["activities"],+ "properties": {+ "activities": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ActivityWireRow"+ },+ "description": "Original activity rows, also retained in the affected entities' histories."+ },+ "nextCursor": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AgentActivityCursor",+ "description": "Resume position, present when more raw rows remain."+ }+ ]+ }+ }+ },"AgentConfigKindDto": {"oneOf": [{@@ -5695,6 +5871,36 @@},"additionalProperties": false},+ "EntityType": {+ "type": "string",+ "description": "The type of an entity in Macro",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "crm_pipeline",+ "reminder",+ "skill",+ "agent_session",+ "scheduled_action",+ "initiative",+ "database",+ "database_row",+ "form",+ "external_chat"+ ]+ },"ExecutionActivity": {"type": "object","description": "A bounded SDK operation observed during execution; not an authorization or write receipt.",diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 3be2d08526..ad5f14e9f2 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -30520,6 +30520,11 @@"type": "string","description": "User or bot that performed the edit."},+ "agent_correlation_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Invocation from the editor's signed document grant."+ },"on_behalf_of": {"oneOf": [{diff --git a/packages/sdk/src/entities/agent-sessions/activity.ts b/packages/sdk/src/entities/agent-sessions/activity.tsnew file mode 100644index 0000000000..7265a31c7b--- /dev/null+++ b/packages/sdk/src/entities/agent-sessions/activity.ts@@ -0,0 +1,88 @@+import type {+ ActivityWireRow,+ AgentActivityCursor,+} from '../../../generated/agent-harness/types.gen';+import { paginate, unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { AgentSession } from './agent-session';++/** Page options for recorded session activity, newest first. */+export type AgentActivityOptions = {+ /** Page size, from 1 to 100; defaults to 50. */+ limit?: number;+ /** Restrict to one code-mode invocation belonging to this session. */+ invocation?: AgentInvocation;+};++/** A code-mode invocation, identified independently of its runtime or retries. */+export class AgentInvocation {+ private constructor(+ private readonly client: MacroClient,+ private readonly parent: AgentSession,+ readonly id: string,+ ) {}++ /** Construct a handle without making a request. */+ static byId(client: MacroClient, session: AgentSession, id: string) {+ return new AgentInvocation(client, session, id);+ }++ /** The session that owns this invocation. */+ session(): AgentSession {+ return this.parent;+ }++ /** Recorded activity caused by this invocation, lazily paginated. */+ activity(options: Omit<AgentActivityOptions, 'invocation'> = {}) {+ return sessionActivity(this.client, this.parent, {+ ...options,+ invocation: this,+ });+ }++ /** Safe identity without an authenticated client. */+ toJSON() {+ return { id: this.id, session: { id: this.parent.id } };+ }+}++/** An original activity-history row attributed to a session. */+export type AgentActivity = {+ /** The originating invocation; absent on legacy rows. */+ invocation?: AgentInvocation;+ /** Original recorded metadata. Action tags and payloads are forward-compatible. */+ snapshot: ActivityWireRow;+};++/** Iterate recorded mutations; reads and failed requests do not create history. */+export function sessionActivity(+ client: MacroClient,+ session: AgentSession,+ options: AgentActivityOptions = {},+): AsyncGenerator<AgentActivity> {+ if (options.invocation && options.invocation.session().id !== session.id) {+ throw new Error('Activity invocation must belong to this session');+ }+ return paginate<AgentActivity, AgentActivityCursor>(async (cursor) => {+ const page = unwrap(+ await client.agentHarness.getAgentSessionActivity({+ path: { session_id: session.id },+ query: {+ limit: options.limit,+ agentCorrelationId: options.invocation?.id,+ beforeAt: cursor?.occurredAt,+ beforeId: cursor?.id,+ },+ }),+ );+ return {+ items: page.activities.map((snapshot) => ({+ snapshot,+ invocation: snapshot.agent_correlation_id+ ? AgentInvocation.byId(client, session, snapshot.agent_correlation_id)+ : undefined,+ })),+ nextCursor: page.nextCursor,+ };+ });+}diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.tsindex 726e2d6582..490d8f6294 100644--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts@@ -25,6 +25,11 @@ import {sharePermissionBody,} from '../sharing/permissions';import { User } from '../users/user';+import {+ type AgentActivityOptions,+ AgentInvocation,+ sessionActivity,+} from './activity';import { CodeExecution } from './code-execution';import { QueuedAction } from './queued-action';import { type CreateReviewOptions, SessionReview } from './review';@@ -682,6 +687,16 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {CodeExecution.byId(this.client, this, id),};+ /** Recorded activity caused by this session, lazily paginated newest first. */+ activity(options: AgentActivityOptions = {}) {+ return sessionActivity(this.client, this, options);+ }++ /** Code-mode invocation handles, distinct from saved code executions. */+ readonly invocations = {+ byId: (id: string) => AgentInvocation.byId(this.client, this, id),+ };+/** Delete this session and any live resources it owns. */async delete(): Promise<void> {await this.mutate((client) =>diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex cc4a60177f..e72bf6c0b5 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -279,6 +279,11 @@ export class Macro<T extends MacroOpts = MacroOpts> {}}+export {+ type AgentActivity,+ type AgentActivityOptions,+ AgentInvocation,+} from './entities/agent-sessions/activity';export type {ArchiveCause,AutoArchiveOverrides,diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.tsindex 2c4b443d60..cc6e5a961b 100644--- a/packages/sdk/tests/agent-sessions.test.ts+++ b/packages/sdk/tests/agent-sessions.test.ts@@ -664,3 +664,64 @@ describe('AgentSession', () => {);});});++test('session activity keeps invocation filters and lazily advances its cursor', async () => {+ const requests: URL[] = [];+ const invocationId = '0198a4cc-e138-7670-a308-a6b766602709';+ const timestamp = '2026-11-05T12:00:00Z';+ globalThis.fetch = (async (input) => {+ const request = input instanceof Request ? input : new Request(input);+ requests.push(new URL(request.url));+ return Response.json({+ activities: [+ {+ id: `row-${requests.length}`,+ agent_correlation_id: invocationId,+ actor_id: 'bot|0198a4cc-e138-7670-a308-a6b766602701',+ subject_id: 'macro|[email protected]',+ entity_type: 'document',+ entity_id: 'document-fixture',+ action: 'edited',+ action_payload: null,+ occurred_at: timestamp,+ },+ ],+ nextCursor:+ requests.length === 1 ? { occurredAt: timestamp, id: 'row-1' } : null,+ });+ }) as typeof fetch;+ const macro = new Macro({+ token: 'fixture',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ });+ const session = macro.agentSessions.byId(sessionId);+ const invocation = session.invocations.byId(invocationId);+ const activity = invocation.activity({ limit: 1 });+ expect(requests).toHaveLength(0);+ const first = await activity.next();+ expect(first.value?.invocation?.id).toBe(invocationId);+ expect(requests).toHaveLength(1);+ const second = await activity.next();+ expect(second.value?.snapshot.id).toBe('row-2');+ expect((await activity.next()).done).toBe(true);+ expect(requests).toHaveLength(2);+ expect(+ requests.every(+ (url) => url.searchParams.get('agentCorrelationId') === invocationId,+ ),+ ).toBe(true);+ expect(requests[1].searchParams.get('beforeAt')).toBe(timestamp);+ expect(requests[1].searchParams.get('beforeId')).toBe('row-1');+ expect(JSON.stringify(invocation)).not.toContain('fixture');+});++test('session activity rejects another session invocation without a request', () => {+ const macro = new Macro({ token: 'fixture' });+ const session = macro.agentSessions.byId(sessionId);+ const foreign = macro.agentSessions+ .byId('other')+ .invocations.byId('invocation');+ expect(() => session.activity({ invocation: foreign })).toThrow(+ 'must belong to this session',+ );+});diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex 2e75bea9b0..af7a91bf3a 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -201,3 +201,5 @@ listener failure shuts down the process so ECS can replace the task.## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/config-and-service-urls.md`++- Code-mode credentials create durable per-invocation agent correlation; the final merged HTTP router validates incoming attribution before handlers.diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex a091b51068..9c8780ffdc 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -25,9 +25,10 @@ name = "scheduled_action_openapi"path = "src/scheduling_openapi.rs"[dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }universal_input = { path = "../../crates/universal_input" }models_ai_projection = { path = "../../crates/models_ai_projection" }-activity = { path = "../../crates/activity", default-features = false }+activity = { path = "../../crates/activity", default-features = false, features = ["outbound", "schema"] }agent = { path = "../../crates/agent", features = ["debug-messages"] }agent-client-protocol = { workspace = true }agent_changes = { path = "../../crates/agent_changes" }diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex 7aa73f09ef..1b62c19ebd 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -70,6 +70,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changesmodels: AgentModelsRouterState<Models, Auth>,repositories: AgentRepositoriesRouterState<Auth>,public_mcp: Router,+ correlation: Option<agent_correlation::inbound::CorrelationState>,listening: Option<tokio::sync::watch::Sender<bool>>,cognition: Router,universal_input: Router,@@ -87,6 +88,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changestool_approvals: Router,app_connections: Router,code_executions: Router,+ activity: Router,notifications: Router,changes: AgentChangesRouterState<Changes, Access, Auth>,}@@ -94,6 +96,15 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changesimpl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>{+ /// Validate and propagate signed invocation attribution across every mounted API.+ pub fn with_agent_correlation(+ mut self,+ state: agent_correlation::inbound::CorrelationState,+ ) -> Self {+ self.correlation = Some(state);+ self+ }+/// Group the independently constructed route states for the HTTP server.pub fn new(read: AgentSessionRouterState<T, Access, Auth>,@@ -105,6 +116,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>changes: AgentChangesRouterState<Changes, Access, Auth>,) -> Self {Self {+ correlation: None,read,control,create,@@ -129,6 +141,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>tool_approvals: Router::new(),app_connections: Router::new(),code_executions: Router::new(),+ activity: Router::new(),notifications: Router::new(),changes,}@@ -195,6 +208,12 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>}/// Attach session-authorized code execution records.+ /// Attach the session-authorized activity history.+ pub fn with_activity(mut self, router: Router) -> Self {+ self.activity = router;+ self+ }+pub fn with_code_executions(mut self, router: Router) -> Self {self.code_executions = router;self@@ -297,6 +316,7 @@ whereModels: AgentModelsService,Changes: AgentChanges,{+ let correlation = states.correlation.clone();let listening = states.listening.clone();let public_mcp = states.public_mcp.clone();let cognition = states.cognition.clone();@@ -326,6 +346,14 @@ whereswagger::ApiDoc::openapi(),));+ let app = match correlation {+ Some(state) => app.layer(axum::middleware::from_fn_with_state(+ state,+ agent_correlation::inbound::propagate,+ )),+ None => app,+ };+let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await.with_context(|| format!("failed to bind agent harness service to port {port}"))?;@@ -367,6 +395,7 @@ where.merge(states.tool_approvals).merge(states.app_connections).merge(states.code_executions)+ .merge(states.activity).merge(states.notifications).merge(agent_changes_router(states.changes));Router::new()diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rsindex ac895f4131..5eda384d58 100644--- a/services/agent_harness_service/src/api/swagger.rs+++ b/services/agent_harness_service/src/api/swagger.rs@@ -68,6 +68,7 @@ impl Modify for SecurityAddon {universal_input::inbound::axum_router::classify,universal_input::inbound::axum_router::extract,agent_code_mode::inbound::axum_router::get_code_execution,+ agent_session::inbound::axum_router::activity::get_agent_session_activity,agent_code_mode::inbound::axum_router::create_review,agent_code_mode::inbound::axum_router::present_view,agent_code_mode::inbound::axum_router::get_review,diff --git a/services/agent_harness_service/src/code_mode.rs b/services/agent_harness_service/src/code_mode.rsindex 634a0ea8da..90c6c45f96 100644--- a/services/agent_harness_service/src/code_mode.rs+++ b/services/agent_harness_service/src/code_mode.rs@@ -2,6 +2,7 @@use agent_code_mode::domain::{CodeModeError, ExecutionCredentials, ExecutionIdentity, UserExecutionCredentials,};+use agent_correlation::domain::CorrelationRepository;use agent_egress::outbound::macro_mcp::MacroApiTokenSigner;use agent_inmem::domain::tool_gate::{NativeToolGate, NativeToolVerdict};use async_trait::async_trait;@@ -12,6 +13,7 @@ use tokio_util::sync::CancellationToken;pub struct RunCredentials {pub signer: MacroApiTokenSigner,+ pub correlations: agent_correlation::outbound::PgCorrelationRepository,pub gate: Arc<dyn NativeToolGate>,pub hosts: BTreeMap<String, String>,}@@ -25,11 +27,26 @@ impl ExecutionCredentials for RunCredentials {cancel: CancellationToken,) -> Result<RunEnvironment, CodeModeError> {let actor = approve_run(self.gate.as_ref(), identity, source, &cancel).await?;+ let correlation = self+ .correlations+ .create(identity.session.as_uuid(), identity.agent_id.as_uuid())+ .await+ .map_err(|error| {+ tracing::error!(?error, "could not persist code-mode correlation");+ CodeModeError::Unavailable+ })?;// No refresh credential. Covers the 30-second queue/run deadline plus// clock margin; a normal user token expires rather than revoking on exit.let token = self.signer- .mint_for_agent(&actor, 60, Some(identity.agent_id.as_uuid()), None)+ .mint_for_agent(+ &actor,+ 60,+ Some(identity.agent_id.as_uuid()),+ None,+ None,+ Some(correlation),+ ).await.map_err(|error| {tracing::error!(?error, "could not mint execution credential");@@ -54,6 +71,7 @@ impl ExecutionCredentials for RunCredentials {/// no owner gate.pub struct UserRunCredentials {pub signer: MacroApiTokenSigner,+ pub correlations: agent_correlation::outbound::PgCorrelationRepository,pub hosts: BTreeMap<String, String>,}@@ -63,6 +81,7 @@ impl UserExecutionCredentials for UserRunCredentials {&self,user: &MacroUserIdStr<'static>,caller: &ai_toolset::ToolCaller,+ session: Option<uuid::Uuid>,) -> Result<RunEnvironment, CodeModeError> {let agent = match caller {ai_toolset::ToolCaller::Agent(agent) => *agent,@@ -70,6 +89,18 @@ impl UserExecutionCredentials for UserRunCredentials {bot_id::MACRO_AI_BOT_ID}};+ let correlation = match session {+ Some(session) => Some(+ self.correlations+ .create(session, agent.as_uuid())+ .await+ .map_err(|error| {+ tracing::error!(?error, "could not persist code-mode correlation");+ CodeModeError::Unavailable+ })?,+ ),+ None => None,+ };// Same lifetime as session runs: the 30-second deadline plus clock margin.let token = self.signer@@ -78,6 +109,8 @@ impl UserExecutionCredentials for UserRunCredentials {60,Some(agent.as_uuid()),caller.via().map(str::to_owned),+ None,+ correlation,).await.map_err(|error| {diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex c1cfe0e9bc..68dee5c34b 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -768,6 +768,9 @@ async fn run() -> anyhow::Result<()> {service: Arc::new(agent_code_mode::domain::UserCodeModeService::new(Arc::new(public.clone()),Arc::new(code_mode::UserRunCredentials {+ correlations: agent_correlation::outbound::PgCorrelationRepository(+ pool.clone(),+ ),signer: MacroApiTokenSigner::new(pool.clone(),config.macro_api_token_issuer.as_ref(),@@ -843,6 +846,7 @@ async fn run() -> anyhow::Result<()> {Arc::new(agent_code_mode::domain::CodeModeService::new(code_executor,Arc::new(code_mode::RunCredentials {+ correlations: agent_correlation::outbound::PgCorrelationRepository(pool.clone()),signer: MacroApiTokenSigner::new(pool.clone(),config.macro_api_token_issuer.as_ref(),@@ -1850,6 +1854,17 @@ async fn run() -> anyhow::Result<()> {service: notification_service,},);+ let correlation = agent_correlation::inbound::CorrelationState::new(+ pool.clone(),+ JwtValidationArgs::new_with_secret_manager(config.environment, &secrets).await?,+ );+ let agent_activity = agent_session::inbound::axum_router::activity::router(+ agent_session::inbound::axum_router::activity::AgentActivityState::new(+ activity::outbound::pg_activity_repo::PgActivityRepo::new(pool.clone()),+ entity_access.clone(),+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),+ ),+ );let http_shutdown = service_shutdown.clone();let http = tokio::spawn(async move {if let Err(error) = api::setup_and_serve(@@ -1862,6 +1877,8 @@ async fn run() -> anyhow::Result<()> {repositories_state,changes_state,)+ .with_agent_correlation(correlation)+ .with_activity(agent_activity).with_sharing(sharing).with_routine_sessions(routine_sessions).with_conversations(conversations)diff --git a/services/agent_harness_service/src/public_mcp/tool_service.rs b/services/agent_harness_service/src/public_mcp/tool_service.rsindex e99cb3db45..3e96b526df 100644--- a/services/agent_harness_service/src/public_mcp/tool_service.rs+++ b/services/agent_harness_service/src/public_mcp/tool_service.rs@@ -377,6 +377,9 @@ where.tools.try_tool_call(UserCodeModeToolContext {+ session: context.extensions.get::<http::request::Parts>()+ .and_then(|parts| parts.extensions.get::<mcp_auth_proxy::inbound::middleware::ManagedAgentSession>())+ .map(|session| session.0),service: code_mode.service.clone(),cognition: code_mode.cognition.clone(),caller,diff --git a/services/agent_harness_service/src/public_mcp/tool_service/test.rs b/services/agent_harness_service/src/public_mcp/tool_service/test.rsindex 14cc57048a..28d6676af0 100644--- a/services/agent_harness_service/src/public_mcp/tool_service/test.rs+++ b/services/agent_harness_service/src/public_mcp/tool_service/test.rs@@ -315,17 +315,23 @@ mod code_mode {/// Records who ran what, as which agent, and returns the source length as data.#[derive(Default)]- struct Runs(Mutex<Vec<(String, String)>>, Mutex<Vec<ToolCaller>>);+ struct Runs(+ Mutex<Vec<(String, String)>>,+ Mutex<Vec<ToolCaller>>,+ Mutex<Vec<Option<uuid::Uuid>>>,+ );#[async_trait::async_trait]impl UserCodeMode for Runs {async fn execute(&self,user: &MacroUserIdStr<'static>,caller: &ToolCaller,+ session: Option<uuid::Uuid>,request: ExecuteRequest,_: CancellationToken,) -> Result<UserExecutionReceipt, CodeModeError> {self.1.lock().unwrap().push(caller.clone());+ self.2.lock().unwrap().push(session);self.0.lock().unwrap()@@ -752,6 +758,34 @@ mod code_mode {assert_eq!(*runs.1.lock().unwrap(), callers);}+ #[tokio::test]+ async fn managed_mcp_provenance_reaches_code_mode_but_external_callers_have_none() {+ let runs = Arc::new(Runs::default());+ let session = uuid::Uuid::now_v7();+ let external = app(runs.clone());+ let managed = external.clone().layer(axum::Extension(+ mcp_auth_proxy::inbound::middleware::ManagedAgentSession(session),+ ));+ let call = serde_json::json!({"name": "ExecuteCode", "arguments": {"source": "export async function main() { return {data: 1}; }"}});+ rpc_as(+ managed,+ FLAGGED,+ Some(ToolCaller::Agent(BotId::TEST_A)),+ "tools/call",+ call.clone(),+ )+ .await;+ rpc_as(+ external,+ FLAGGED,+ Some(ToolCaller::ApiKey),+ "tools/call",+ call,+ )+ .await;+ assert_eq!(*runs.2.lock().unwrap(), [Some(session), None]);+ }+/// A request the middleware left without a caller runs nothing.#[tokio::test]async fn execute_code_without_a_caller_runs_nothing() {@@ -804,6 +838,7 @@ mod code_mode {&self,_: &MacroUserIdStr<'static>,_: &ToolCaller,+ _: Option<uuid::Uuid>,) -> Result<code_execution::domain::RunEnvironment, CodeModeError> {Ok(code_execution::domain::RunEnvironment::default())}diff --git a/services/agent_harness_service/src/routine_code.rs b/services/agent_harness_service/src/routine_code.rsindex 4e13ddbfe2..13a197dbb3 100644--- a/services/agent_harness_service/src/routine_code.rs+++ b/services/agent_harness_service/src/routine_code.rs@@ -78,6 +78,8 @@ impl RoutineCredentials for MacroApiTokenSigner {TOKEN_LIFETIME_SECONDS,Some(bot_id::MACRO_NEW_BOT_ID.as_uuid()),None,+ None,+ None,).await?)}diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex a3d5b88376..bfc205edeb 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -179,3 +179,5 @@ inputs cannot select an agent, and ordinary user credentials remain unattributed- Rules: `.agents/rules/config-and-service-urls.md`,`.agents/rules/rust/security.md` · Skill: `new-service`++- The HTTP boundary validates optional signed agent correlation without changing existing authorization.diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 1bf4e390db..c190e362dc 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -39,6 +39,7 @@ rate_limit = []return_passwordless_code = [][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }crm = { path = "../../crates/crm", default-features = false, features = ["lookup"] }agent_api_keys = { path = "../../crates/agent_api_keys" }ai_billing = { path = "../../crates/ai_billing" }diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rsindex 6cf9e3a3ed..8c5b766955 100644--- a/services/authentication_service/src/api.rs+++ b/services/authentication_service/src/api.rs@@ -61,9 +61,15 @@ pub(crate) async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::R)]);let env = state.environment;+ let correlation =+ agent_correlation::inbound::CorrelationState::new(state.db.clone(), state.jwt_args.clone());let app = api_router(state.clone()).with_state(state)+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ )).layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())// The health router is attached here so we don't attach the logging middleware to it.merge(health::router())diff --git a/services/authentication_service/src/api/jwt/macro_api_token.rs b/services/authentication_service/src/api/jwt/macro_api_token.rsindex 50f011a09f..b957d4229e 100644--- a/services/authentication_service/src/api/jwt/macro_api_token.rs+++ b/services/authentication_service/src/api/jwt/macro_api_token.rs@@ -89,6 +89,8 @@ pub async fn handler(let macro_api_token =macro_auth::macro_api_token::encode_macro_api_token(EncodeMacroApiTokenArgs {+ agent_correlation_id: None,+ agent_session_id: None,agent_id: authorization.authorization.userdiff --git a/services/calendar_service/AGENTS.md b/services/calendar_service/AGENTS.mdindex d88a3d21a0..5f2b5c6a1c 100644--- a/services/calendar_service/AGENTS.md+++ b/services/calendar_service/AGENTS.md@@ -56,3 +56,5 @@ gateway `/calendar` prefix.- Rules: `.agents/rules/config-and-service-urls.md` · Skill: `new-service` ·Docs: `docs/guides/new-service.md` (uses this service as the model)++- The HTTP boundary validates optional signed agent correlation without changing existing authorization.diff --git a/services/calendar_service/Cargo.toml b/services/calendar_service/Cargo.tomlindex 8623cc73b0..9fc28cc3f4 100644--- a/services/calendar_service/Cargo.toml+++ b/services/calendar_service/Cargo.toml@@ -18,6 +18,7 @@ connection_gateway = []default = ["connection_gateway"][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }email_api_client = { path = "../../crates/email_api_client", features = ["outbound-outlook", "microsoft-gate"] }anyhow = { workspace = true }authentication_service_client = { path = "../../crates/authentication_service_client" }diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rsindex 218952cff4..679d6e959f 100644--- a/services/calendar_service/src/api.rs+++ b/services/calendar_service/src/api.rs@@ -25,12 +25,19 @@ const GATEWAY_PATH_PREFIX: &str = "/calendar";pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {let env = state.config.environment;let port = state.config.port;- let traced_api = api_router(state.clone()).with_state(state).layer(- ServiceBuilder::new()- .layer(TraceLayer::new_for_http())- .layer(macro_cors::cors_layer())- .layer(CompressionLayer::new().gzip(true)),- );+ let correlation = state.correlation.clone();+ let traced_api = api_router(state.clone())+ .with_state(state)+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ ))+ .layer(+ ServiceBuilder::new()+ .layer(TraceLayer::new_for_http())+ .layer(macro_cors::cors_layer())+ .layer(CompressionLayer::new().gzip(true)),+ );let health = crate::health::router();let app = mount_at_root_and_prefix(traced_api.merge(health)).merge(swagger_ui());diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rsindex bb7a9d4d52..320b6e94eb 100644--- a/services/calendar_service/src/api/context.rs+++ b/services/calendar_service/src/api/context.rs@@ -50,6 +50,8 @@ pub type CalendarMutationSvc = CalendarMutationServiceImpl</// Shared HTTP application state for the calendar service.#[derive(Clone)]pub struct ApiContext {+ /// Signed invocation validation and propagation.+ pub correlation: agent_correlation::inbound::CorrelationState,/// Resolved service configuration.pub config: Arc<Config>,/// Authorization state for authenticated mutation routes.diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rsindex 1dd1606a3b..3e6398530b 100644--- a/services/calendar_service/src/main.rs+++ b/services/calendar_service/src/main.rs@@ -172,7 +172,7 @@ async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(- MacroAuthJwtValidator::new(jwt_args),+ MacroAuthJwtValidator::new(jwt_args.clone()),InternalAuthConfig {api_key: config.internal_api_key.to_string(),default_user_id: None,@@ -318,6 +318,7 @@ async fn main() -> anyhow::Result<()> {));}let api_result = calendar_service::api::setup_and_serve(ApiContext {+ correlation: agent_correlation::inbound::CorrelationState::new(db.clone(), jwt_args),config: Arc::new(config),authorization_state,calendar_service,diff --git a/services/connection_gateway/AGENTS.md b/services/connection_gateway/AGENTS.mdindex 1089fabf3b..c2a60acae9 100644--- a/services/connection_gateway/AGENTS.md+++ b/services/connection_gateway/AGENTS.md@@ -78,3 +78,5 @@ the socket themselves.## Related- Rules: `.agents/rules/config-and-service-urls.md`++- The HTTP boundary validates optional signed agent correlation without changing existing authorization.diff --git a/services/connection_gateway/Cargo.toml b/services/connection_gateway/Cargo.tomlindex a1e8d4a4f2..d4b33e6a9e 100644--- a/services/connection_gateway/Cargo.toml+++ b/services/connection_gateway/Cargo.toml@@ -29,6 +29,7 @@ path = "src/openapi.rs"local_auth = ["macro_authorization/local_auth"][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }anyhow = { workspace = true }async-trait = { workspace = true }aws-sdk-dynamodb = { workspace = true }diff --git a/services/connection_gateway/src/main.rs b/services/connection_gateway/src/main.rsindex 3e691249ec..c6732947c3 100644--- a/services/connection_gateway/src/main.rs+++ b/services/connection_gateway/src/main.rs@@ -138,7 +138,7 @@ async fn main() -> Result<()> {let config = Arc::new(config);let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(- MacroAuthJwtValidator::new(jwt_args),+ MacroAuthJwtValidator::new(jwt_args.clone()),InternalAuthConfig {api_key: config.internal_api_key.to_string(),default_user_id: None,@@ -147,6 +147,7 @@ async fn main() -> Result<()> {PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(pgpool.clone())),)));+ let correlation = agent_correlation::inbound::CorrelationState::new(pgpool.clone(), jwt_args);let app = router(AppState {context,config: Arc::clone(&config),@@ -157,7 +158,11 @@ async fn main() -> Result<()> {)),}).layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())- .layer(cors);+ .layer(cors)+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ ));tracing::info!("connection gateway is up and running with environment {:?} on port {}",diff --git a/services/contacts_service/AGENTS.md b/services/contacts_service/AGENTS.mdindex 5c2a0444f7..76f8a6d76f 100644--- a/services/contacts_service/AGENTS.md+++ b/services/contacts_service/AGENTS.md@@ -43,3 +43,5 @@ outbox worker that notifies `connection_gateway`.## Related- Domain crate: `crates/contacts`++- The HTTP boundary validates optional signed agent correlation without changing existing authorization.diff --git a/services/contacts_service/Cargo.toml b/services/contacts_service/Cargo.tomlindex 806e2de842..ac4f398a3f 100644--- a/services/contacts_service/Cargo.toml+++ b/services/contacts_service/Cargo.toml@@ -18,6 +18,7 @@ name = "contacts_service_doppler_config"path = "src/doppler_config.rs"[dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }anyhow = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }diff --git a/services/contacts_service/src/main.rs b/services/contacts_service/src/main.rsindex b872238701..a7015877cd 100644--- a/services/contacts_service/src/main.rs+++ b/services/contacts_service/src/main.rs@@ -111,7 +111,7 @@ async fn main() -> anyhow::Result<()> {).await?;let authorization_service = MacroAuthorizationServiceImpl::new(- MacroAuthJwtValidator::new(jwt_args),+ MacroAuthJwtValidator::new(jwt_args.clone()),InternalAuthConfig {api_key: config.internal_api_key.to_string(),default_user_id: None,@@ -133,6 +133,7 @@ async fn main() -> anyhow::Result<()> {let cors = macro_cors::cors_layer();let port = config.port;+ let correlation = agent_correlation::inbound::CorrelationState::new(db.clone(), jwt_args);let app = mount_at_root_and_prefix(contacts_router(ContactsRouterState {contacts_service: service,@@ -147,6 +148,10 @@ async fn main() -> anyhow::Result<()> {SwaggerUi::new("/contacts/docs").url("/contacts/api-doc/openapi.json", ApiDoc::openapi()),);+ let app = app.layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ ));let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await.unwrap();diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.mdindex 59506b6e5b..c4d019a980 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -108,3 +108,5 @@ threads, pins, recents, notifications, folders, activity.- Rules: `.agents/rules/rust/db.md`, `.agents/rules/observability.md`- Negotiate Mail cache profiles through `x-macro-mail-cache-profile` (CORS-enabled HTTP) and `mailCacheProfile` (WebSocket connection init); preserve authenticated connection data and default unknown capabilities to v2.++- The HTTP boundary validates agent correlation; activity consumption restores Kafka envelope attribution before materialization.diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 13fb64c1f4..7b95259310 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -44,6 +44,7 @@ local_auth = ["macro_authorization/local_auth"]location_check = [][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }access_requests = { path = "../../crates/access_requests" }async-trait = { workspace = true }ai_billing = { path = "../../crates/ai_billing" }diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex e8f3d42565..0247c15390 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -51,7 +51,15 @@ pub const MACRO_INTERNAL_USER_ID: &str = "macro|[email protected]";pub(crate) async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {let sync_sessions = state.sync_sessions.clone();+ let correlation = agent_correlation::inbound::CorrelationState::new(+ state.db.clone(),+ state.jwt_validation_args.clone(),+ );let app = api_router(state.clone())+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ )).layer(ServiceBuilder::new().layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())diff --git a/services/document_storage_service/src/service/activity.rs b/services/document_storage_service/src/service/activity.rsindex 0672864da1..c176edf459 100644--- a/services/document_storage_service/src/service/activity.rs+++ b/services/document_storage_service/src/service/activity.rs@@ -54,30 +54,34 @@ pub(crate) async fn ingest(envelope.event.ingest(envelope.event_id)}- match event {- ActivitySourceEvent::DocumentMacroEvent(e) => {- let envelope = e.event();- documents_hex::domain::activity::ingest_with_editing_sessions(- &envelope.event,- envelope.event_id,- editing_activity,- )- .await- }- ActivitySourceEvent::ChannelMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::MessageMacroEvent(e) => {- let envelope = e.event();- channels::domain::activity::ingest_message_event(envelope.event_id, &envelope.event)+ let correlation = event.agent_correlation_id();+ agent_correlation::context::scope(correlation, async {+ match event {+ ActivitySourceEvent::DocumentMacroEvent(e) => {+ let envelope = e.event();+ documents_hex::domain::activity::ingest_with_editing_sessions(+ &envelope.event,+ envelope.event_id,+ editing_activity,+ )+ .await+ }+ ActivitySourceEvent::ChannelMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::MessageMacroEvent(e) => {+ let envelope = e.event();+ channels::domain::activity::ingest_message_event(envelope.event_id, &envelope.event)+ }+ ActivitySourceEvent::ChatMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::ProjectMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::EmailMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::PropertyMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::CallMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::InitiativeMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::DatabaseMacroEvent(e) => arm(e.event()),+ ActivitySourceEvent::FormMacroEvent(event) => arm(event.event()),}- ActivitySourceEvent::ChatMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::ProjectMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::EmailMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::PropertyMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::CallMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::InitiativeMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::DatabaseMacroEvent(e) => arm(e.event()),- ActivitySourceEvent::FormMacroEvent(event) => arm(event.event()),- }+ })+ .await}/// Realtime activity audience: everyone with current access to the entity,diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rsindex 4d421c8fbf..ba546efc31 100644--- a/services/document_storage_service/src/service/entity_mutation.rs+++ b/services/document_storage_service/src/service/entity_mutation.rs@@ -770,14 +770,14 @@ wherelet receipt = self.receipt(actor, requested).await?;let requested = requested.clone();let user_id = actor.user_id.clone();- tokio::spawn(+ tokio::spawn(agent_correlation::context::capture(async move {duplicator.duplicate_entity(requested, receipt, user_id, display_name).await}.in_current_span(),- )+ )).await.map_err(|error| EntityMutationErrorCode::internal(rootcause::report!(error)))?}diff --git a/services/email_service/AGENTS.md b/services/email_service/AGENTS.mdindex 27b6cebf38..1ee65e765d 100644--- a/services/email_service/AGENTS.md+++ b/services/email_service/AGENTS.md@@ -180,3 +180,5 @@ the gateway `/email` prefix.## Related- Rules: `.agents/rules/config-and-service-urls.md` · Skill: `new-service`++- Validate optional agent correlation at the HTTP boundary; delayed Gmail completion restores it from the scheduled-message row.diff --git a/services/email_service/Cargo.toml b/services/email_service/Cargo.tomlindex 48079ebce4..5c71cbf727 100644--- a/services/email_service/Cargo.toml+++ b/services/email_service/Cargo.toml@@ -88,6 +88,7 @@ sfs_map = []sfs_delete = [][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }calendar_events = { path = "../../crates/calendar_events", features = ["google", "inbound", "postgres", "schema"] }ammonia = { workspace = true }anyhow = { workspace = true }diff --git a/services/email_service/src/api.rs b/services/email_service/src/api.rsindex 77ff87e014..7cb65e9a67 100644--- a/services/email_service/src/api.rs+++ b/services/email_service/src/api.rs@@ -29,13 +29,21 @@ const GATEWAY_PATH_PREFIX: &str = "/email";pub(crate) async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {let env = state.config.environment;+ let correlation =+ agent_correlation::inbound::CorrelationState::new(state.db.clone(), state.jwt_args.clone());let port = state.config.port;- let traced_api = api_router(state.clone()).with_state(state).layer(- ServiceBuilder::new()- .layer(TraceLayer::new_for_http())- .layer(macro_cors::cors_layer())- .layer(CompressionLayer::new().gzip(true)),- );+ let traced_api = api_router(state.clone())+ .with_state(state)+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ ))+ .layer(+ ServiceBuilder::new()+ .layer(TraceLayer::new_for_http())+ .layer(macro_cors::cors_layer())+ .layer(CompressionLayer::new().gzip(true)),+ );let health = health::router();let app = mount_at_root_and_prefix(traced_api.merge(health)).merge(swagger_ui());diff --git a/services/email_service/src/outbound/scheduled_delivery.rs b/services/email_service/src/outbound/scheduled_delivery.rsindex fa7f4c4369..ece61dce82 100644--- a/services/email_service/src/outbound/scheduled_delivery.rs+++ b/services/email_service/src/outbound/scheduled_delivery.rs@@ -199,7 +199,10 @@ impl ScheduledDeliveryRepo for ScheduledDeliveryAdapter {if let (Some(message_db_id), Some(thread_db_id)) =(message_to_send.db_id, message_to_send.thread_db_id){- let _ = ctx+ agent_correlation::context::scope(+ scheduled_message.agent_correlation_id,+ async {+ let _ = ctx.macro_event_broker.send_event(&EmailMacroEvent::message_sent(MessageSentMetadata {link_id: link.id,@@ -234,6 +237,9 @@ impl ScheduledDeliveryRepo for ScheduledDeliveryAdapter {.inspect_err(|error| tracing::error!(error=?error, "failed to publish email event"),);+ },+ )+ .await;}// Cleanup attachments in the background after successful senddiff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.mdindex 81bdf47043..b6a336c1fe 100644--- a/services/mcp_auth_proxy/AGENTS.md+++ b/services/mcp_auth_proxy/AGENTS.md@@ -112,3 +112,5 @@ and other library consumers. Both retain OAuth metadata, CORS, and bearer auth.## Related- Skill: `new-service` (for how this is wired as a dependency, not a deploy)++- Only verified Macro JWT session provenance becomes `ManagedAgentSession`; external MCP callers remain uncorrelated.diff --git a/services/mcp_auth_proxy/src/inbound/middleware.rs b/services/mcp_auth_proxy/src/inbound/middleware.rsindex f07064b90a..2010b61b5f 100644--- a/services/mcp_auth_proxy/src/inbound/middleware.rs+++ b/services/mcp_auth_proxy/src/inbound/middleware.rs@@ -21,6 +21,10 @@ use macro_user_id::user_id::MacroUserIdStr;#[derive(Clone)]pub struct JwtAccessToken(pub String);+/// Managed session provenance from a verified Macro API JWT.+#[derive(Clone, Copy)]+pub struct ManagedAgentSession(pub uuid::Uuid);+/// What the bearer middleware validates a request with.#[derive(Clone)]pub struct BearerAuth {@@ -144,6 +148,14 @@ pub async fn validate_bearer(}};+ if let JwtToken::MacroApiToken(api) = &jwt_token+ && api.agent_id.is_some()+ && let Some(session) = api.agent_session_id+ {+ request+ .extensions_mut()+ .insert(ManagedAgentSession(session));+ }let (user_id, auth_method, caller) = match jwt_token {JwtToken::MacroAccessToken(access) => {let name = match auth.clients.client_name(&token).await {diff --git a/services/notification_service/AGENTS.md b/services/notification_service/AGENTS.mdindex b0068c10b3..89508726c7 100644--- a/services/notification_service/AGENTS.md+++ b/services/notification_service/AGENTS.md@@ -53,3 +53,5 @@ worker that sends email/mobile-push/websocket notifications.## Related- Skill: `new-service`++- The HTTP boundary validates optional signed agent correlation without changing existing authorization.diff --git a/services/notification_service/Cargo.toml b/services/notification_service/Cargo.tomlindex fa56c3a0ce..040b2268c8 100644--- a/services/notification_service/Cargo.toml+++ b/services/notification_service/Cargo.toml@@ -23,6 +23,7 @@ local_queue = []push_notification_event_handler = [][dependencies]+agent_correlation = { path = "../../crates/agent_correlation", features = ["http", "postgres"] }anyhow = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sesv2 = { workspace = true }diff --git a/services/notification_service/src/api.rs b/services/notification_service/src/api.rsindex 6e84f84eac..81a1b0a2de 100644--- a/services/notification_service/src/api.rs+++ b/services/notification_service/src/api.rs@@ -25,9 +25,14 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationReaingress_state: NotificationRouterState<S, AuthorizationService>,) -> anyhow::Result<()> {let port = state.config.port;+ let correlation = state.correlation.clone();let env = state.config.environment;let app = api_router(state.clone(), ingress_state).with_state(state)+ .layer(axum::middleware::from_fn_with_state(+ correlation,+ agent_correlation::inbound::propagate,+ )).merge(health::router()).layer(ServiceBuilder::new()diff --git a/services/notification_service/src/api/context.rs b/services/notification_service/src/api/context.rsindex 5698aa234e..8cc5170401 100644--- a/services/notification_service/src/api/context.rs+++ b/services/notification_service/src/api/context.rs@@ -15,6 +15,8 @@ pub(crate) type ItemPreferences =#[derive(Clone, FromRef)]pub struct ApiContext {+ /// Signed invocation validation and propagation.+ pub correlation: agent_correlation::inbound::CorrelationState,pub item_preferences: ItemPreferences,pub db: PgPool,pub sns_client: Arc<sns_client::SNS>,diff --git a/services/notification_service/src/main.rs b/services/notification_service/src/main.rsindex 9556a9059e..bd34a16bfc 100644--- a/services/notification_service/src/main.rs+++ b/services/notification_service/src/main.rs@@ -139,7 +139,7 @@ pub async fn main() -> anyhow::Result<()> {JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client).await?;let authorization_state = MacroAuthorizationState::new(Arc::new(AuthorizationService::new(- MacroAuthJwtValidator::new(jwt_args),+ MacroAuthJwtValidator::new(jwt_args.clone()),InternalAuthConfig {api_key: config.internal_api_key.as_ref().to_string(),default_user_id: None,@@ -354,6 +354,7 @@ pub async fn main() -> anyhow::Result<()> {api::setup_and_serve(ApiContext {+ correlation: agent_correlation::inbound::CorrelationState::new(db.clone(), jwt_args),item_preferences: ::notification::domain::item_preferences::ItemNotificationPreferenceService::new(::notification::outbound::item_preferences::PgItemNotificationPreferenceRepository(db.clone()),),diff --git a/services/sync-service/AGENTS.md b/services/sync-service/AGENTS.mdindex 75c4a0b440..75825632ae 100644--- a/services/sync-service/AGENTS.md+++ b/services/sync-service/AGENTS.md@@ -102,3 +102,5 @@ to the requested surface. These are scoped sync JWTs, not app-session tokens.connection. To regress connect-before-initialize, build without`create-default-state` and run `SYNC_TEST_UNINITIALIZED_ROOMS=true npx vitest runtests/canvas_initialization.test.ts`; the usual test build seeds automatically.++- Preserve signed document-grant agent correlation in editor metadata and pending batches; different invocations remain distinct editors.diff --git a/services/sync-service/README.md b/services/sync-service/README.mdindex fd2f6be601..9861571c1d 100644--- a/services/sync-service/README.md+++ b/services/sync-service/README.md@@ -33,6 +33,10 @@ When a client updates a document via a WebSocket message, we apply the update toUnfortunately, query params are the best way to authenticate a websocket connection. Since we use tls, query params should be encrypted in transit.the `sync-service` will verify the jwt and ensure that the user has the correct permissions to access the document.+Document grants may also carry signed `agent_correlation_id` attribution. The+worker preserves it through editor metadata and pending activity batches so+separate code-mode invocations remain distinct, without changing permissions.+HTTP routes use Axum `FromRequestParts` extractors to authenticate before thehandler runs. Document view/edit/admin routes declare their minimum grant;atomic state/update routes require an exact signed document grant, and internaldiff --git a/services/sync-service/src/domain/document.rs b/services/sync-service/src/domain/document.rsindex e10f6c1116..b307b76f7c 100644--- a/services/sync-service/src/domain/document.rs+++ b/services/sync-service/src/domain/document.rs@@ -65,6 +65,8 @@ pub struct PreparedUpdate {/// Signed-token attribution stored alongside the existing operation log.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]pub struct DocumentAttribution {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<uuid::Uuid>,pub actor: String,pub on_behalf_of: Option<String>,}@@ -75,9 +77,12 @@ impl DocumentAttribution {pub fn from_session_claims(actor: Option<String>,user_id: Option<String>,+ agent_correlation_id: Option<uuid::Uuid>,) -> Result<Option<Self>, DocumentError> {match (actor, user_id) {- (Some(actor), user_id) => Self::from_signed_claims(actor, user_id).map(Some),+ (Some(actor), user_id) => {+ Self::from_signed_claims(actor, user_id, agent_correlation_id).map(Some)+ }(None, Some(user_id)) => {// Human identities retain the user-claim bound; long valid// email addresses can exceed the explicit agent-actor bound.@@ -85,6 +90,7 @@ impl DocumentAttribution {return Err(DocumentError::Invalid("Invalid signed attribution."));}Ok(Some(Self {+ agent_correlation_id,actor: user_id,on_behalf_of: None,}))@@ -96,11 +102,13 @@ impl DocumentAttribution {pub fn from_signed_claims(actor: String,on_behalf_of: Option<String>,+ agent_correlation_id: Option<uuid::Uuid>,) -> Result<Self, DocumentError> {if actor.len() > 256 || on_behalf_of.as_ref().is_some_and(|user| user.len() > 1024) {return Err(DocumentError::Invalid("Invalid signed attribution."));}Ok(Self {+ agent_correlation_id,actor,on_behalf_of,})diff --git a/services/sync-service/src/domain/document/test.rs b/services/sync-service/src/domain/document/test.rsindex 0c73cd685d..27074c2ad6 100644--- a/services/sync-service/src/domain/document/test.rs+++ b/services/sync-service/src/domain/document/test.rs@@ -284,7 +284,7 @@ fn session_attribution_uses_the_verified_human_or_agent_identity() {);assert_eq!(long_user.len(), 260);assert_eq!(- DocumentAttribution::from_session_claims(None, Some(long_user.clone()))+ DocumentAttribution::from_session_claims(None, Some(long_user.clone()), None).unwrap().unwrap().actor,@@ -293,25 +293,31 @@ fn session_attribution_uses_the_verified_human_or_agent_identity() {let user = "macro|[email protected]".to_string();assert_eq!(- DocumentAttribution::from_session_claims(None, Some(user.clone())).unwrap(),+ DocumentAttribution::from_session_claims(None, Some(user.clone()), None).unwrap(),Some(DocumentAttribution {+ agent_correlation_id: None,actor: user.clone(),on_behalf_of: None}));assert_eq!(- DocumentAttribution::from_session_claims(Some("bot|agent".into()), Some(user.clone()))- .unwrap(),+ DocumentAttribution::from_session_claims(+ Some("bot|agent".into()),+ Some(user.clone()),+ None+ )+ .unwrap(),Some(DocumentAttribution {+ agent_correlation_id: None,actor: "bot|agent".into(),on_behalf_of: Some(user)}));assert_eq!(- DocumentAttribution::from_session_claims(None, None).unwrap(),+ DocumentAttribution::from_session_claims(None, None, None).unwrap(),None);- assert!(DocumentAttribution::from_session_claims(None, Some("x".repeat(1025))).is_err());+ assert!(DocumentAttribution::from_session_claims(None, Some("x".repeat(1025)), None).is_err());}#[test]@@ -339,3 +345,29 @@ fn writing_peers_are_the_peers_with_operations_in_the_blob() {assert!(writing_peers(b"not a loro blob").is_err());}++#[test]+fn persisted_editor_metadata_distinguishes_invocations_by_the_same_actor() {+ let first = uuid::Uuid::from_u128(1);+ let second = uuid::Uuid::from_u128(2);+ let one = DocumentAttribution::from_session_claims(+ Some("bot|agent".into()),+ Some("macro|[email protected]".into()),+ Some(first),+ )+ .unwrap()+ .unwrap();+ let two = DocumentAttribution::from_session_claims(+ Some("bot|agent".into()),+ Some("macro|[email protected]".into()),+ Some(second),+ )+ .unwrap()+ .unwrap();+ let editors = std::collections::BTreeSet::from([one.clone(), two, one.clone()]);+ assert_eq!(editors.len(), 2);+ assert_eq!(+ serde_json::to_value(one).unwrap()["agent_correlation_id"],+ first.to_string()+ );+}diff --git a/services/sync-service/src/domain/permissions.rs b/services/sync-service/src/domain/permissions.rsindex 7e27347996..73ab7270cd 100644--- a/services/sync-service/src/domain/permissions.rs+++ b/services/sync-service/src/domain/permissions.rs@@ -26,6 +26,7 @@ pub enum WriteAccess {/// Verified grant normalized at the dedicated session access boundary.#[derive(Debug)]pub struct AuthToken {+ pub agent_correlation_id: Option<uuid::Uuid>,pub user_id: Option<String>,pub(crate) document_id: String,pub access_level: AccessLevel,diff --git a/services/sync-service/src/domain/permissions/test.rs b/services/sync-service/src/domain/permissions/test.rsindex 254477e761..ed176ef938 100644--- a/services/sync-service/src/domain/permissions/test.rs+++ b/services/sync-service/src/domain/permissions/test.rs@@ -3,6 +3,7 @@ use super::*;#[test]fn document_grants_enforce_scope_and_minimum_permission() {let token = AuthToken {+ agent_correlation_id: None,user_id: None,document_id: "document-a".into(),access_level: AccessLevel::View,@@ -33,6 +34,7 @@ fn document_grants_enforce_scope_and_minimum_permission() {#[test]fn admin_grants_cannot_cross_document_scope_on_atomic_operations() {let token = AuthToken {+ agent_correlation_id: None,user_id: None,document_id: "document-a".into(),access_level: AccessLevel::Admin,diff --git a/services/sync-service/src/inbound/credentials.rs b/services/sync-service/src/inbound/credentials.rsindex df32326ccb..60eb423950 100644--- a/services/sync-service/src/inbound/credentials.rs+++ b/services/sync-service/src/inbound/credentials.rs@@ -9,6 +9,7 @@ use crate::error::ResultExt;#[derive(Deserialize)]struct DocumentClaims {+ agent_correlation_id: Option<uuid::Uuid>,user_id: Option<String>,document_id: String,access_level: AccessLevel,@@ -33,6 +34,7 @@ pub(crate) fn decode_document_token(token: &str, secret: &str) -> worker::Resultreturn Err(Error::from("surface grant cannot authorize a document"));}Ok(AuthToken {+ agent_correlation_id: claims.agent_correlation_id,user_id: claims.user_id,document_id: claims.document_id,access_level: claims.access_level,@@ -58,6 +60,7 @@ pub(crate) fn decode_surface_token(SurfaceAccessLevel::Owner => AccessLevel::Owner,};Ok(AuthToken {+ agent_correlation_id: None,user_id: claims.user_id,document_id: identity.storage_key(),access_level,diff --git a/services/sync-service/src/inbound/durable_object.rs b/services/sync-service/src/inbound/durable_object.rsindex c68220565b..b431c467ad 100644--- a/services/sync-service/src/inbound/durable_object.rs+++ b/services/sync-service/src/inbound/durable_object.rs@@ -84,6 +84,8 @@ macro_rules! maybe_404 {#[derive(Debug, Serialize, Deserialize, Clone)]pub struct WebSocketMetadata {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_correlation_id: Option<uuid::Uuid>,pub user_id: Option<String>,pub access_level: AccessLevel,#[serde(default, skip_serializing_if = "Option::is_none")]@@ -188,8 +190,12 @@ impl<'a> Wsm<'a> {let ws_id = self.get_ws_id()?.to_string();let map = self.dss.ws_meta_map.lock("Wsm::edit_attribution");let meta = map.get(&ws_id).context("missing ws metadata")?;- DocumentAttribution::from_session_claims(meta.actor.clone(), meta.user_id.clone())- .context("invalid signed websocket attribution")+ DocumentAttribution::from_session_claims(+ meta.actor.clone(),+ meta.user_id.clone(),+ meta.agent_correlation_id,+ )+ .context("invalid signed websocket attribution")}pub async fn write_access(&mut self) -> Result<WriteAccess> {@@ -635,6 +641,7 @@ impl SyncSession {.accept_websocket_with_tags(&pair.server, &[&ws_id]);let ws_meta = WebSocketMetadata {+ agent_correlation_id: claims.agent_correlation_id,user_id: claims.user_id,access_level: claims.access_level,actor: claims.actor,diff --git a/services/sync-service/src/inbound/durable_object/document_api.rs b/services/sync-service/src/inbound/durable_object/document_api.rsindex d4508e7220..ea43345825 100644--- a/services/sync-service/src/inbound/durable_object/document_api.rs+++ b/services/sync-service/src/inbound/durable_object/document_api.rs@@ -134,6 +134,7 @@ impl SyncSession {let editor = match document::DocumentAttribution::from_session_claims(claims.actor,claims.user_id,+ claims.agent_correlation_id,) {Ok(editor) => editor,Err(error) => return error_response(error),diff --git a/services/sync-service/src/inbound/durable_object/peer_ids/test.rs b/services/sync-service/src/inbound/durable_object/peer_ids/test.rsindex 29aa1fffa7..678272473e 100644--- a/services/sync-service/src/inbound/durable_object/peer_ids/test.rs+++ b/services/sync-service/src/inbound/durable_object/peer_ids/test.rs@@ -6,6 +6,7 @@ use std::collections::BTreeSet;#[test]fn signed_actor_filters_random_agent_ids_and_preserves_legacy_ai_filter() {let mut metadata = WebSocketMetadata {+ agent_correlation_id: None,user_id: Some("user".into()),access_level: AccessLevel::Edit,actor: Some("bot|agent".into()),diff --git a/services/sync-service/src/inbound/durable_object/surface_api/test.rs b/services/sync-service/src/inbound/durable_object/surface_api/test.rsindex 89dc423f37..0f3647352b 100644--- a/services/sync-service/src/inbound/durable_object/surface_api/test.rs+++ b/services/sync-service/src/inbound/durable_object/surface_api/test.rs@@ -78,6 +78,7 @@ fn failed_rollback_never_overwrites_the_unidentified_snapshot() {#[test]fn hibernated_surface_metadata_retains_kind_and_strict_expiry() {let meta = WebSocketMetadata {+ agent_correlation_id: None,user_id: Some("user".into()),access_level: AccessLevel::Edit,actor: Some("actor".into()),@@ -104,6 +105,7 @@ fn legacy_metadata_is_only_valid_for_documents() {assert!(legacy.grant_active(SessionKind::Document, usize::MAX));assert!(!legacy.grant_active(SessionKind::Surface, 0));let missing_expiry = WebSocketMetadata {+ agent_correlation_id: None,session_kind: SessionKind::Surface,..legacy};diff --git a/services/sync-service/tests/document_atomic.test.ts b/services/sync-service/tests/document_atomic.test.tsindex 72a41c16bb..ded72b3cb0 100644--- a/services/sync-service/tests/document_atomic.test.ts+++ b/services/sync-service/tests/document_atomic.test.ts@@ -101,21 +101,34 @@ describe("atomic document API", () => {const initial = await snapshot(id);expect((await post(id, edit(initial, "A1", "Current"))).status).toBe(200);const full = await snapshot(id);- const response = await mf.dispatchFetch(`${url(id, "snapshot")}?shallow=true`, {- headers: auth(id, "view"),- });+ const response = await mf.dispatchFetch(+ `${url(id, "snapshot")}?shallow=true`,+ {+ headers: auth(id, "view"),+ },+ );expect(response.status).toBe(200);- const body = (await response.json()) as { snapshot: string; revision: string };+ const body = (await response.json()) as {+ snapshot: string;+ revision: string;+ };const compact = new LoroDoc();compact.import(Buffer.from(body.snapshot, "base64"));expect(compact.isShallow()).toBe(true);expect(compact.toJSON()).toEqual(full.doc.toJSON());expect(body.revision).toBe(full.revision);- const change = edit({ ...body, doc: compact }, "B1", "Edited from compact state");+ const change = edit(+ { ...body, doc: compact },+ "B1",+ "Edited from compact state",+ );expect((await post(id, change)).status).toBe(200);const saved = await snapshot(id);- expect(saved.doc.getMap("properties").get("B1")).toBe("Edited from compact state");- for (const document of [initial.doc, full.doc, compact, saved.doc]) document.free();+ expect(saved.doc.getMap("properties").get("B1")).toBe(+ "Edited from compact state",+ );+ for (const document of [initial.doc, full.doc, compact, saved.doc])+ document.free();});it("returns a coherent authorized snapshot and rejects viewers, wrong-document grants, missing and invalid tokens", async () => {const id = await seed();@@ -274,35 +287,42 @@ describe("atomic document API", () => {expect((await snapshot(id)).doc.toJSON()).toEqual(source.doc.toJSON());});- it("stores signed actor metadata with the oplog and ignores body attribution", async () => {- const id = await seed();- const request = edit(await snapshot(id));- expect((await post(id, { ...request, actor: "forged" })).status).toBe(400);- const token = jwt.sign(- {- document_id: id,- user_id: "macro|real-user",- access_level: "edit",+ it.each([undefined, "00000000-0000-0000-0000-000000000001"])(+ "stores signed actor metadata and correlation %s with the oplog and ignores body attribution",+ async (correlation) => {+ const id = await seed();+ const request = edit(await snapshot(id));+ expect((await post(id, { ...request, actor: "forged" })).status).toBe(+ 400,+ );+ const token = jwt.sign(+ {+ document_id: id,+ user_id: "macro|real-user",+ access_level: "edit",+ actor: "bot|document-agent",+ agent_correlation_id: correlation,+ exp: Math.floor(Date.now() / 1000) + 60,+ },+ "local",+ );+ expect(+ (await post(id, request, { Authorization: `Bearer ${token}` })).status,+ ).toBe(200);+ const response = await mf.dispatchFetch(+ `http://localhost/document/${id}/debug_do_kv_list/actor`,+ { headers: { "x-internal-auth-key": "local" } },+ );+ expect(response.status).toBe(200);+ const records = (await response.json()) as [string, number[]][];+ expect(records).toHaveLength(1);+ expect(JSON.parse(Buffer.from(records[0][1]).toString())).toEqual({actor: "bot|document-agent",- exp: Math.floor(Date.now() / 1000) + 60,- },- "local",- );- expect(- (await post(id, request, { Authorization: `Bearer ${token}` })).status,- ).toBe(200);- const response = await mf.dispatchFetch(- `http://localhost/document/${id}/debug_do_kv_list/actor`,- { headers: { "x-internal-auth-key": "local" } },- );- expect(response.status).toBe(200);- const records = (await response.json()) as [string, number[]][];- expect(records).toHaveLength(1);- expect(JSON.parse(Buffer.from(records[0][1]).toString())).toEqual({- actor: "bot|document-agent",- on_behalf_of: "macro|real-user",- });- });+ on_behalf_of: "macro|real-user",+ ...(correlation ? { agent_correlation_id: correlation } : {}),+ });+ },+ );it("persists a bounded delta larger than a single small KV value", async () => {const id = await seed();