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(activity): attribute AI tool creates and edits to the tool actor (Macro AI) (#6050)
teo6bd5217591ca
diff --git a/Cargo.lock b/Cargo.lockindex ced8affb89..f0bdab2f4d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12621,6 +12621,7 @@ dependencies = ["axum","axum-extra","base64 0.22.1",+ "bot_id","chrono","document_sub_type","documents",@@ -12687,6 +12688,7 @@ dependencies = ["anyhow","async-trait","axum",+ "bot_id","chrono","document_sub_type","entity_access",diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 3444009408..dcabeb7d37 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -18345,6 +18345,10 @@"description": "Metadata for [`DocumentTopicEvent::Deleted`].","required": ["document_id"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically deleted the document. Absent on events published\nbefore attribution, and on user-receipt writes (ingest then uses\n[`Self::actor_user_id`])."+ },"actor_user_id": {"oneOf": [{@@ -18360,6 +18364,17 @@"type": "string","description": "The id of the deleted document."},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this delete belongs on, when different from\n[`Self::actor`]."+ }+ ]+ },"project_id": {"type": ["string", "null"],"description": "Project the document belonged to, when any."@@ -19075,6 +19090,10 @@"description": "Metadata for [`DocumentTopicEvent::Updated`].","required": ["document_id", "owner", "share_permission_updated"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically updated the document. Absent on events published\nbefore attribution, and on user-receipt writes (ingest then uses\n[`Self::actor_user_id`])."+ },"actor_user_id": {"oneOf": [{@@ -19105,6 +19124,17 @@}]},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this update belongs on, when different from\n[`Self::actor`]."+ }+ ]+ },"owner": {"$ref": "#/components/schemas/MacroUserIdStr","description": "The owner of the document."diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 5209490aac..398fa4c959 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -793,6 +793,7 @@ pub fn build_properties_tool_context(PropertiesToolContext {service: properties,entity_access_service,+ actor: bot_id::MACRO_AI_BOT_ID,}}@@ -1305,6 +1306,19 @@ pub struct ToolServiceContext {pub usage_context: ai_usage::UsageContext,}+impl ToolServiceContext {+ /// Run the mutating tools as `actor`, delegated for the requesting user,+ /// instead of the default Macro AI bot. Hosts running a specific agent+ /// call this once when they build the context for that agent's session.+ pub fn with_actor(mut self, actor: bot_id::BotId) -> Self {+ self.document_tool_context = self.document_tool_context.with_actor(actor);+ self.properties_tool_context = self.properties_tool_context.with_actor(actor);+ self.project_tool_context = self.project_tool_context.with_actor(actor);+ self.channel_tool_context = self.channel_tool_context.with_actor(actor);+ self+ }+}+impl FromRef<ToolServiceContext> for ai_toolset::NoContext {fn from_ref(_ctx: &ToolServiceContext) -> Self {ai_toolset::NoContext()diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.tomlindex d5be4adb6d..d030c8662d 100644--- a/crates/channels/Cargo.toml+++ b/crates/channels/Cargo.toml@@ -137,6 +137,7 @@ schemars = { workspace = true, optional = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+bot_id = { path = "../bot_id", features = ["test-utils"] }http-body-util = { workspace = true }kafka_util = { path = "../kafka_util" }macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rsindex 55dde583ed..1016d5a730 100644--- a/crates/channels/src/inbound/toolset.rs+++ b/crates/channels/src/inbound/toolset.rs@@ -20,6 +20,7 @@ use crate::{},};use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};+use bot_id::BotId;use entity_access::domain::{models::{AccessError, AccessLevel, AdminParticipantRole, EntityAccessReceipt, EntityType,@@ -47,6 +48,9 @@ wherepub service: Arc<Svc>,/// Entity access service used to ensure the caller is a channel member.pub entity_access_service: Arc<AccessSvc>,+ /// The bot these tools act as, on behalf of the requesting user. Defaults+ /// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].+ pub actor: BotId,}impl<Svc, AccessSvc> Clone for ChannelToolContext<Svc, AccessSvc>@@ -58,6 +62,7 @@ whereSelf {service: self.service.clone(),entity_access_service: self.entity_access_service.clone(),+ actor: self.actor,}}}@@ -72,9 +77,16 @@ whereSelf {service: Arc::new(service),entity_access_service: Arc::new(entity_access_service),+ actor: bot_id::MACRO_AI_BOT_ID,}}+ /// Set the bot these tools act as.+ pub fn with_actor(mut self, actor: BotId) -> Self {+ self.actor = actor;+ self+ }+/// Require that the request user is an active member of the channel before reading it.pub async fn require_channel_member(&self,diff --git a/crates/channels/src/inbound/toolset/send_channel_message.rs b/crates/channels/src/inbound/toolset/send_channel_message.rsindex b0a9c6f3b0..b13949a45e 100644--- a/crates/channels/src/inbound/toolset/send_channel_message.rs+++ b/crates/channels/src/inbound/toolset/send_channel_message.rs@@ -57,9 +57,9 @@ where.require_channel_member(&request_context, self.channel_id).await?;- // AI sends as the Macro agent bot; the triggering user is recorded+ // AI sends as the tool actor bot; the triggering user is recorded// separately so the client can render a "from <user>" pill.- let actor = Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID);+ let actor = Sender::new_from_bot(service_context.actor);let triggered_by = Some(request_context.user_id.as_ref().to_string());let req = PostMessageRequest {diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rsindex 47f4bc2bc6..002b597989 100644--- a/crates/channels/src/inbound/toolset/test.rs+++ b/crates/channels/src/inbound/toolset/test.rs@@ -5,17 +5,20 @@ use super::{manage_channel_participants::{ManageChannelParticipants, ParticipantAction},parse_participants,rename_channel::RenameChannel,+ send_channel_message::SendChannelMessage,};use crate::domain::{models::{AddParticipantsRequest, ChannelMetadata, ChannelType, CreateChannelRequest,- CreateChannelResponse, PatchChannelRequest, RemoveParticipantsRequest, Sender,+ CreateChannelResponse, PatchChannelRequest, PostMessageRequest, PostMessageResponse,+ RemoveParticipantsRequest, Sender,},ports::{ChannelMutationErr, ChannelService},};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, schema::generate_validated_input_schema,};+use bot_id::BotId;use entity_access::domain::{models::{AccessError, AccessLevel, BotAccessScope, CallChannelInfo, EntityAccessReceipt,@@ -40,6 +43,7 @@ type CreatedChannelCall = (Sender, Option<i64>, CreateChannelRequest);type PatchChannelCall = (Sender, Uuid, PatchChannelRequest);type AddParticipantsCall = (Sender, Uuid, AddParticipantsRequest);type RemoveParticipantsCall = (Sender, Uuid, RemoveParticipantsRequest);+type PostMessageCall = (Sender, Uuid, PostMessageRequest);#[derive(Clone, Default)]struct ToolTestChannelService {@@ -50,6 +54,7 @@ struct ToolTestChannelService {patch_error: Option<String>,adds: Arc<Mutex<Vec<AddParticipantsCall>>>,removes: Arc<Mutex<Vec<RemoveParticipantsCall>>>,+ posts: Arc<Mutex<Vec<PostMessageCall>>>,metadata_name: Option<String>,}@@ -170,6 +175,22 @@ impl ChannelService for ToolTestChannelService {Ok(())}+ async fn post_message(+ &self,+ actor: Sender,+ channel_id: Uuid,+ req: PostMessageRequest,+ ) -> Result<PostMessageResponse, ChannelMutationErr> {+ self.posts+ .lock()+ .expect("post lock")+ .push((actor, channel_id, req));+ Ok(PostMessageResponse {+ id: Uuid::new_v4().to_string(),+ nonce: None,+ })+ }+async fn add_participants(&self,actor: Sender,@@ -266,9 +287,13 @@ impl EntityAccessService for ToolTestAccessService {_user_id: Option<&MacroUserId<Lowercase<'_>>>,_entity_id: &str,_entity_type: EntityType,- _required_level: AccessLevel,+ required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::internal("test access failure"))+ match self.receipt_error {+ Some(ReceiptFail::Unauthorized) => Err(AccessError::Unauthorized),+ Some(ReceiptFail::NotFound) => Err(AccessError::NotFound("missing")),+ None => Ok(required_level),+ }}async fn check_public_access(@@ -659,6 +684,52 @@ async fn rename_channel_surfaces_dm_rename_rejection() {);}+#[tokio::test]+async fn send_channel_message_posts_as_the_context_actor_for_the_user() {+ let channel_id = Uuid::new_v4();+ let service = ToolTestChannelService::default();+ let posts = service.posts.clone();++ let tool = SendChannelMessage {+ content: "hello".to_string(),+ channel_id,+ thread_id: None,+ };++ tool.call(+ ServiceContext(ChannelToolContext::new(+ service.clone(),+ ToolTestAccessService::default(),+ )),+ RequestContext::new(user_id()),+ )+ .await+ .expect("member can post");+ tool.call(+ ServiceContext(+ ChannelToolContext::new(service, ToolTestAccessService::default())+ .with_actor(BotId::TEST_A),+ ),+ RequestContext::new(user_id()),+ )+ .await+ .expect("member can post");++ let posts = posts.lock().expect("post lock");+ let [(default_actor, _, default_req), (custom_actor, _, _)] = posts.as_slice() else {+ panic!("expected two posts, got {}", posts.len());+ };+ assert_eq!(+ default_actor.as_bot().map(|id| id.bot_id()),+ Some(bot_id::MACRO_AI_BOT_ID)+ );+ assert_eq!(default_req.triggered_by.as_deref(), Some(TEST_USER_ID));+ assert_eq!(+ custom_actor.as_bot().map(|id| id.bot_id()),+ Some(BotId::TEST_A)+ );+}+#[tokio::test]async fn manage_participants_adds_canonical_ids() {let channel_id = Uuid::new_v4();diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.tomlindex 95a700cbb8..9e0243ca14 100644--- a/crates/documents/Cargo.toml+++ b/crates/documents/Cargo.toml@@ -161,6 +161,7 @@ non_empty = { path = "../non_empty" }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+bot_id = { path = "../bot_id", features = ["test-utils"] }dotenvy = { workspace = true }embedding = { path = "../embedding" }http-body-util = { workspace = true }diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rsindex 3c49321e88..089522be00 100644--- a/crates/documents/src/domain/activity.rs+++ b/crates/documents/src/domain/activity.rs@@ -13,6 +13,21 @@ use chrono::{DateTime, Utc};use uuid::Uuid;use super::events::DocumentTopicEvent;+use macro_user_id::user_id::MacroUserIdStr;++/// Attribution for `updated` / `deleted` events. Bot receipts publish `actor`;+/// user receipts (and events from before attribution) only `actor_user_id`.+/// `None` when neither is set, e.g. internal callers.+fn mutation_attribution(+ actor: &Option<Actor<'static>>,+ actor_user_id: &Option<MacroUserIdStr<'static>>,+ on_behalf_of: &Option<MacroUserIdStr<'static>>,+) -> Option<Attribution> {+ let actor = actor+ .clone()+ .or_else(|| actor_user_id.clone().map(Actor::new_from_user))?;+ Some(Attribution::new(actor, on_behalf_of.clone()))+}impl ActivitySource for DocumentTopicEvent {/// Maps one `macro.documents` event to its ingest outcome.@@ -48,24 +63,36 @@ impl ActivitySource for DocumentTopicEvent {metadata.created_at.unwrap_or_else(|| event_time(event_id)),)}- DocumentTopicEvent::Updated(metadata) => match &metadata.actor_user_id {- Some(actor) => single(- Attribution::direct(Actor::new_from_user(actor.clone())),- CommonAction::Edited,- &metadata.document_id,- event_time(event_id),- ),- None => Ingest::Ignore,- },- DocumentTopicEvent::Deleted(metadata) => match &metadata.actor_user_id {- Some(actor) => single(- Attribution::direct(Actor::new_from_user(actor.clone())),- CommonAction::Deleted,- &metadata.document_id,- event_time(event_id),- ),- None => Ingest::Ignore,- },+ DocumentTopicEvent::Updated(metadata) => {+ match mutation_attribution(+ &metadata.actor,+ &metadata.actor_user_id,+ &metadata.on_behalf_of,+ ) {+ Some(attribution) => single(+ attribution,+ CommonAction::Edited,+ &metadata.document_id,+ event_time(event_id),+ ),+ None => Ingest::Ignore,+ }+ }+ DocumentTopicEvent::Deleted(metadata) => {+ match mutation_attribution(+ &metadata.actor,+ &metadata.actor_user_id,+ &metadata.on_behalf_of,+ ) {+ Some(attribution) => single(+ attribution,+ CommonAction::Deleted,+ &metadata.document_id,+ event_time(event_id),+ ),+ None => Ingest::Ignore,+ }+ }// The copy is a new document; its creation is the activity.DocumentTopicEvent::Copied(metadata) => single(Attribution::direct(Actor::new_from_user(metadata.owner.clone())),diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rsindex 53a9f4caf2..38902e965f 100644--- a/crates/documents/src/domain/activity/test.rs+++ b/crates/documents/src/domain/activity/test.rs@@ -113,6 +113,8 @@ fn attributed_update_and_delete_map_to_activities() {document_id: DOCUMENT_ID.to_string(),owner: user("macro|[email protected]"),actor_user_id: Some(user("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,document_name: Some("renamed".to_string()),previous_project_id: None,project_id: None,@@ -126,18 +128,45 @@ fn attributed_update_and_delete_map_to_activities() {let deleted = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,project_id: None,}));let activity = single_activity(deleted.event.ingest(deleted.event_id));assert_eq!(activity.action, Action::Deleted);}+#[test]+fn delegated_update_stays_on_the_user_feed() {+ let updated = envelope(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {+ document_id: DOCUMENT_ID.to_string(),+ owner: user("macro|[email protected]"),+ actor_user_id: None,+ actor: Some(Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID)),+ on_behalf_of: Some(user("macro|[email protected]")),+ document_name: Some("renamed".to_string()),+ previous_project_id: None,+ project_id: None,+ file_type: None,+ share_permission_updated: false,+ }));+ let activity = single_activity(updated.event.ingest(updated.event_id));+ assert_eq!(activity.action, Action::Edited);+ assert_eq!(+ activity.actor.as_ref(),+ bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()+ );+ assert_eq!(activity.subject_id, "macro|[email protected]");+}+#[test]fn unattributable_mutations_are_dropped() {let updated = envelope(DocumentTopicEvent::Updated(DocumentUpdatedMetadata {document_id: DOCUMENT_ID.to_string(),owner: user("macro|[email protected]"),actor_user_id: None,+ actor: None,+ on_behalf_of: None,document_name: None,previous_project_id: None,project_id: None,@@ -149,6 +178,8 @@ fn unattributable_mutations_are_dropped() {let deleted = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,project_id: None,}));assert_eq!(deleted.event.ingest(deleted.event_id), Ingest::Ignore);@@ -234,6 +265,8 @@ fn replaying_an_event_derives_identical_activity_ids() {let event = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,project_id: None,}));diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rsindex e9e8cb06bf..17b985c169 100644--- a/crates/documents/src/domain/events.rs+++ b/crates/documents/src/domain/events.rs@@ -58,6 +58,16 @@ pub struct DocumentUpdatedMetadata {/// The authenticated user who performed the update; `None` for/// unauthenticated or internal callers.pub actor_user_id: Option<MacroUserIdStr<'static>>,+ /// Who mechanically updated the document. Absent on events published+ /// before attribution, and on user-receipt writes (ingest then uses+ /// [`Self::actor_user_id`]).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[cfg_attr(feature = "schema", schema(value_type = Option<String>))]+ pub actor: Option<Actor<'static>>,+ /// The user whose feed this update belongs on, when different from+ /// [`Self::actor`].+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,/// New (cleaned) document name; `None` when unchanged.pub document_name: Option<String>,/// Project id before the update.@@ -80,6 +90,16 @@ pub struct DocumentDeletedMetadata {/// The authenticated user who deleted the document; `None` for/// unauthenticated or internal callers.pub actor_user_id: Option<MacroUserIdStr<'static>>,+ /// Who mechanically deleted the document. Absent on events published+ /// before attribution, and on user-receipt writes (ingest then uses+ /// [`Self::actor_user_id`]).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[cfg_attr(feature = "schema", schema(value_type = Option<String>))]+ pub actor: Option<Actor<'static>>,+ /// The user whose feed this delete belongs on, when different from+ /// [`Self::actor`].+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,/// Project the document belonged to, when any.pub project_id: Option<String>,}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex 92e440a2db..44a6a75ea3 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -15,15 +15,15 @@ use std::str::FromStr;use std::time::{SystemTime, UNIX_EPOCH};use unicode_segmentation::UnicodeSegmentation;-use activity::Attribution;+use activity::{Actor, Attribution};use anyhow::anyhow;use cloudfront_sign::{SignedOptions, get_signed_url};use connection::domain::models::{InvalidationEvent, InvalidationReason};use connection::domain::ports::ConnectionService;use document_sub_type::DocumentSubType;use entity_access::domain::models::{- EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, MemberTeamRole, OwnerAccessLevel,- ViewAccessLevel,+ BotReceiptScope, EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, MemberTeamRole,+ OwnerAccessLevel, ViewAccessLevel,};use foreign_entity::domain::models::{ForeignEntity, SourceId};use foreign_entity::domain::ports::ForeignEntityService;@@ -147,14 +147,35 @@ fn should_revoke_non_owner_user_access(}}-/// The user id to attribute a document lifecycle event to, when the caller is-/// an authenticated user.-fn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {+/// Attribution fields published on document `updated` / `deleted` events.+///+/// User receipts keep filling the legacy `actor_user_id`; bot receipts acting+/// for a user fill `actor` + `on_behalf_of`. Team-scoped bots, internal and+/// unauthenticated callers publish nothing attributable.+#[derive(Default)]+struct PublishedDocumentActors {+ actor: Option<Actor<'static>>,+ on_behalf_of: Option<MacroUserIdStr<'static>>,+ actor_user_id: Option<MacroUserIdStr<'static>>,+}++fn published_document_actors(auth: &EntityAccessAuth) -> PublishedDocumentActors {match auth {- EntityAccessAuth::Authenticated(user_id) => Some(user_id.clone()),- EntityAccessAuth::Bot(_)- | EntityAccessAuth::Unauthenticated- | EntityAccessAuth::Internal => None,+ EntityAccessAuth::Authenticated(user_id) => PublishedDocumentActors {+ actor_user_id: Some(user_id.clone()),+ ..Default::default()+ },+ EntityAccessAuth::Bot(bot) => match bot.scope() {+ BotReceiptScope::User { acting_user } => PublishedDocumentActors {+ actor: Some(Actor::new_from_bot(bot.bot_id())),+ on_behalf_of: Some(acting_user.clone()),+ actor_user_id: None,+ },+ BotReceiptScope::Team { .. } => PublishedDocumentActors::default(),+ },+ EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => {+ PublishedDocumentActors::default()+ }}}@@ -1028,11 +1049,18 @@ impl<tracing::error!(error=?e, "failed to send invalidation event");});+ let PublishedDocumentActors {+ actor,+ on_behalf_of,+ actor_user_id,+ } = published_document_actors(entity_access_receipt.auth());self.publish_document_event(&DocumentMacroEvent::deleted(entity_access_receipt.entity().entity_id.clone(),DocumentDeletedMetadata {document_id: entity_access_receipt.entity().entity_id.clone(),- actor_user_id: event_actor_user_id(entity_access_receipt.auth()),+ actor_user_id,+ actor,+ on_behalf_of,project_id,},));@@ -1435,12 +1463,19 @@ impl<tracing::error!(error=?e, "failed to send invalidation event");});+ let PublishedDocumentActors {+ actor,+ on_behalf_of,+ actor_user_id,+ } = published_document_actors(entity_access_receipt.auth());self.publish_document_event(&DocumentMacroEvent::updated(entity_access_receipt.entity().entity_id.clone(),DocumentUpdatedMetadata {document_id: entity_access_receipt.entity().entity_id.clone(),owner: document_context.owner.clone(),- actor_user_id: event_actor_user_id(entity_access_receipt.auth()),+ actor_user_id,+ actor,+ on_behalf_of,document_name,previous_project_id: document_context.project_id.clone(),project_id: args.project_id,diff --git a/crates/documents/src/inbound/toolset.rs b/crates/documents/src/inbound/toolset.rsindex 6bcbce68ff..96a11de71d 100644--- a/crates/documents/src/inbound/toolset.rs+++ b/crates/documents/src/inbound/toolset.rs@@ -23,9 +23,12 @@ use crate::{markdown_init::LexicalSyncMarkdownInitializer,},};+use activity::{Actor, Attribution};use ai_toolset::AsyncToolCollection;+use bot_id::BotId;use entity_access::domain::ports::EntityAccessService;use lexical_client::LexicalClient;+use macro_user_id::user_id::MacroUserIdStr;use std::sync::Arc;use sync_service_client::SyncServiceClient;@@ -62,6 +65,10 @@ pub struct DocumentToolContext</// Records the token usage the editing worker reports. Defaults to a no-op;/// the chat path injects the real (Postgres-backed) recorder per request.pub recorder: Arc<dyn ai_usage::UsageRecorder>,++ /// The bot these tools act as, on behalf of the requesting user. Defaults+ /// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].+ pub actor: BotId,}impl<@@ -80,6 +87,7 @@ impl<editing: self.editing.clone(),document_permission_jwt_secret: self.document_permission_jwt_secret.clone(),recorder: self.recorder.clone(),+ actor: self.actor,}}}@@ -120,6 +128,7 @@ impl<editing: Arc::new(editing),document_permission_jwt_secret,recorder: Arc::new(ai_usage::NoOpUsageRecorder),+ actor: bot_id::MACRO_AI_BOT_ID,}}@@ -128,6 +137,17 @@ impl<self.recorder = recorder;self}++ /// Set the bot these tools act as.+ pub fn with_actor(mut self, actor: BotId) -> Self {+ self.actor = actor;+ self+ }++ /// Attribution for a write these tools make for `user`.+ pub fn attribution(&self, user: MacroUserIdStr<'static>) -> Attribution {+ Attribution::delegated(Actor::new_from_bot(self.actor), user)+ }}/// Create a document toolsetdiff --git a/crates/documents/src/inbound/toolset/create_document.rs b/crates/documents/src/inbound/toolset/create_document.rsindex abc77ddd37..0f4bdd2b78 100644--- a/crates/documents/src/inbound/toolset/create_document.rs+++ b/crates/documents/src/inbound/toolset/create_document.rs@@ -128,7 +128,8 @@ whereNone};- let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone());+ let mut metadata_builder = NewDocumentMetadata::builder(self.document_name.clone())+ .attribution(service_context.attribution(user_id.clone()));if let Some(project_id) = self.project_id {metadata_builder = metadata_builder.project_id(project_id);}diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rsindex ac1dfe496c..97c63f334f 100644--- a/crates/documents/src/inbound/toolset/edit_document.rs+++ b/crates/documents/src/inbound/toolset/edit_document.rs@@ -120,7 +120,7 @@ whereself.document_id.clone(),AccessLevel::Edit,&ctx.document_permission_jwt_secret,- Some(bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()),+ Some(ctx.actor.into_storage_id().to_string()),).map_err(|e| ToolCallError {description: "failed to mint document token".to_string(),diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex 4ca2351a85..fb02557de6 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -454,6 +454,13 @@ fn request_context() -> RequestContext {async fn call_edit_document(file_type: &str,+) -> (ToolResult<EditDocumentResponse>, FakeEditingWorker) {+ call_edit_document_as(file_type, None).await+}++async fn call_edit_document_as(+ file_type: &str,+ actor: Option<BotId>,) -> (ToolResult<EditDocumentResponse>, FakeEditingWorker) {let editing = FakeEditingWorker::default();let tool = EditDocument {@@ -461,16 +468,28 @@ async fn call_edit_document(instructions: "tidy up the imports".to_string(),};- let result = tool- .call(- tool_context(FakeDocumentService::new(file_type), editing.clone()),- request_context(),- )- .await;+ let mut context = tool_context(FakeDocumentService::new(file_type), editing.clone());+ if let Some(actor) = actor {+ context.0 = context.0.with_actor(actor);+ }+ let result = tool.call(context, request_context()).await;(result, editing)}+fn minted_token_actor(editing: &FakeEditingWorker) -> Option<String> {+ let token = editing+ .tokens+ .lock()+ .expect("edit tokens lock poisoned")+ .first()+ .expect("edit minted a document token")+ .clone();+ decode_permission_token(&token, "unused-jwt-secret")+ .expect("edit token should decode")+ .actor+}+#[tokio::test]async fn rejects_non_markdown_document_without_calling_the_worker() {let (result, editing) = call_edit_document("py").await;@@ -531,6 +550,38 @@ async fn allows_markdown_document() {);}+#[tokio::test]+async fn edit_token_carries_the_context_actor() {+ let (result, editing) = call_edit_document_as("md", Some(BotId::TEST_A)).await;+ result.expect("a markdown document should be editable");++ assert_eq!(+ minted_token_actor(&editing).as_deref(),+ Some(BotId::TEST_A.into_storage_id().as_ref())+ );+}++#[test]+fn tool_writes_are_delegated_from_the_context_actor_to_the_requesting_user() {+ let user = MacroUserIdStr::try_from(TEST_USER_ID.to_string()).expect("valid user");+ let default_context =+ tool_context(FakeDocumentService::new("md"), FakeEditingWorker::default());+ assert_eq!(default_context.actor, bot_id::MACRO_AI_BOT_ID);++ let attribution = default_context+ .0+ .with_actor(BotId::TEST_A)+ .attribution(user);+ assert_eq!(+ attribution.actor().as_ref(),+ BotId::TEST_A.into_storage_id().as_ref()+ );+ assert_eq!(+ attribution.on_behalf_of().as_ref().map(|id| id.as_ref()),+ Some(TEST_USER_ID)+ );+}+#[test]fn only_markdown_is_editable() {assert!(ensure_markdown(&document_with_file_type(Some("md"))).is_ok());diff --git a/crates/documents/src/inbound/toolset/rename_document.rs b/crates/documents/src/inbound/toolset/rename_document.rsindex a3254d4271..ad6b08e039 100644--- a/crates/documents/src/inbound/toolset/rename_document.rs+++ b/crates/documents/src/inbound/toolset/rename_document.rs@@ -7,7 +7,10 @@ use crate::domain::{use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use ai_toolset::{ToolAnnotated, ToolAnnotations};use async_trait::async_trait;-use entity_access::domain::{models::EntityType, ports::EntityAccessService};+use entity_access::domain::{+ models::{BotAccessScope, EntityType},+ ports::EntityAccessService,+};use models_permissions::share_permission::access_level::EditAccessLevel;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -84,9 +87,9 @@ wherelet entity_access_receipt = service_context.entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(- &request_context.user_id,- None,+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ service_context.actor,+ BotAccessScope::user(request_context.user_id.clone()),&document_id,EntityType::Document,)diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rsindex 98318c7439..bc82821d9d 100644--- a/crates/entity_access/src/domain/models.rs+++ b/crates/entity_access/src/domain/models.rs@@ -34,6 +34,15 @@ pub enum BotAccessScope {}impl BotAccessScope {+ /// User scope for a caller that knows only the acting user, such as an AI+ /// tool request, which carries no organization context.+ pub fn user(user_id: MacroUserIdStr<'static>) -> Self {+ Self::User {+ user_id,+ user_org_id: None,+ }+ }+/// Returns the verified acting user's identifier for user scope.pub fn user_id(&self) -> Option<&MacroUserIdStr<'static>> {match self {diff --git a/crates/projects/Cargo.toml b/crates/projects/Cargo.tomlindex b127867517..976284a471 100644--- a/crates/projects/Cargo.toml+++ b/crates/projects/Cargo.toml@@ -54,6 +54,7 @@ unicode-segmentation = { workspace = true }uuid = { workspace = true }# Domain models (always included)+bot_id = { path = "../bot_id" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management", default-features = false, features = ["outbound",diff --git a/crates/projects/src/inbound/toolset.rs b/crates/projects/src/inbound/toolset.rsindex be54529d22..4919fe28f3 100644--- a/crates/projects/src/inbound/toolset.rs+++ b/crates/projects/src/inbound/toolset.rs@@ -10,6 +10,7 @@ mod test;use std::sync::Arc;use ai_toolset::AsyncToolCollection;+use bot_id::BotId;use entity_access::domain::ports::EntityAccessService;use entity_mutation::MoveEntity;@@ -42,6 +43,9 @@ wherepub chat_move_service: Arc<CSvc>,/// Move capability for email threads.pub email_move_service: Arc<EmSvc>,+ /// The bot these tools act as, on behalf of the requesting user. Defaults+ /// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].+ pub actor: BotId,}impl<PSvc, ESvc, DSvc, CSvc, EmSvc> Clone for ProjectToolContext<PSvc, ESvc, DSvc, CSvc, EmSvc>@@ -59,6 +63,7 @@ wheredocument_move_service: self.document_move_service.clone(),chat_move_service: self.chat_move_service.clone(),email_move_service: self.email_move_service.clone(),+ actor: self.actor,}}}@@ -85,8 +90,15 @@ wheredocument_move_service,chat_move_service,email_move_service,+ actor: bot_id::MACRO_AI_BOT_ID,}}++ /// Set the bot these tools act as.+ pub fn with_actor(mut self, actor: BotId) -> Self {+ self.actor = actor;+ self+ }}/// Create a project toolset.diff --git a/crates/projects/src/inbound/toolset/move_to_project.rs b/crates/projects/src/inbound/toolset/move_to_project.rsindex 40d220365c..82dc88f8f2 100644--- a/crates/projects/src/inbound/toolset/move_to_project.rs+++ b/crates/projects/src/inbound/toolset/move_to_project.rs@@ -3,7 +3,10 @@use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use ai_toolset::{ToolAnnotated, ToolAnnotations};use async_trait::async_trait;-use entity_access::domain::models::EditAccessLevel;+use bot_id::BotId;+use entity_access::domain::models::{+ AccessError, BotAccessScope, EditAccessLevel, EntityAccessReceipt, RequiredPermission,+};use entity_access::domain::ports::EntityAccessService;use entity_mutation::{EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest};use macro_user_id::user_id::MacroUserIdStr;@@ -40,7 +43,7 @@ impl MoveableEntityType {}}-fn entity_access_failed(error: entity_access::domain::models::AccessError) -> ToolCallError {+fn entity_access_failed(error: AccessError) -> ToolCallError {ToolCallError {description:"you do not have the access required to move this entity, or it does not exist"@@ -49,7 +52,7 @@ fn entity_access_failed(error: entity_access::domain::models::AccessError) -> To}}-fn project_access_failed(error: entity_access::domain::models::AccessError) -> ToolCallError {+fn project_access_failed(error: AccessError) -> ToolCallError {ToolCallError {description: "you do not have edit access to the destination project, or it does not exist".to_string(),@@ -79,11 +82,62 @@ fn move_failed(code: EntityMutationErrorCode) -> ToolCallError {}}+/// Whose receipts a move is minted with.+///+/// Documents publish bot attribution from the tool actor's receipt. Chat+/// `patch`, project lifecycle events, and email `thread_project_changed` still+/// require an authenticated user, so those moves stay user-scoped.+#[derive(Clone, Copy, PartialEq, Eq)]+enum MovePrincipal {+ Bot(BotId),+ User,+}++impl MovePrincipal {+ fn for_entity(actor: BotId, entity_type: EntityType) -> Self {+ match entity_type {+ EntityType::Document => Self::Bot(actor),+ _ => Self::User,+ }+ }++ async fn receipt<T, ESvc>(+ self,+ entity_access_service: &ESvc,+ user_id: &MacroUserIdStr<'static>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError>+ where+ T: RequiredPermission,+ ESvc: EntityAccessService,+ {+ match self {+ Self::Bot(actor) => {+ entity_access_service+ .generate_bot_entity_access_receipt::<T>(+ actor,+ BotAccessScope::user(user_id.clone()),+ entity_id,+ entity_type,+ )+ .await+ }+ Self::User => {+ entity_access_service+ .generate_entity_access_receipt::<T>(user_id, None, entity_id, entity_type)+ .await+ }+ }+ }+}+/// Mint the receipts a domain's move capability requires and dispatch to it,/// mirroring the DSS entity-mutation router.async fn move_with<S, ESvc>(service: &S,entity_access_service: &ESvc,+ actor: BotId,user_id: &MacroUserIdStr<'static>,entity: Entity<'static>,project_id: Option<String>,@@ -92,10 +146,11 @@ whereS: MoveEntity,ESvc: EntityAccessService,{- let receipt = entity_access_service- .generate_entity_access_receipt::<S::Receipt>(+ let principal = MovePrincipal::for_entity(actor, entity.entity_type);+ let receipt = principal+ .receipt::<S::Receipt, _>(+ entity_access_service,user_id,- None,&entity.entity_id,entity.entity_type,)@@ -104,10 +159,10 @@ wherelet request = match project_id {Some(project_id) => {- let project_receipt = entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(+ let project_receipt = principal+ .receipt::<EditAccessLevel, _>(+ entity_access_service,user_id,- None,&project_id,EntityType::Project,)@@ -193,11 +248,13 @@ wherelet project_id = self.project_id.map(|id| id.to_string());let entity_access_service = &*service_context.entity_access_service;+ let actor = service_context.actor;match self.entity_type {MoveableEntityType::Document => {move_with(&*service_context.document_move_service,entity_access_service,+ actor,&user_id,entity,project_id,@@ -208,6 +265,7 @@ wheremove_with(&*service_context.chat_move_service,entity_access_service,+ actor,&user_id,entity,project_id,@@ -218,6 +276,7 @@ wheremove_with(&*service_context.email_move_service,entity_access_service,+ actor,&user_id,entity,project_id,@@ -228,6 +287,7 @@ wheremove_with(&*service_context.service,entity_access_service,+ actor,&user_id,entity,project_id,diff --git a/crates/properties/Cargo.toml b/crates/properties/Cargo.tomlindex ff707602b4..3f52f97f91 100644--- a/crates/properties/Cargo.toml+++ b/crates/properties/Cargo.toml@@ -41,6 +41,7 @@ async-trait = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }document_sub_type = { path = "../document_sub_type" }+bot_id = { path = "../bot_id" }entity_access = { path = "../entity_access", default-features = false, features = ["ports",] }diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rsindex b5fc0d1124..3cfb1496e5 100644--- a/crates/properties/src/domain/service_impl.rs+++ b/crates/properties/src/domain/service_impl.rs@@ -676,7 +676,7 @@ whereif property_definition_id == SystemPropertyKey::ASSIGNEES_UUID&& entity_type == EntityType::Task{- self.handle_task_assignees_property(entity_id, value, access.authenticated_user())+ self.handle_task_assignees_property(entity_id, value, access.acting_user_id()).await?;}diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rsindex 177efb4649..75ab4b14ad 100644--- a/crates/properties/src/domain/service_impl/task_properties.rs+++ b/crates/properties/src/domain/service_impl/task_properties.rs@@ -36,10 +36,12 @@ where) -> Result<(), PropertiesErr> {let user_id = match access.auth() {EntityAccessAuth::Internal => return Ok(()),- EntityAccessAuth::Authenticated(user_id) => user_id,- EntityAccessAuth::Bot(_) | EntityAccessAuth::Unauthenticated => {+ EntityAccessAuth::Unauthenticated => {return Err(PropertiesErr::PermissionDenied);}+ EntityAccessAuth::Authenticated(_) | EntityAccessAuth::Bot(_) => access+ .acting_user_id()+ .ok_or(PropertiesErr::PermissionDenied)?,};if referenced_task_ids.is_empty() {return Ok(());diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex deaabb90e1..48ed0f1f73 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -1812,6 +1812,48 @@ async fn test_link_parent_task_rejects_bot_and_unauthenticated_callers() {}}+#[tokio::test]+async fn test_link_parent_task_allows_user_scoped_bot_receipt() {+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);+ let parent_id = Uuid::from_u128(0xabcdef01_2345_6789_abcd_ef0123456789);+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000005759"));+ let bot_access = EditReceipt::dangerously_assert_bot(+ bot_id.into_storage_id(),+ BotReceiptScope::User {+ acting_user: caller_user_id(),+ },+ &task_id.to_string(),+ AccessEntityType::Document,+ );++ let mut repo = MockPropertiesRepo::new();+ repo.expect_link_parent_task()+ .withf(move |t, p| *t == task_id && *p == Some(parent_id))+ .returning(|task_id, _| {+ let property = entity_property(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::PARENT_TASK_UUID,+ );+ Box::pin(async move { Ok(Some(property)) })+ });++ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );++ service+ .handle_task_relationship_property(+ &bot_access,+ SystemPropertyKey::PARENT_TASK_UUID,+ Some(parent_task_value(parent_id)),+ )+ .await+ .unwrap();+}+#[tokio::test]async fn test_link_parent_task_error_propagates() {let mut repo = MockPropertiesRepo::new();@@ -3012,6 +3054,97 @@ async fn canonical_document_task_assignee_write_grants_permissions() {.unwrap();}+#[tokio::test]+async fn user_scoped_bot_assignee_write_notifies_as_the_acting_user() {+ let task_id = Uuid::from_u128(0xA5516F);+ let assignee = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let acting_user = caller_user_id();+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000005759"));+ let bot_access = EditReceipt::dangerously_assert_bot(+ bot_id.into_storage_id(),+ BotReceiptScope::User {+ acting_user: acting_user.clone(),+ },+ &task_id.to_string(),+ AccessEntityType::Document,+ );++ let mut repo = MockPropertiesRepo::new();+ repo.expect_get_document_sub_types()+ .withf(move |ids| ids == [task_id])+ .returning(move |_| {+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })+ });+ repo.expect_get_property_definition().returning(|_| {+ Box::pin(async {+ Ok(Some(PropertyDefinition {+ id: SystemPropertyKey::ASSIGNEES_UUID,+ owner: models_properties::PropertyOwner::System,+ display_name: "Assignees".to_string(),+ data_type: models_properties::DataType::Entity,+ is_multi_select: true,+ specific_entity_type: Some(EntityType::User),+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: true,+ is_metadata: false,+ }))+ })+ });+ repo.expect_get_entity_property_value()+ .returning(|_, _, _| Box::pin(async { Ok(None) }));+ repo.expect_upsert_entity_property().returning(+ |entity_id, entity_type, property_definition_id, _| {+ let property = entity_property(entity_id, entity_type, property_definition_id);+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property,+ value: None,+ previous_value: None,+ })+ })+ },+ );++ let mut permission_service = MockPermissionService::new();+ let expected_assignee = assignee.clone();+ permission_service+ .expect_grant_permissions_to_task()+ .withf(move |user_ids, id| {+ user_ids == [expected_assignee.clone()] && id == task_id.to_string()+ })+ .returning(|_, _| Box::pin(async { Ok(()) }));++ let mut notif_service = MockNotificationService::new();+ let expected_assigned_by = acting_user.clone();+ notif_service+ .expect_send_task_assigned()+ .times(1)+ .withf(move |notification| {+ notification.assigned_by.as_ref() == expected_assigned_by.as_ref()+ && notification.recipient_ids.len() == 1+ })+ .returning(|_| Box::pin(async { Ok(()) }));++ let service = PropertiesServiceImpl::new(repo, Some(permission_service), Some(notif_service));++ service+ .set_entity_property(+ &bot_access,+ SystemPropertyKey::ASSIGNEES_UUID,+ Some(+ models_properties::api::requests::SetPropertyValue::MultiEntityReference {+ references: vec![models_properties::EntityReference::new(+ assignee.as_ref(),+ EntityType::User,+ )],+ },+ ),+ )+ .await+ .unwrap();+}+#[tokio::test]async fn canonical_document_task_read_uses_task_storage_type() {let task_id = Uuid::from_u128(0xBEEF);diff --git a/crates/properties/src/inbound/toolset.rs b/crates/properties/src/inbound/toolset.rsindex b9ae0da8d5..9912a22ff7 100644--- a/crates/properties/src/inbound/toolset.rs+++ b/crates/properties/src/inbound/toolset.rs@@ -14,6 +14,7 @@ mod test;use crate::domain::service::{PropertiesService, TeamReceipt};use ai_toolset::{AsyncToolCollection, RequestContext, ServiceContext, ToolCallError};+use bot_id::BotId;use entity_access::domain::models::{AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType,};@@ -36,6 +37,9 @@ pub struct PropertiesToolContext<T: PropertiesService, A: EntityAccessService> {pub service: Arc<T>,/// The canonical service used to mint entity access receipts.pub entity_access_service: Arc<A>,+ /// The bot these tools act as, on behalf of the requesting user. Defaults+ /// to Macro AI; hosts running a specific agent set it with [`Self::with_actor`].+ pub actor: BotId,}impl<T: PropertiesService, A: EntityAccessService> Clone for PropertiesToolContext<T, A> {@@ -43,6 +47,7 @@ impl<T: PropertiesService, A: EntityAccessService> Clone for PropertiesToolConteSelf {service: self.service.clone(),entity_access_service: self.entity_access_service.clone(),+ actor: self.actor,}}}@@ -53,8 +58,15 @@ impl<T: PropertiesService, A: EntityAccessService> PropertiesToolContext<T, A> {Self {service: Arc::new(service),entity_access_service: Arc::new(entity_access_service),+ actor: bot_id::MACRO_AI_BOT_ID,}}++ /// Set the bot these tools act as.+ pub fn with_actor(mut self, actor: BotId) -> Self {+ self.actor = actor;+ self+ }}/// Mint the caller's team-membership receipt, or `None` when they are not on adiff --git a/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rsindex 946bd27eda..161d4642f9 100644--- a/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs+++ b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs@@ -6,7 +6,7 @@ use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use ai_toolset::{ToolAnnotated, ToolAnnotations};use async_trait::async_trait;-use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::models::{BotAccessScope, EditAccessLevel};use entity_access::domain::ports::EntityAccessService;use schemars::JsonSchema;use serde::{Deserialize, Serialize};@@ -153,9 +153,9 @@ wherelet entity_type = model_entity::EntityType::from(entity.entity_type);match service_context.entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(- &request_context.user_id,- None,+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ service_context.actor,+ BotAccessScope::user(request_context.user_id.clone()),&entity.entity_id,entity_type,)diff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rsindex 6f16aad195..c3cc6ef1c0 100644--- a/crates/properties/src/inbound/toolset/set_entity_property.rs+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs@@ -5,7 +5,7 @@ use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolRuse ai_toolset::{ToolAnnotated, ToolAnnotations};use async_trait::async_trait;use chrono::{DateTime, Utc};-use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::models::{BotAccessScope, EditAccessLevel};use entity_access::domain::ports::EntityAccessService;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;@@ -225,9 +225,9 @@ where// Prove the requesting user can edit the entity before writing anything.let entity_access_receipt = service_context.entity_access_service- .generate_entity_access_receipt::<EditAccessLevel>(- &request_context.user_id,- None,+ .generate_bot_entity_access_receipt::<EditAccessLevel>(+ service_context.actor,+ BotAccessScope::user(request_context.user_id.clone()),&self.entity_id,entity_type,)diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 2c6f873b13..1a288e9d24 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -63,6 +63,8 @@ fn updated_event() -> Event<DocumentTopicEvent> {document_id: DOCUMENT_ID.to_string(),owner: user(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,document_name: Some("Updated".to_string()),previous_project_id: None,project_id: None,@@ -133,6 +135,8 @@ fn document_lifecycle_events_map_to_updated_and_deleted_patches() {let deleted = DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,project_id: None,});@@ -152,6 +156,8 @@ fn moving_a_document_out_of_a_project_updates_the_previous_project() {document_id: DOCUMENT_ID.to_string(),owner: user(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,document_name: None,previous_project_id: Some(previous_project_id.clone()),project_id: None,diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 563274886b..af2550f40d 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -475,6 +475,8 @@ fn document_event_cases() -> Vec<EventCase> {document_id: DOCUMENT_ID.to_string(),owner: user_id("macro|[email protected]"),actor_user_id: Some(user_id("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,document_name: Some("renamed".to_string()),previous_project_id: None,project_id: None,@@ -493,6 +495,8 @@ fn document_event_cases() -> Vec<EventCase> {DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user_id("macro|[email protected]")),+ actor: None,+ on_behalf_of: None,project_id: None,}),2,@@ -1257,6 +1261,8 @@ async fn malformed_document_id_is_permanent_and_skips_access_resolution() {let event = Event::new(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: "not-a-uuid".to_string(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,project_id: None,}));diff --git a/crates/webhook/src/inbound/kafka_consumer/test.rs b/crates/webhook/src/inbound/kafka_consumer/test.rsindex 1762e37590..179f3a1b92 100644--- a/crates/webhook/src/inbound/kafka_consumer/test.rs+++ b/crates/webhook/src/inbound/kafka_consumer/test.rs@@ -41,6 +41,8 @@ fn document_event() -> Event<DocumentTopicEvent> {Event::new(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: "doc_1".to_string(),actor_user_id: None,+ actor: None,+ on_behalf_of: None,project_id: None,}))}diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 961facf533..5562f26ece 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -4063,11 +4063,18 @@ export type DocumentCreatedMetadata = {* Metadata for [`DocumentTopicEvent::Deleted`].*/export type DocumentDeletedMetadata = {+ /**+ * Who mechanically deleted the document. Absent on events published+ * before attribution, and on user-receipt writes (ingest then uses+ * [`Self::actor_user_id`]).+ */+ actor?: string | null;actor_user_id?: null | MacroUserIdStr;/*** The id of the deleted document.*/document_id: string;+ on_behalf_of?: null | MacroUserIdStr;/*** Project the document belonged to, when any.*/@@ -4515,6 +4522,12 @@ export type DocumentTopicEvent = {* Metadata for [`DocumentTopicEvent::Updated`].*/export type DocumentUpdatedMetadata = {+ /**+ * Who mechanically updated the document. Absent on events published+ * before attribution, and on user-receipt writes (ingest then uses+ * [`Self::actor_user_id`]).+ */+ actor?: string | null;actor_user_id?: null | MacroUserIdStr;/*** The id of the updated document.@@ -4525,6 +4538,7 @@ export type DocumentUpdatedMetadata = {*/document_name?: string | null;file_type?: null | FileTypeUpdate;+ on_behalf_of?: null | MacroUserIdStr;/*** The owner of the document.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 3444009408..dcabeb7d37 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -18345,6 +18345,10 @@"description": "Metadata for [`DocumentTopicEvent::Deleted`].","required": ["document_id"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically deleted the document. Absent on events published\nbefore attribution, and on user-receipt writes (ingest then uses\n[`Self::actor_user_id`])."+ },"actor_user_id": {"oneOf": [{@@ -18360,6 +18364,17 @@"type": "string","description": "The id of the deleted document."},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this delete belongs on, when different from\n[`Self::actor`]."+ }+ ]+ },"project_id": {"type": ["string", "null"],"description": "Project the document belonged to, when any."@@ -19075,6 +19090,10 @@"description": "Metadata for [`DocumentTopicEvent::Updated`].","required": ["document_id", "owner", "share_permission_updated"],"properties": {+ "actor": {+ "type": ["string", "null"],+ "description": "Who mechanically updated the document. Absent on events published\nbefore attribution, and on user-receipt writes (ingest then uses\n[`Self::actor_user_id`])."+ },"actor_user_id": {"oneOf": [{@@ -19105,6 +19124,17 @@}]},+ "on_behalf_of": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MacroUserIdStr",+ "description": "The user whose feed this update belongs on, when different from\n[`Self::actor`]."+ }+ ]+ },"owner": {"$ref": "#/components/schemas/MacroUserIdStr","description": "The owner of the document."diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex f5483b9a4f..6663a0579e 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -850,6 +850,8 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>document_id: DOCUMENT_ID.to_string(),owner: owner.clone(),actor_user_id: Some(owner.clone()),+ actor: None,+ on_behalf_of: None,document_name: Some("Renamed document".to_string()),previous_project_id: Some(PROJECT_ID.to_string()),project_id: None,@@ -867,6 +869,8 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>document_id: DOCUMENT_ID.to_string(),owner: owner.clone(),actor_user_id: Some(owner.clone()),+ actor: None,+ on_behalf_of: None,document_name: None,previous_project_id: None,project_id: Some(PROJECT_ID.to_string()),@@ -883,6 +887,8 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>DocumentTopicEvent::Deleted(DocumentDeletedMetadata {document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(owner.clone()),+ actor: None,+ on_behalf_of: None,project_id: Some(PROJECT_ID.to_string()),}),DocumentEventDescription {