Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(activity): attribute system and agent document creates (#5831)

teo2f020a8d6f80
diff --git a/Cargo.lock b/Cargo.lock
index 250a4e2ca7..1187091f2d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -475,6 +475,7 @@ dependencies = [
name = "ai_tools"
version = "0.1.0"
dependencies = [
+ "activity",
"agent",
"ai_toolset",
"ai_usage",
@@ -485,6 +486,7 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
+ "bot_id",
"calendar_events",
"call",
"channels",
@@ -4862,6 +4864,7 @@ dependencies = [
"axum",
"axum-extra",
"base64 0.22.1",
+ "bot_id",
"bots",
"bytes",
"bzip2",
@@ -5078,6 +5081,7 @@ dependencies = [
"axum",
"axum-extra",
"base64 0.22.1",
+ "bot_id",
"chrono",
"clap",
"cloudfront_sign",
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 3b615d3ef3..07eab5243f 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -16474,6 +16474,10 @@
"description": "Metadata for [`DocumentTopicEvent::Created`].",
"required": ["document_id", "owner", "document_name"],
"properties": {
+ "actor": {
+ "type": ["string", "null"],
+ "description": "Who mechanically created the document. Absent on events published\nbefore attribution: ingest then treats [`Self::owner`] as the actor."
+ },
"created_at": {
"type": ["string", "null"],
"format": "date-time",
@@ -16498,6 +16502,17 @@
}
]
},
+ "on_behalf_of": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "The user whose feed this creation belongs on, when different from\n[`Self::actor`]. Absent means the actor is also the subject."
+ }
+ ]
+ },
"owner": {
"$ref": "#/components/schemas/MacroUserIdStr",
"description": "The owner (creator) of the document."
diff --git a/crates/activity/src/domain/models.rs b/crates/activity/src/domain/models.rs
index 855271ec38..ab7fbcae91 100644
--- a/crates/activity/src/domain/models.rs
+++ b/crates/activity/src/domain/models.rs
@@ -31,6 +31,53 @@ use uuid::Uuid;
/// prefix-parseable string. An agent is a bot acting with `on_behalf_of`
/// set — agent-ness is relational, not an identity kind.
pub use channel_sender::ChannelSender as Actor;
+
+/// Who performed an action, and whose feed it belongs on.
+///
+/// Stored as `actor_id` plus `subject_id` (`on_behalf_of ?? actor`).
+#[derive(Debug, Clone, PartialEq)]
+pub enum Attribution {
+ /// The principal acted for themselves. Subject equals actor.
+ Direct {
+ /// Who mechanically acted.
+ actor: Actor<'static>,
+ },
+ /// A bot or the platform acted for a user. Subject is that user.
+ Delegated {
+ /// Who mechanically acted.
+ actor: Actor<'static>,
+ /// Whose activity feed this belongs on.
+ subject: MacroUserIdStr<'static>,
+ },
+}
+
+impl Attribution {
+ /// The principal acted for themselves.
+ pub fn direct(actor: Actor<'static>) -> Self {
+ Self::Direct { actor }
+ }
+
+ /// A bot or the platform acted for `subject`.
+ pub fn delegated(actor: Actor<'static>, subject: MacroUserIdStr<'static>) -> Self {
+ Self::Delegated { actor, subject }
+ }
+
+ /// Who mechanically acted.
+ pub fn actor(&self) -> Actor<'static> {
+ match self {
+ Self::Direct { actor } | Self::Delegated { actor, .. } => actor.clone(),
+ }
+ }
+
+ /// The initiating user when this action is delegated; `None` when direct.
+ pub fn on_behalf_of(&self) -> Option<MacroUserIdStr<'static>> {
+ match self {
+ Self::Direct { .. } => None,
+ Self::Delegated { subject, .. } => Some(subject.clone()),
+ }
+ }
+}
+
/// The entity-kind vocabulary activities are recorded against (re-exported
/// for domain mappings).
pub use model_entity::EntityType;
@@ -380,6 +427,29 @@ pub struct Activity {
}
impl Activity {
+ /// Builds an activity for a [`CommonAction`] from a resolved
+ /// [`Attribution`].
+ pub fn attributed(
+ source_event_id: Uuid,
+ ordinal: u32,
+ attribution: Attribution,
+ entity_type: EntityType,
+ entity_id: impl Into<String>,
+ action: CommonAction,
+ occurred_at: DateTime<Utc>,
+ ) -> Self {
+ Self::common(
+ source_event_id,
+ ordinal,
+ attribution.actor(),
+ attribution.on_behalf_of(),
+ entity_type,
+ entity_id,
+ action,
+ occurred_at,
+ )
+ }
+
/// Builds an activity for a [`CommonAction`] — valid on every entity
/// kind by definition, so any (kind, id) pairing is accepted.
#[allow(clippy::too_many_arguments)]
diff --git a/crates/activity/src/domain/models/test.rs b/crates/activity/src/domain/models/test.rs
index ffd2ab61a0..846619e7f0 100644
--- a/crates/activity/src/domain/models/test.rs
+++ b/crates/activity/src/domain/models/test.rs
@@ -135,6 +135,49 @@ fn activity_ids_are_deterministic_per_event_and_ordinal() {
assert_ne!(activity_id(event_id, 0), activity_id(Uuid::from_u128(8), 0));
}
+#[test]
+fn attribution_direct_leaves_subject_on_the_actor() {
+ let actor = Actor::new_from_user(user("macro|[email protected]"));
+ let attribution = Attribution::direct(actor.clone());
+
+ assert_eq!(attribution.actor(), actor);
+ assert_eq!(attribution.on_behalf_of(), None);
+
+ let activity = Activity::attributed(
+ Uuid::from_u128(4),
+ 0,
+ attribution,
+ EntityType::Document,
+ "doc-1",
+ CommonAction::Created,
+ Utc::now(),
+ );
+ assert_eq!(activity.actor, actor);
+ assert_eq!(activity.subject_id, "macro|[email protected]");
+}
+
+#[test]
+fn attribution_delegated_keeps_actor_and_scopes_the_subject() {
+ let actor = Actor::new_from_user(user("macro|[email protected]"));
+ let subject = user("macro|[email protected]");
+ let attribution = Attribution::delegated(actor.clone(), subject.clone());
+
+ assert_eq!(attribution.actor(), actor);
+ assert_eq!(attribution.on_behalf_of(), Some(subject));
+
+ let activity = Activity::attributed(
+ Uuid::from_u128(5),
+ 0,
+ attribution,
+ EntityType::Document,
+ "doc-1",
+ CommonAction::Edited,
+ Utc::now(),
+ );
+ assert_eq!(activity.actor, actor);
+ assert_eq!(activity.subject_id, "macro|[email protected]");
+}
+
#[test]
fn subject_is_the_actor_unless_delegated() {
let direct = Activity::common(
diff --git a/crates/activity/src/lib.rs b/crates/activity/src/lib.rs
index c377756ede..436cac306e 100644
--- a/crates/activity/src/lib.rs
+++ b/crates/activity/src/lib.rs
@@ -26,8 +26,8 @@ pub mod inbound;
pub mod outbound;
pub use domain::models::{
- Action, ActionDecodeError, Activity, ActivityRecord, ActivitySource, Actor, CallStart,
- CommonAction, DomainActivity, EntityType, Ingest, ParticipantChange, PropertyChange,
+ Action, ActionDecodeError, Activity, ActivityRecord, ActivitySource, Actor, Attribution,
+ CallStart, CommonAction, DomainActivity, EntityType, Ingest, ParticipantChange, PropertyChange,
RecordedAction, VIEW_ACTION_TAGS, activity_id, event_time,
};
pub use domain::ports::{ActivityFeedPage, ActivityReads, EntityActivityMap};
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index cc5998909d..5b86a812b6 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -14,7 +14,9 @@ anthropic = { path = "../anthropic", features = ["toolset"] }
attachment = { path = "../attachment" }
non_empty = { path = "../non_empty" }
ai_toolset = { path = "../ai_toolset" }
+activity = { path = "../activity", default-features = false }
anyhow.workspace = true
+bot_id = { path = "../bot_id" }
async-trait.workspace = true
axum = { workspace = true, features = ["macros"] }
aws-sdk-sqs.workspace = true
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 9f39e9ad06..c4ed1f5bee 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -896,7 +896,12 @@ impl ToolEntityCreator {
) -> anyhow::Result<String> {
use std::str::FromStr as _;
let document = documents::domain::create::NewPlainTextDocument::builder(
- documents::domain::create::NewDocumentMetadata::new(name.to_string()),
+ documents::domain::create::NewDocumentMetadata::builder(name.to_string())
+ .attribution(activity::Attribution::delegated(
+ activity::Actor::new_from_bot(bot_id::MACRO_AI_BOT_ID),
+ user.clone(),
+ ))
+ .build(),
)
.file_type(model::document::FileType::from_str("md").expect("md is a valid file type"))
.text(markdown.to_string())
diff --git a/crates/bot_id/src/lib.rs b/crates/bot_id/src/lib.rs
index af72c8ae59..1c3377337d 100644
--- a/crates/bot_id/src/lib.rs
+++ b/crates/bot_id/src/lib.rs
@@ -60,6 +60,13 @@ pub const MACRO_AI_HANDLE: &str = "macro";
/// Display name for the "Macro" system bot.
pub const MACRO_AI_NAME: &str = "Macro";
+/// Stable [`BotId`] for autonomous Macro platform operations.
+pub const MACRO_SYSTEM_BOT_ID: BotId =
+ BotId::new_from_uuid(Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_5759));
+
+/// Display name for the autonomous Macro platform principal.
+pub const MACRO_SYSTEM_NAME: &str = "Macro System";
+
/// Stable [`BotId`] for the "Macro Coder" system bot, our coding-agent harness.
///
/// Distinct from [`MACRO_AI_BOT_ID`] on purpose: mentioning Macro AI answers in
diff --git a/crates/bot_id/src/test.rs b/crates/bot_id/src/test.rs
index 8ecf43c054..b949840253 100644
--- a/crates/bot_id/src/test.rs
+++ b/crates/bot_id/src/test.rs
@@ -36,6 +36,16 @@ fn bot_id_str_from_bot_id_creates_storage_string() {
assert_eq!(storage.to_string(), format!("bot|{bot_id}"));
}
+#[test]
+fn system_bot_id_is_stable_and_distinct_from_ai_personas() {
+ assert_eq!(
+ MACRO_SYSTEM_BOT_ID.into_storage_id().as_ref(),
+ "bot|00000000-0000-0000-0000-000000005759"
+ );
+ assert_ne!(MACRO_SYSTEM_BOT_ID, MACRO_AI_BOT_ID);
+ assert_ne!(MACRO_SYSTEM_BOT_ID, MACRO_CODER_BOT_ID);
+}
+
#[test]
fn rejects_non_bot_storage_string() {
assert!(BotIdStr::parse_from_str("macro|[email protected]").is_err());
diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml
index 5a8c9d2c9c..95a700cbb8 100644
--- a/crates/documents/Cargo.toml
+++ b/crates/documents/Cargo.toml
@@ -72,6 +72,7 @@ service = ["dep:entity_access_management", "dep:foreign_entity", "ports"]
[dependencies]
activity = { path = "../activity", default-features = false }
+bot_id = { path = "../bot_id" }
# Core
anyhow = { workspace = true }
chrono = { workspace = true }
diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rs
index 266c6edcaa..2a5619efac 100644
--- a/crates/documents/src/domain/activity.rs
+++ b/crates/documents/src/domain/activity.rs
@@ -6,7 +6,9 @@
#[cfg(test)]
mod test;
-use ::activity::{Activity, ActivitySource, Actor, CommonAction, EntityType, Ingest, event_time};
+use ::activity::{
+ Activity, ActivitySource, Actor, Attribution, CommonAction, EntityType, Ingest, event_time,
+};
use chrono::{DateTime, Utc};
use uuid::Uuid;
@@ -18,15 +20,14 @@ impl ActivitySource for DocumentTopicEvent {
/// Exhaustive on purpose: a new event variant fails compilation here
/// until someone classifies it or explicitly drops it.
fn ingest(&self, event_id: Uuid) -> Ingest {
- let single = |actor: Actor<'static>,
+ let single = |attribution: Attribution,
action: CommonAction,
document_id: &str,
occurred_at: DateTime<Utc>| {
- Ingest::Insert(vec![Activity::common(
+ Ingest::Insert(vec![Activity::attributed(
event_id,
0,
- actor,
- None,
+ attribution,
EntityType::Document,
document_id,
action,
@@ -35,15 +36,25 @@ impl ActivitySource for DocumentTopicEvent {
};
match self {
- DocumentTopicEvent::Created(metadata) => single(
- Actor::new_from_user(metadata.owner.clone()),
- CommonAction::Created,
- &metadata.document_id,
- metadata.created_at.unwrap_or_else(|| event_time(event_id)),
- ),
+ DocumentTopicEvent::Created(metadata) => {
+ let actor = metadata
+ .actor
+ .clone()
+ .unwrap_or_else(|| Actor::new_from_user(metadata.owner.clone()));
+ let attribution = match metadata.on_behalf_of.clone() {
+ Some(subject) => Attribution::delegated(actor, subject),
+ None => Attribution::direct(actor),
+ };
+ single(
+ attribution,
+ CommonAction::Created,
+ &metadata.document_id,
+ metadata.created_at.unwrap_or_else(|| event_time(event_id)),
+ )
+ }
DocumentTopicEvent::Updated(metadata) => match &metadata.actor_user_id {
Some(actor) => single(
- Actor::new_from_user(actor.clone()),
+ Attribution::direct(Actor::new_from_user(actor.clone())),
CommonAction::Edited,
&metadata.document_id,
event_time(event_id),
@@ -52,7 +63,7 @@ impl ActivitySource for DocumentTopicEvent {
},
DocumentTopicEvent::Deleted(metadata) => match &metadata.actor_user_id {
Some(actor) => single(
- Actor::new_from_user(actor.clone()),
+ Attribution::direct(Actor::new_from_user(actor.clone())),
CommonAction::Deleted,
&metadata.document_id,
event_time(event_id),
@@ -61,7 +72,7 @@ impl ActivitySource for DocumentTopicEvent {
},
// The copy is a new document; its creation is the activity.
DocumentTopicEvent::Copied(metadata) => single(
- Actor::new_from_user(metadata.owner.clone()),
+ Attribution::direct(Actor::new_from_user(metadata.owner.clone())),
CommonAction::Created,
&metadata.document_id,
event_time(event_id),
diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rs
index a7ed347d1e..ec1b542cae 100644
--- a/crates/documents/src/domain/activity/test.rs
+++ b/crates/documents/src/domain/activity/test.rs
@@ -40,6 +40,8 @@ fn created_maps_to_a_created_activity_with_the_metadata_timestamp() {
let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {
document_id: DOCUMENT_ID.to_string(),
owner: user("macro|[email protected]"),
+ actor: None,
+ on_behalf_of: None,
document_name: "spec".to_string(),
file_type: Some(FileType::Md),
project_id: None,
@@ -54,6 +56,55 @@ fn created_maps_to_a_created_activity_with_the_metadata_timestamp() {
assert_eq!(activity.entity_id, DOCUMENT_ID);
assert_eq!(activity.occurred_at, created_at);
assert_eq!(activity.id, activity_id(event.event_id, 0));
+ assert_eq!(activity.actor.as_ref(), "macro|[email protected]");
+}
+
+#[test]
+fn created_with_system_actor_is_not_the_owner_subject() {
+ let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {
+ document_id: DOCUMENT_ID.to_string(),
+ owner: user("macro|[email protected]"),
+ actor: Some(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID)),
+ on_behalf_of: None,
+ document_name: "invoice".to_string(),
+ file_type: None,
+ project_id: None,
+ sub_type: None,
+ created_at: None,
+ }));
+
+ let activity = single_activity(event.event.ingest(event.event_id));
+ assert_eq!(activity.action, Action::Created);
+ assert_eq!(
+ activity.actor.as_ref(),
+ bot_id::MACRO_SYSTEM_BOT_ID.into_storage_id().as_ref()
+ );
+ assert_eq!(
+ activity.subject_id,
+ bot_id::MACRO_SYSTEM_BOT_ID.into_storage_id().as_ref()
+ );
+}
+
+#[test]
+fn created_on_behalf_of_the_owner_stays_on_their_feed() {
+ let event = envelope(DocumentTopicEvent::Created(DocumentCreatedMetadata {
+ document_id: DOCUMENT_ID.to_string(),
+ owner: user("macro|[email protected]"),
+ actor: Some(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID)),
+ on_behalf_of: Some(user("macro|[email protected]")),
+ document_name: "welcome".to_string(),
+ file_type: None,
+ project_id: None,
+ sub_type: None,
+ created_at: None,
+ }));
+
+ let activity = single_activity(event.event.ingest(event.event_id));
+ assert_eq!(
+ activity.actor.as_ref(),
+ bot_id::MACRO_SYSTEM_BOT_ID.into_storage_id().as_ref()
+ );
+ assert_eq!(activity.subject_id, "macro|[email protected]");
}
#[test]
diff --git a/crates/documents/src/domain/create/mod.rs b/crates/documents/src/domain/create/mod.rs
index aff8a5effc..0d7ae93dde 100644
--- a/crates/documents/src/domain/create/mod.rs
+++ b/crates/documents/src/domain/create/mod.rs
@@ -5,6 +5,7 @@
//! call sites should choose the lifecycle they need (`create_markdown_text` or
//! `create_text_file`).
+use activity::Attribution;
use anyhow::Context;
use base64::Engine;
use macro_user_id::user_id::MacroUserIdStr;
@@ -30,6 +31,7 @@ pub struct NewDocumentMetadata {
email_attachment_id: Option<uuid::Uuid>,
created_at: Option<chrono::DateTime<chrono::Utc>>,
skip_history: bool,
+ attribution: Option<Attribution>,
}
impl NewDocumentMetadata {
@@ -48,6 +50,7 @@ impl NewDocumentMetadata {
email_attachment_id: None,
created_at: None,
skip_history: false,
+ attribution: None,
},
}
}
@@ -69,6 +72,7 @@ impl NewDocumentMetadata {
created_at: self.created_at,
sub_type: kind.subtype.sub_type(),
skip_history: self.skip_history,
+ attribution: self.attribution,
}
}
}
@@ -110,6 +114,12 @@ impl NewDocumentMetadataBuilder {
self
}
+ /// Attribute the create without changing document ownership.
+ pub fn attribution(mut self, attribution: Attribution) -> Self {
+ self.metadata.attribution = Some(attribution);
+ self
+ }
+
/// Build the metadata value.
pub fn build(self) -> NewDocumentMetadata {
self.metadata
@@ -730,13 +740,68 @@ fn file_shas(file_content: &[u8]) -> FileShas {
#[cfg(test)]
mod tests {
- use super::{MarkdownSubtype, NewDocumentMetadata, NewPlainTextDocument, file_shas};
+ use super::{
+ MarkdownSubtype, NewDocumentMetadata, NewPlainTextDocument, RepoDocumentKind,
+ RepoDocumentSubtype, file_shas,
+ };
+ use activity::{Actor, Attribution};
+ use macro_user_id::user_id::MacroUserIdStr;
use model::document::FileType;
fn metadata() -> NewDocumentMetadata {
NewDocumentMetadata::new("test")
}
+ fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()
+ }
+
+ fn repo_kind() -> RepoDocumentKind {
+ RepoDocumentKind {
+ file_type: Some(FileType::Md),
+ sha: "sha".to_string(),
+ subtype: RepoDocumentSubtype::Regular,
+ team_id: None,
+ }
+ }
+
+ #[test]
+ fn creation_attribution_defaults_to_none() {
+ let args = metadata().into_repo_args(owner(), repo_kind());
+ assert_eq!(args.attribution, None);
+ assert_eq!(
+ args.resolved_attribution(),
+ Attribution::direct(Actor::new_from_user(owner()))
+ );
+ }
+
+ #[test]
+ fn email_attachment_create_resolves_to_the_system_principal() {
+ let args = NewDocumentMetadata::builder("invoice.pdf")
+ .email_attachment_id(uuid::Uuid::from_u128(1))
+ .build()
+ .into_repo_args(owner(), repo_kind());
+
+ assert_eq!(args.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(
+ args.resolved_attribution(),
+ Attribution::direct(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID))
+ );
+ }
+
+ #[test]
+ fn creation_attribution_can_be_set_without_changing_owner() {
+ let attribution =
+ Attribution::delegated(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID), owner());
+ let args = NewDocumentMetadata::builder("welcome")
+ .attribution(attribution.clone())
+ .build()
+ .into_repo_args(owner(), repo_kind());
+
+ assert_eq!(args.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(args.resolved_attribution(), attribution);
+ }
+
#[test]
fn new_plain_text_rejects_non_markdown_task() {
let err = NewPlainTextDocument::builder(metadata())
diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rs
index 9763a35998..e65deeafdb 100644
--- a/crates/documents/src/domain/events.rs
+++ b/crates/documents/src/domain/events.rs
@@ -7,6 +7,7 @@
#[cfg(test)]
mod test;
+use activity::Actor;
use chrono::{DateTime, Utc};
use document_sub_type::DocumentSubType;
use macro_event_broker::{Event, MacroEvent, TopicEvent};
@@ -25,6 +26,15 @@ pub struct DocumentCreatedMetadata {
pub document_id: String,
/// The owner (creator) of the document.
pub owner: MacroUserIdStr<'static>,
+ /// Who mechanically created the document. Absent on events published
+ /// before attribution: ingest then treats [`Self::owner`] as the actor.
+ #[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 creation belongs on, when different from
+ /// [`Self::actor`]. Absent means the actor is also the subject.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,
/// The document name, with any file extension stripped.
pub document_name: String,
/// File type of the document, when known.
diff --git a/crates/documents/src/domain/events/test.rs b/crates/documents/src/domain/events/test.rs
index c01f5694be..210393a8f8 100644
--- a/crates/documents/src/domain/events/test.rs
+++ b/crates/documents/src/domain/events/test.rs
@@ -184,6 +184,36 @@ fn search_event_constructors_use_the_document_key_and_schema_v1() {
);
}
+#[test]
+fn created_events_without_attribution_still_decode() {
+ let payload = json!({
+ "event_id": "00000000-0000-0000-0000-000000000005",
+ "schema_version": 1,
+ "event_type": "document.created",
+ "metadata": {
+ "document_id": DOCUMENT_ID,
+ "owner": "macro|[email protected]",
+ "document_name": "notes",
+ "file_type": null,
+ "project_id": null,
+ "sub_type": null,
+ "created_at": null,
+ },
+ });
+
+ let decoded: Event<DocumentTopicEvent> =
+ serde_json::from_value(payload).expect("pre-attribution created event decodes");
+
+ match decoded.event {
+ DocumentTopicEvent::Created(metadata) => {
+ assert_eq!(metadata.owner.as_ref(), "macro|[email protected]");
+ assert_eq!(metadata.actor, None);
+ assert_eq!(metadata.on_behalf_of, None);
+ }
+ other => panic!("expected created, got {other:?}"),
+ }
+}
+
#[test]
fn existing_v1_document_events_still_decode() {
let payload = json!({
diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rs
index 55b68d80f0..d7ab74e119 100644
--- a/crates/documents/src/domain/models.rs
+++ b/crates/documents/src/domain/models.rs
@@ -1,5 +1,6 @@
//! Domain models for the documents crate.
+use activity::{Actor, Attribution};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::DocumentResponseMetadata;
@@ -329,6 +330,24 @@ pub struct CreateDocumentRepoArgs {
pub sub_type: Option<document_sub_type::DocumentSubType>,
/// Whether to skip adding to user history.
pub skip_history: bool,
+ /// Explicit activity attribution. Unset uses [`Self::resolved_attribution`].
+ pub attribution: Option<Attribution>,
+}
+
+impl CreateDocumentRepoArgs {
+ /// Resolves who created this document for activity recording.
+ ///
+ /// Ownership (`user_id`) is unchanged. Email auto-imports default to
+ /// the system principal so they do not appear on the owner's feed.
+ pub fn resolved_attribution(&self) -> Attribution {
+ self.attribution.clone().unwrap_or_else(|| {
+ if self.email_attachment_id.is_some() {
+ Attribution::direct(Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID))
+ } else {
+ Attribution::direct(Actor::new_from_user(self.user_id.clone()))
+ }
+ })
+ }
}
/// Configuration for CloudFront presigned URL generation.
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index 99b1f16bb3..6b404f2098 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -1051,6 +1051,7 @@ impl<
let file_type = args.file_type;
let project_id = args.project_id;
let sha = args.sha.clone();
+ let attribution = args.resolved_attribution();
// The owner's team default link-share preference decides the initial
// share permission; without a team the per-file-type default applies.
@@ -1177,6 +1178,8 @@ impl<
DocumentCreatedMetadata {
document_id: document_metadata.document_id.clone(),
owner: document_metadata.owner.clone(),
+ actor: Some(attribution.actor()),
+ on_behalf_of: attribution.on_behalf_of(),
document_name: document_metadata.document_name.clone(),
file_type,
project_id: project_id.map(|p| p.to_string()),
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index b21de1b760..e870b753df 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -1904,6 +1904,7 @@ fn create_document_repo_args(file_type: FileType) -> CreateDocumentRepoArgs {
created_at: None,
sub_type: None,
skip_history: false,
+ attribution: None,
}
}
@@ -1991,6 +1992,52 @@ async fn create_document_repo_receives_disabled_share_when_team_turned_link_shar
.await;
}
+#[tokio::test]
+async fn create_document_publishes_resolved_attribution() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_team_default_link_share()
+ .returning(|_| Box::pin(std::future::ready(Ok(None))));
+ let created_metadata = make_test_metadata();
+ repo.expect_create_document()
+ .returning(move |_, _| Box::pin(std::future::ready(Ok(created_metadata.clone()))));
+ repo.expect_set_document_content()
+ .returning(|_, _| Box::pin(std::future::ready(Ok(()))));
+ repo.expect_get_team_task_metadata()
+ .returning(|_| Box::pin(std::future::ready(Ok(None))));
+
+ let (service, event_broker) = make_test_service_with_event_broker(repo);
+ let mut args = create_document_repo_args(FileType::Txt);
+ args.email_attachment_id = Some(uuid::Uuid::from_u128(7));
+
+ crate::domain::ports::DocumentService::create_document(
+ &service,
+ macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ args,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let published = event_broker.published();
+ let published = published.lock().unwrap();
+ assert_eq!(published[0].payload["event_type"], "document.created");
+ assert_eq!(
+ published[0].payload["metadata"]["owner"],
+ );
+ assert_eq!(
+ published[0].payload["metadata"]["actor"],
+ bot_id::MACRO_SYSTEM_BOT_ID.into_storage_id().as_ref()
+ );
+ assert!(
+ published[0].payload["metadata"]
+ .get("on_behalf_of")
+ .is_none()
+ );
+}
+
#[tokio::test]
async fn edited_interaction_bumps_document_before_publishing() {
let mut repo = make_mock_repo();
diff --git a/crates/documents/src/inbound/axum_router/create_document.rs b/crates/documents/src/inbound/axum_router/create_document.rs
index 1e7ef73aa3..a6900c8a51 100644
--- a/crates/documents/src/inbound/axum_router/create_document.rs
+++ b/crates/documents/src/inbound/axum_router/create_document.rs
@@ -102,6 +102,7 @@ pub async fn create_document_handler<
.is_task
.then_some(document_sub_type::DocumentSubType::Task),
skip_history: req.skip_history,
+ attribution: None,
};
let response_data = state
diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rs
index bd61eeadc0..cb1a9ceb00 100644
--- a/crates/documents/src/outbound/pg_document_repo.rs
+++ b/crates/documents/src/outbound/pg_document_repo.rs
@@ -430,6 +430,7 @@ impl DocumentRepo for PgDocumentRepo {
created_at: provided_created_at,
sub_type: requested_sub_type,
skip_history,
+ attribution: _,
} = args;
let now = chrono::Utc::now();
diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rs
index f4f57b8c29..aef50a34f4 100644
--- a/crates/documents/src/outbound/pg_document_repo/tests.rs
+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs
@@ -46,6 +46,7 @@ fn create_document_args(
created_at: None,
sub_type: is_task.then_some(document_sub_type::DocumentSubType::Task),
skip_history: false,
+ attribution: None,
}
}
diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
index 17c12083ce..2433af9da9 100644
--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
@@ -121,6 +121,8 @@ fn document_lifecycle_events_map_to_updated_and_deleted_patches() {
let created = DocumentTopicEvent::Created(DocumentCreatedMetadata {
document_id: DOCUMENT_ID.to_string(),
owner: user(),
+ actor: None,
+ on_behalf_of: None,
document_name: "Created".to_string(),
file_type: None,
project_id: None,
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index fe28ba09a8..10c4fd6a66 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -447,6 +447,8 @@ fn document_event_cases() -> Vec<EventCase> {
DocumentTopicEvent::Created(DocumentCreatedMetadata {
document_id: DOCUMENT_ID.to_string(),
owner: user_id("macro|[email protected]"),
+ actor: None,
+ on_behalf_of: None,
document_name: "notes".to_string(),
file_type: None,
project_id: None,
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 418329504a..528f86ee70 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -3742,6 +3742,11 @@ export type DocumentCopiedMetadata = {
* Metadata for [`DocumentTopicEvent::Created`].
*/
export type DocumentCreatedMetadata = {
+ /**
+ * Who mechanically created the document. Absent on events published
+ * before attribution: ingest then treats [`Self::owner`] as the actor.
+ */
+ actor?: string | null;
/**
* Creation timestamp reported by the repository.
*/
@@ -3755,6 +3760,7 @@ export type DocumentCreatedMetadata = {
*/
document_name: string;
file_type?: null | FileType;
+ on_behalf_of?: null | MacroUserIdStr;
/**
* The owner (creator) of the document.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 3b615d3ef3..07eab5243f 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -16474,6 +16474,10 @@
"description": "Metadata for [`DocumentTopicEvent::Created`].",
"required": ["document_id", "owner", "document_name"],
"properties": {
+ "actor": {
+ "type": ["string", "null"],
+ "description": "Who mechanically created the document. Absent on events published\nbefore attribution: ingest then treats [`Self::owner`] as the actor."
+ },
"created_at": {
"type": ["string", "null"],
"format": "date-time",
@@ -16498,6 +16502,17 @@
}
]
},
+ "on_behalf_of": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "The user whose feed this creation belongs on, when different from\n[`Self::actor`]. Absent means the actor is also the subject."
+ }
+ ]
+ },
"owner": {
"$ref": "#/components/schemas/MacroUserIdStr",
"description": "The owner (creator) of the document."
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index d22d9fb891..a4e05ff238 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -48,6 +48,7 @@ axum = { workspace = true, features = [
axum-extra = { workspace = true }
base64 = { workspace = true }
bots = { path = "../../crates/bots" }
+bot_id = { path = "../../crates/bot_id" }
bytes = { workspace = true }
calendar_events = { path = "../../crates/calendar_events", features = ["dispatch-sqs", "inbound", "notify", "postgres"] }
bzip2 = { workspace = true, default-features = false, features = [
diff --git a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
index 0c37477f7c..24fd7db075 100644
--- a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
+++ b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
@@ -1,4 +1,5 @@
use crate::api::context::{ApiContext, AuthorizationService};
+use activity::{Actor, Attribution};
use axum::{
extract::State,
response::{IntoResponse, Json, Response},
@@ -170,6 +171,10 @@ pub async fn handler(
tracing::info!("initialize starter docs");
let user_id = &user_context.authorization.user.macro_user_id;
+ let system_for_user = Attribution::delegated(
+ Actor::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),
+ user_id.clone(),
+ );
// Resolve every starter document's deterministic id up front so the
// templates can cross-link before any document has been created.
@@ -202,6 +207,7 @@ pub async fn handler(
NewMarkdownTextDocument {
metadata: NewDocumentMetadata::builder(task.name)
.id(starter_doc_id(user_id, task.name))
+ .attribution(system_for_user.clone())
.build(),
markdown: fill(task.template),
subtype: MarkdownSubtype::Task {
@@ -232,6 +238,7 @@ pub async fn handler(
NewMarkdownTextDocument {
metadata: NewDocumentMetadata::builder(HOW_TO_GUIDE_NAME)
.id(starter_doc_id(user_id, HOW_TO_GUIDE_NAME))
+ .attribution(system_for_user.clone())
.build(),
markdown: fill(HOW_TO_GUIDE_TEMPLATE),
subtype: MarkdownSubtype::Note,
diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
index f0b03cd5f5..8e67e701c7 100644
--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs
+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
@@ -828,6 +828,8 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>
DocumentTopicEvent::Created(DocumentCreatedMetadata {
document_id: DOCUMENT_ID.to_string(),
owner: owner.clone(),
+ actor: None,
+ on_behalf_of: None,
document_name: "Document".to_string(),
file_type: Some(FileType::Pdf),
project_id: Some(PROJECT_ID.to_string()),