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.

46.8 KB
Raw Blame
use super::{mentions::MessageReferenceKind, models::*, ports::*};
use channel_sender::ChannelSender;
use entity_access::domain::models::{
    AdminParticipantRole, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,
    EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole, OwnerAccessLevel,
    RequiredPermission, ViewAccessLevel, ViewOnly,
};
use uuid::Uuid;

#[cfg(test)]
mod test;
mod timeline;

/// Call-scoped guest conversation use cases.
pub mod guest_chat;

/// Minimum view permission for any supported message parent.
#[derive(Debug, Clone, Copy)]
pub struct MessageView;

impl RequiredPermission for MessageView {
    fn is_satisfied_by(permission: &EntityPermission) -> bool {
        permission.satisfies::<ViewAccessLevel>() || permission.satisfies::<ViewOnly>()
    }
}

/// Minimum posting permission: channel member or entity commenter.
#[derive(Debug, Clone, Copy)]
pub struct MessageWrite;

impl RequiredPermission for MessageWrite {
    fn is_satisfied_by(permission: &EntityPermission) -> bool {
        permission.satisfies::<CommentAccessLevel>()
            || permission.satisfies::<MemberParticipantRole>()
    }
}

/// Shared message use cases. Parent management and delivery are separate capabilities.
#[derive(Clone)]
pub struct MessageService<R, E> {
    activity: Option<std::sync::Arc<dyn activity::domain::timeline::ActivityTimeline>>,
    repo: R,
    events: E,
    references: std::sync::Arc<dyn MessageReferenceAccess>,
    mentions: std::sync::Arc<dyn MessageMentionExtractor>,
    groups: std::sync::Arc<dyn MessageGroupRecipients>,
}

impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
    /// Compose a service from persistence and delivery ports.
    pub fn new(repo: R, events: E) -> Self {
        Self {
            activity: None,
            repo,
            events,
            references: std::sync::Arc::new(DenyMessageReferences),
            mentions: std::sync::Arc::new(NoMessageMentionExtractor),
            groups: std::sync::Arc::new(NoMessageGroups),
        }
    }

    /// Supply the activity owner's read boundary for mixed parent timelines.
    pub fn with_activity(
        mut self,
        activity: impl activity::domain::timeline::ActivityTimeline,
    ) -> Self {
        self.activity = Some(std::sync::Arc::new(activity));
        self
    }

    /// Supply current channel membership for authored group mentions.
    pub fn with_group_recipients(mut self, groups: impl MessageGroupRecipients) -> Self {
        self.groups = std::sync::Arc::new(groups);
        self
    }

    /// Supply the reference access boundary for attachments and entity mentions.
    pub fn with_references(mut self, references: impl MessageReferenceAccess) -> Self {
        self.references = std::sync::Arc::new(references);
        self
    }

    /// Parse raw bot Markdown through the same reference boundary as editor messages.
    pub fn with_mention_extractor(mut self, mentions: impl MessageMentionExtractor) -> Self {
        self.mentions = std::sync::Arc::new(mentions);
        self
    }

    /// Read the same bounded message timeline for either parent.
    #[tracing::instrument(skip(self, access))]
    pub async fn timeline(
        &self,
        access: EntityAccessReceipt<MessageView>,
        query: MessageTimelineQuery,
    ) -> Result<MessagePage, MessageError> {
        async {
            let (parent, query) = self.timeline_selection(&access, query).await?;
            self.repo.timeline(&parent, query).await
        }
        .await
        .inspect_err(log_read_error)
    }

    /// Read a parent's messages and its timeline activity as one ordered page.
    /// Parents without a timeline activity source return their messages only.
    #[tracing::instrument(skip(self, access))]
    pub async fn timeline_entries(
        &self,
        access: EntityAccessReceipt<MessageView>,
        query: MessageTimelineQuery,
    ) -> Result<MessageTimelinePage, MessageError> {
        async {
            let (parent, query) = self.timeline_selection(&access, query).await?;
            let Some(source) = timeline_activity(&parent) else {
                return self.repo.timeline(&parent, query).await.map(Into::into);
            };
            // These filters select a subset of roots, and activity has no matching
            // filter, so the merged window would be wrong. Including deleted threads
            // only adds tombstones on the same keyset, so it combines with activity.
            if !query.ids.is_empty()
                || query.anchored.is_some()
                || query.activity_after.is_some()
                || query.activity_before.is_some()
            {
                return Err(MessageError::Invalid(
                    "activity timelines cannot be combined with message filters",
                ));
            }
            let page = self.activity_timeline(&parent, source, query).await?;
            self.with_call_entries(page).await
        }
        .await
        .inspect_err(log_read_error)
    }

    /// Validate a selection and resolve the parent it reads.
    async fn timeline_selection(
        &self,
        access: &EntityAccessReceipt<MessageView>,
        mut query: MessageTimelineQuery,
    ) -> Result<(MessageParent, MessageTimelineQuery), MessageError> {
        if query
            .activity_after
            .zip(query.activity_before)
            .is_some_and(|(from, to)| from >= to)
        {
            return Err(MessageError::Invalid("activity start must precede end"));
        }
        if query.around.is_some()
            && (!query.ids.is_empty()
                || query.anchored.is_some()
                || query.activity_after.is_some()
                || query.activity_before.is_some())
        {
            return Err(MessageError::Invalid(
                "centered windows cannot have filters",
            ));
        }
        let parent = parent_from_receipt(access)?;
        self.ensure_parent(&parent).await?;
        query.limit = Some(query.limit.unwrap_or(50).clamp(1, 100));
        if query.ids.len() > 100 || (query.around.is_some() && query.cursor.is_some()) {
            return Err(MessageError::Invalid("invalid timeline selection"));
        }
        Ok((parent, query))
    }

    /// Read a message and its canonical root for navigation.
    #[tracing::instrument(skip(self, access))]
    pub async fn get(
        &self,
        access: EntityAccessReceipt<MessageView>,
        id: Uuid,
    ) -> Result<Message, MessageError> {
        async {
            let parent = parent_from_receipt(&access)?;
            self.ensure_parent(&parent).await?;
            self.active_message(&parent, id, true).await
        }
        .await
        .inspect_err(log_read_error)
    }

    /// Open a specific discussion, including roots outside the current timeline page.
    #[tracing::instrument(skip(self, access))]
    pub async fn get_thread(
        &self,
        access: EntityAccessReceipt<MessageView>,
        root_id: Uuid,
    ) -> Result<MessageThread, MessageError> {
        async {
            let parent = parent_from_receipt(&access)?;
            self.ensure_parent(&parent).await?;
            let state = self.active_thread(&parent, root_id).await?;
            let root = self.active_message(&parent, root_id, true).await?;
            let replies = self.repo.replies(&parent, root_id).await?;
            Ok(MessageThread {
                state,
                root,
                replies,
            })
        }
        .await
        .inspect_err(log_read_error)
    }

    /// Load authorized history preceding a live prompt in this conversation.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn preceding(
        &self,
        access: EntityAccessReceipt<MessageView>,
        id: Uuid,
        limit: u16,
    ) -> Result<Vec<Message>, MessageError> {
        let parent = parent_from_receipt(&access)?;
        self.ensure_parent(&parent).await?;
        self.active_message(&parent, id, false).await?;
        self.repo.preceding(&parent, id, limit.clamp(1, 100)).await
    }

    /// Publish transient typing for an existing discussion.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn typing(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        root_id: Option<Uuid>,
        active: bool,
        nonce: Option<String>,
    ) -> Result<(), MessageError> {
        self.publish_typing(access, root_id, active, nonce, None)
            .await
    }

    /// Publish an agent session typing through the bot that speaks for it.
    /// Only a bot capability may say a session is typing: a person's typing
    /// never names one.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn agent_typing(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        root_id: Option<Uuid>,
        active: bool,
        agent: AgentTyping,
    ) -> Result<(), MessageError> {
        if !matches!(access.auth(), EntityAccessAuth::Bot(_)) {
            return Err(MessageError::Forbidden);
        }
        self.publish_typing(access, root_id, active, None, Some(agent))
            .await
    }

    async fn publish_typing(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        root_id: Option<Uuid>,
        active: bool,
        nonce: Option<String>,
        agent: Option<AgentTyping>,
    ) -> Result<(), MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        if let Some(root_id) = root_id {
            self.active_thread(&parent, root_id).await?;
        }
        self.publish(MessageEvent {
            parent,
            actor: actor.as_ref().to_owned(),
            nonce,
            change: MessageChange::Typing {
                thread_id: root_id,
                active,
                agent,
            },
        })
        .await;
        Ok(())
    }

    /// Post a root or reply with shared thread and anchor validation.
    #[tracing::instrument(err, skip(self, access, input))]
    pub async fn post(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        input: PostMessage,
    ) -> Result<Message, MessageError> {
        if let Some(id) = input.id {
            validate_client_id(id, chrono::Utc::now())?;
        }
        let parent = parent_from_receipt(&access)?;
        if !matches!(parent, MessageParent::Call(_)) {
            return self.post_validated(access, input).await;
        }
        let Some(client_message_id) = input.id else {
            return self.post_validated(access, input).await;
        };
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        // The first call message uses the call ID, so its submitted ID must be
        // resolved separately. Replays return persisted content without delivery.
        if let Some(message) = self
            .repo
            .get_by_client_message_id(&parent, &actor, client_message_id)
            .await?
        {
            return Ok(message);
        }
        match self.post_validated(access, input).await {
            Err(MessageError::Conflict) => self
                .repo
                .get_by_client_message_id(&parent, &actor, client_message_id)
                .await?
                .ok_or(MessageError::Conflict),
            result => result,
        }
    }

    /// Post a trusted server event once, including after long broker delays.
    /// Replays return the stored message even if its discussion was deleted;
    /// they never restore deleted content or publish another message event.
    #[tracing::instrument(err, skip(self, access, input))]
    pub async fn post_from_event(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        event_id: Uuid,
        mut input: PostMessage,
    ) -> Result<Message, MessageError> {
        validate_uuid_v7(event_id)?;
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        let thread_id = input.thread_id;
        if let Some(message) = self.repo.get(&parent, event_id).await? {
            return validate_event_message(message, &parent, &actor, thread_id);
        }
        input.id = Some(event_id);
        match self.post_validated(access, input).await {
            Err(MessageError::Conflict) => {
                let message = self
                    .repo
                    .get(&parent, event_id)
                    .await?
                    .ok_or(MessageError::Conflict)?;
                validate_event_message(message, &parent, &actor, thread_id)
            }
            result => result,
        }
    }

    async fn post_validated(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        mut input: PostMessage,
    ) -> Result<Message, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        if actor.as_bot().is_some() && input.mentions.is_empty() {
            input.mentions = self.mentions.extract(&input.content).await?;
        }
        validate_post(&parent, &input)?;
        if let Some((file_type, error)) = input.anchor.as_ref().and_then(required_file_type)
            && self
                .repo
                .document_file_type(&parent.entity_id())
                .await?
                .as_deref()
                != Some(file_type)
        {
            return Err(MessageError::Invalid(error));
        }
        input.mentions = self
            .validate_references(&access, input.mentions, &input.attachments)
            .await?;
        let canonical_root_id = match parent {
            MessageParent::Call(call_id) => {
                if input.thread_id.is_some_and(|root| root != call_id) {
                    return Err(MessageError::Invalid(
                        "call messages belong to the call thread",
                    ));
                }

                // A stale client must not write to a chat nobody will see.
                if self.repo.call_thread_facts(call_id).await?.is_some() {
                    return Err(MessageError::Invalid(
                        "this call's discussion is in its channel",
                    ));
                }

                Some(call_id)
            }
            _ => {
                if let Some(root) = input.thread_id {
                    self.active_thread_or_call_root(&parent, root).await?;
                }
                None
            }
        };
        let notification_policy = input.notification_policy;
        let nonce = input.nonce.clone();
        let mentions = self.resolve_mentions(&parent, &input.mentions).await?;
        let message = self
            .repo
            .create(CreateMessage {
                canonical_root_id,
                parent: parent.clone(),
                actor: actor.clone(),
                guest_name: None,
                kind: MessageKind::Message,
                triggered_by: match &input.attribution {
                    MessageAttribution::AccountManager { manager_user_id } => {
                        Some(manager_user_id.clone())
                    }
                    MessageAttribution::ActingUser
                    | MessageAttribution::ActingUserVia { .. }
                    | MessageAttribution::Unprompted => access
                        .acting_user_id()
                        .filter(|_| actor.as_bot().is_some() && input.attribution.has_acting_user())
                        .map(ToString::to_string),
                },
                triggered_via: match &input.attribution {
                    MessageAttribution::ActingUserVia { client } if actor.as_bot().is_some() => {
                        Some(client.clone())
                    }
                    MessageAttribution::ActingUserVia { .. }
                    | MessageAttribution::ActingUser
                    | MessageAttribution::AccountManager { .. }
                    | MessageAttribution::Unprompted => None,
                },
                input,
            })
            .await?;
        self.publish(MessageEvent {
            parent,
            actor: actor.as_ref().to_owned(),
            nonce,
            change: MessageChange::Posted {
                notification_policy,
                message: message.clone(),
                mentions,
            },
        })
        .await;
        Ok(message)
    }

    /// Create a channel call's thread root once, however often it is asked for.
    ///
    /// Takes no receipt because nothing here is the caller's to choose: the
    /// channel, sender and text all come from the call's own record, which only
    /// the call domain writes after checking channel access.
    #[tracing::instrument(err, skip(self), name = "call.discussion.create_root")]
    pub async fn ensure_call_root(&self, call_id: Uuid) -> Result<Message, MessageError> {
        let facts = self
            .repo
            .call_thread_facts(call_id)
            .await?
            .ok_or(MessageError::NotFound)?;
        let parent = MessageParent::Channel(facts.channel_id);
        if let Some(root) = self.repo.get(&parent, call_id).await? {
            return Ok(root);
        }

        let actor = ChannelSender::try_from(facts.created_by)
            .map_err(|_| MessageError::Invalid("the call has an invalid creator"))?;
        let created = self
            .repo
            .create(CreateMessage {
                canonical_root_id: None,
                parent: parent.clone(),
                actor: actor.clone(),
                guest_name: None,
                kind: MessageKind::CallRoot,
                triggered_by: None,
                triggered_via: None,
                input: PostMessage {
                    attribution: MessageAttribution::default(),
                    notification_policy: PostMessageNotificationPolicy::Silent,
                    id: Some(call_id),
                    content: CALL_ROOT_TEXT.to_owned(),
                    thread_id: None,
                    anchor: None,
                    mentions: vec![],
                    attachments: vec![],
                    nonce: None,
                },
            })
            .await;
        let message = match created {
            // The other request created it and delivers it.
            Err(MessageError::Conflict) => {
                return self
                    .repo
                    .get(&parent, call_id)
                    .await?
                    .ok_or(MessageError::Conflict);
            }
            result => result?,
        };

        self.publish(MessageEvent {
            parent,
            actor: actor.as_ref().to_owned(),
            nonce: None,
            change: MessageChange::CallRootPosted {
                message: message.clone(),
            },
        })
        .await;
        Ok(message)
    }

    /// Apply partial updates without requiring callers to reconstruct a message.
    #[tracing::instrument(err, skip(self, access, patch))]
    pub async fn patch(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        id: Uuid,
        patch: MessagePatch,
    ) -> Result<Message, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        let current = self.active_message(&parent, id, false).await?;
        reject_call_root(&current)?;
        if current.sender_id != actor
            && !(matches!(parent, MessageParent::Channel(_))
                && can_moderate(access.entity_permission()))
        {
            return Err(MessageError::Forbidden);
        }
        let attachments = match patch.attachments {
            AttachmentChange::Preserve => None,
            AttachmentChange::Replace(attachments) => Some(attachments),
            AttachmentChange::Delta { remove, add } => {
                let mut retained: Vec<_> = current
                    .attachments
                    .iter()
                    .filter(|attachment| !remove.contains(&attachment.id))
                    .map(|attachment| NewAttachment {
                        entity_type: attachment.entity_type.clone(),
                        entity_id: attachment.entity_id.clone(),
                        width: attachment.width,
                        height: attachment.height,
                    })
                    .collect();
                retained.extend(add);
                Some(retained)
            }
        };
        let mentions = patch.mentions.unwrap_or_else(|| {
            if patch.content.is_some() && actor.as_bot().is_some() {
                Vec::new()
            } else {
                current.mentions.clone()
            }
        });
        let mut input = EditMessage {
            content: patch.content.unwrap_or_else(|| current.content.clone()),
            mentions,
            attachments,
            nonce: patch.nonce,
            notification_policy: patch.notification_policy,
        };
        if actor.as_bot().is_some() && input.mentions.is_empty() {
            input.mentions = self.mentions.extract(&input.content).await?;
        }
        let has_attachments = input
            .attachments
            .as_ref()
            .map_or(!current.attachments.is_empty(), |a| !a.is_empty());
        if input.content.trim().is_empty() && !has_attachments {
            return Err(MessageError::Invalid(
                "a message needs content or an attachment",
            ));
        }
        input.mentions = self
            .validate_references(
                &access,
                input.mentions,
                input.attachments.as_deref().unwrap_or_default(),
            )
            .await?;
        // Reconciliation may repeat a bot's final reply after a process died
        // between patching it and recording success. Identical content must
        // not produce another edit event or completion notification.
        if actor.as_bot().is_some()
            && input.content == current.content
            && input.mentions == current.mentions
            && input.attachments.is_none()
        {
            return Ok(current);
        }
        let notification_policy = input.notification_policy;
        let nonce = input.nonce.clone();
        let mentions = self.resolve_mentions(&parent, &input.mentions).await?;
        let message = self.repo.edit(&parent, id, input).await?;
        self.publish(MessageEvent {
            parent,
            actor: actor.as_ref().to_owned(),
            nonce,
            change: MessageChange::Edited {
                notification_policy,
                message: message.clone(),
                mentions,
                previous_attachments: current.attachments,
            },
        })
        .await;
        Ok(message)
    }

    /// Delete one message. On a discussion, deleting the root deletes the discussion.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn delete(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        id: Uuid,
        nonce: Option<String>,
    ) -> Result<Message, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        let current = self.active_message(&parent, id, false).await?;
        reject_call_root(&current)?;
        // A comment's replies and its place in the document belong to the comment,
        // not to its first message, so the root carries the whole discussion with
        // it. Channel roots are one message in a conversation that continues
        // without them, and keep the tombstone the channel timeline renders.
        if parent.is_discussion() && current.thread_id.is_none() {
            self.delete_discussion(&access, &parent, &actor, id, nonce)
                .await?;
            return self
                .repo
                .get(&parent, id)
                .await?
                .ok_or(MessageError::NotFound);
        }
        let channel_bot =
            matches!(parent, MessageParent::Channel(_)) && current.sender_id.as_bot().is_some();
        if current.sender_id != actor && !can_moderate(access.entity_permission()) && !channel_bot {
            return Err(MessageError::Forbidden);
        }
        let message = self.repo.delete(&parent, id).await?;
        self.publish_message(
            actor,
            nonce,
            &message,
            MessageChange::MessageDeleted {
                message: message.clone(),
            },
        )
        .await;
        Ok(message)
    }

    /// Add or remove a reaction owned by the authenticated caller.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn react(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        id: Uuid,
        emoji: String,
        add: bool,
        nonce: Option<String>,
    ) -> Result<Message, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        self.ensure_parent(&parent).await?;
        let current = self.active_message(&parent, id, false).await?;
        reject_call_root(&current)?;
        if emoji.is_empty() || emoji.chars().count() > 32 || emoji.chars().any(char::is_control) {
            return Err(MessageError::Invalid("invalid reaction"));
        }
        let ReactionResult { message, changed } = self
            .repo
            .react(&parent, id, actor.as_ref(), &emoji, add)
            .await?;
        // Idempotent retries still return the current message to the caller,
        // but must not publish another change or notify the author again.
        if !changed {
            return Ok(message);
        }
        self.publish_message(
            actor,
            nonce,
            &message,
            MessageChange::ReactionChanged {
                message: message.clone(),
                emoji,
                added: add,
            },
        )
        .await;
        Ok(message)
    }

    /// Update a discussion; detaching document text requires edit access.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn patch_thread(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        root_id: Uuid,
        patch: ThreadPatch,
    ) -> Result<ThreadState, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        if !parent.is_discussion() {
            return Err(MessageError::Invalid(
                "only entity discussions support thread updates",
            ));
        }
        self.ensure_parent(&parent).await?;
        let thread = self.active_thread(&parent, root_id).await?;
        if patch.resolved.is_none() && !patch.detach_anchor {
            return Err(MessageError::Invalid("thread update must change a field"));
        }
        if patch.detach_anchor {
            if !matches!(parent, MessageParent::Document(_)) {
                return Err(MessageError::Invalid(
                    "only document discussions have anchors",
                ));
            }
            if !access.entity_permission().satisfies::<EditAccessLevel>() {
                return Err(MessageError::Forbidden);
            }
            if !matches!(thread.anchor, None | Some(ThreadAnchor::Markdown { .. })) {
                return Err(MessageError::Invalid(
                    "only Markdown text anchors can be detached",
                ));
            }
        }
        let nonce = patch.nonce.clone();
        let state = self.repo.patch_thread(&parent, root_id, patch).await?;
        self.publish(MessageEvent {
            parent,
            actor: actor.as_ref().to_owned(),
            nonce,
            change: MessageChange::ThreadUpdated {
                state: state.clone(),
            },
        })
        .await;
        Ok(state)
    }

    /// Explicitly delete a discussion, including all its replies.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn delete_thread(
        &self,
        access: EntityAccessReceipt<MessageWrite>,
        root_id: Uuid,
        nonce: Option<String>,
    ) -> Result<ThreadState, MessageError> {
        let parent = parent_from_receipt(&access)?;
        let actor = actor_from_receipt(&access, &parent)?;
        if !parent.is_discussion() {
            return Err(MessageError::Invalid(
                "only entity discussions support whole-thread deletion",
            ));
        }
        self.ensure_parent(&parent).await?;
        self.delete_discussion(&access, &parent, &actor, root_id, nonce)
            .await
    }

    /// The one teardown policy: whoever may delete a discussion outright is
    /// whoever may delete it by deleting its root, since both take replies
    /// written by other people with them.
    async fn delete_discussion(
        &self,
        access: &EntityAccessReceipt<MessageWrite>,
        parent: &MessageParent,
        actor: &ChannelSender<'static>,
        root_id: Uuid,
        nonce: Option<String>,
    ) -> Result<ThreadState, MessageError> {
        let thread = self.active_thread(parent, root_id).await?;
        if thread.user_id != actor.as_ref() && !can_moderate(access.entity_permission()) {
            return Err(MessageError::Forbidden);
        }
        let state = self.repo.delete_thread(parent, root_id).await?;
        self.publish(MessageEvent {
            parent: parent.clone(),
            actor: actor.as_ref().to_owned(),
            nonce,
            change: MessageChange::ThreadUpdated {
                state: state.clone(),
            },
        })
        .await;
        Ok(state)
    }

    /// The parent a live message belongs to, so an adapter addressed only by
    /// message id can mint that parent's receipt. Grants nothing on its own.
    #[tracing::instrument(err, skip(self))]
    pub async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError> {
        self.repo.parent_of(id).await
    }

    /// Resolve an old link through the sole message store under current parent access.
    #[tracing::instrument(err, skip(self, access))]
    pub async fn resolve_legacy(
        &self,
        access: EntityAccessReceipt<MessageView>,
        id: i64,
        is_thread: bool,
    ) -> Result<Message, MessageError> {
        let parent = parent_from_receipt(&access)?;
        self.ensure_parent(&parent).await?;
        let id = self
            .repo
            .resolve_legacy(&parent, id, is_thread)
            .await?
            .ok_or(MessageError::NotFound)?;
        self.active_message(&parent, id, true).await
    }

    async fn resolve_mentions(
        &self,
        parent: &MessageParent,
        authored: &[SimpleMention],
    ) -> Result<Vec<SimpleMention>, MessageError> {
        let mut seen = std::collections::HashSet::new();
        let mut resolved = Vec::new();
        let mut group_members = None;
        for mention in authored {
            if MessageReferenceKind::parse(&mention.entity_type)
                == Some(MessageReferenceKind::Group)
            {
                let MessageParent::Channel(channel) = parent else {
                    return Err(MessageError::Invalid("group mentions require a channel"));
                };
                if group_members.is_none() {
                    group_members = Some(self.groups.channel_members(*channel).await?);
                }
                for user in group_members.as_ref().unwrap() {
                    let user = SimpleMention::user(user);
                    if seen.insert((user.entity_type.clone(), user.entity_id.clone())) {
                        resolved.push(user);
                    }
                }
            } else if seen.insert((mention.entity_type.clone(), mention.entity_id.clone())) {
                resolved.push(mention.clone());
            }
        }
        Ok(resolved)
    }

    /// Rejects malformed references and attachments the sender cannot view, and
    /// returns the mentions to record. A mention of something the sender cannot
    /// view stays in the content but is not recorded, so it shares, notifies,
    /// and triggers nothing.
    async fn validate_references(
        &self,
        access: &EntityAccessReceipt<MessageWrite>,
        mentions: Vec<SimpleMention>,
        attachments: &[NewAttachment],
    ) -> Result<Vec<SimpleMention>, MessageError> {
        if attachments.len() > 10 || mentions.len() > 100 {
            return Err(MessageError::Invalid("too many message references"));
        }
        for attachment in attachments {
            if attachment.width.is_some_and(|n| n <= 0) || attachment.height.is_some_and(|n| n <= 0)
            {
                return Err(MessageError::Invalid("invalid attachment dimensions"));
            }
        }
        let mut checked = std::collections::HashSet::new();
        let mut hidden = std::collections::HashSet::new();
        for (raw_kind, id, mention) in mentions
            .iter()
            .map(|m| (m.entity_type.as_str(), m.entity_id.as_str(), true))
            .chain(
                attachments
                    .iter()
                    .map(|a| (a.entity_type.as_str(), a.entity_id.as_str(), false)),
            )
        {
            if !checked.insert((raw_kind, id, mention)) {
                continue;
            }
            // Editors also emit display-only chips (dates, contacts, colors) as
            // mentions. They name nothing that can be authorized, so they are
            // stored as written, exactly as the channel writer did before.
            let Some(kind) = MessageReferenceKind::parse(raw_kind) else {
                continue;
            };
            let entity_type = match kind {
                MessageReferenceKind::User if mention => {
                    // Macro AI is surfaced through the user mention UI. Other bots
                    // use the explicit bot tag, which the trigger service authorizes.
                    let sender = ChannelSender::try_from(id)
                        .map_err(|_| MessageError::Invalid("invalid mentioned user"))?;
                    if sender
                        .as_bot()
                        .is_some_and(|bot| bot.bot_id() != bot_id::MACRO_AI_BOT_ID)
                    {
                        return Err(MessageError::Invalid("bot mentions require the bot tag"));
                    }
                    continue;
                }
                MessageReferenceKind::Bot if mention => {
                    bot_id::BotIdStr::try_from(id)
                        .map_err(|_| MessageError::Invalid("invalid mentioned bot"))?;
                    continue;
                }
                // Static media is already readable by any authenticated user who
                // has its UUID, matching static_file_service's read policy.
                MessageReferenceKind::StaticImage | MessageReferenceKind::StaticVideo
                    if !mention =>
                {
                    Uuid::parse_str(id)
                        .map_err(|_| MessageError::Invalid("invalid media identifier"))?;
                    continue;
                }
                MessageReferenceKind::Group
                    if mention
                        && id == "here"
                        && access.entity().entity_type == EntityType::Channel =>
                {
                    continue;
                }
                MessageReferenceKind::Automation => continue,
                MessageReferenceKind::Document => EntityType::Document,
                MessageReferenceKind::Form => EntityType::Form,
                MessageReferenceKind::Channel => EntityType::Channel,
                MessageReferenceKind::EmailThread => EntityType::EmailThread,
                MessageReferenceKind::Call => EntityType::Call,
                MessageReferenceKind::CalendarEvent => EntityType::CalendarEvent,
                MessageReferenceKind::Chat => EntityType::Chat,
                MessageReferenceKind::AgentSession => EntityType::AgentSession,
                MessageReferenceKind::Project => EntityType::Project,
                MessageReferenceKind::CrmCompany => EntityType::CrmCompany,
                MessageReferenceKind::CrmContact => EntityType::CrmContact,
                MessageReferenceKind::ExternalChat => EntityType::ExternalChat,
                _ => return Err(MessageError::Invalid("unsupported message reference")),
            };
            if !self
                .references
                .can_view(access.auth(), entity_type, id)
                .await?
            {
                if !mention {
                    return Err(MessageError::Forbidden);
                }
                hidden.insert((raw_kind.to_owned(), id.to_owned()));
            }
        }
        Ok(mentions
            .into_iter()
            .filter(|m| !hidden.contains(&(m.entity_type.clone(), m.entity_id.clone())))
            .collect())
    }

    async fn ensure_parent(&self, parent: &MessageParent) -> Result<(), MessageError> {
        if !self.repo.parent_exists(parent).await? {
            return Err(MessageError::NotFound);
        }
        Ok(())
    }

    async fn active_thread(
        &self,
        parent: &MessageParent,
        root: Uuid,
    ) -> Result<ThreadState, MessageError> {
        let thread = self
            .repo
            .thread(parent, root)
            .await?
            .ok_or(MessageError::NotFound)?;
        if thread.deleted_at.is_some() {
            return Err(MessageError::NotFound);
        }
        Ok(thread)
    }

    /// A reply's root, creating a call's root first if posting it failed when
    /// the call started.
    async fn active_thread_or_call_root(
        &self,
        parent: &MessageParent,
        root: Uuid,
    ) -> Result<ThreadState, MessageError> {
        match self.active_thread(parent, root).await {
            Err(MessageError::NotFound) => {
                let facts = self.repo.call_thread_facts(root).await?;
                let in_this_channel =
                    facts.is_some_and(|facts| MessageParent::Channel(facts.channel_id) == *parent);
                if !in_this_channel {
                    return Err(MessageError::NotFound);
                }

                self.ensure_call_root(root).await?;
                self.active_thread(parent, root).await
            }
            result => result,
        }
    }

    async fn active_message(
        &self,
        parent: &MessageParent,
        id: Uuid,
        tombstone: bool,
    ) -> Result<Message, MessageError> {
        let message = self
            .repo
            .get(parent, id)
            .await?
            .ok_or(MessageError::NotFound)?;
        if message.parent != *parent || (!tombstone && message.deleted_at.is_some()) {
            return Err(MessageError::NotFound);
        }
        self.active_thread(parent, message.root_id()).await?;
        Ok(message)
    }

    async fn publish_message(
        &self,
        actor: ChannelSender<'static>,
        nonce: Option<String>,
        message: &Message,
        change: MessageChange,
    ) {
        self.publish(MessageEvent {
            parent: message.parent.clone(),
            actor: actor.as_ref().to_owned(),
            nonce,
            change,
        })
        .await;
    }

    async fn publish(&self, event: MessageEvent) {
        // The transaction has committed. Reporting failure to the caller would encourage
        // duplicate posts; reconnect/refetch also reconciles a missed transient update.
        let _ = self.events.publish(event).await.inspect_err(|e| {
            tracing::error!(error=?e, "failed to deliver committed message event");
        });
    }
}

/// Parent moderation beyond authorship.
///
/// A document owner may delete any comment on that document, including a
/// discussion they did not start. Channel admins and owners may moderate
/// channel messages the same way. Edit and comment access do not.
fn can_moderate(permission: &EntityPermission) -> bool {
    permission.satisfies::<OwnerAccessLevel>() || permission.satisfies::<AdminParticipantRole>()
}

/// Logs a failed read in the current span.
///
/// Unlike `#[instrument(err)]`, whose level is fixed, this keeps refusals at
/// INFO: clients and agents read messages, threads, and parents that were
/// deleted under them. Repository failures stay at ERROR.
fn log_read_error(error: &MessageError) {
    match error {
        MessageError::Repository(_) => tracing::error!(error = %error),
        MessageError::NotFound
        | MessageError::Forbidden
        | MessageError::Invalid(_)
        | MessageError::Conflict => tracing::info!(error = %error),
    }
}

fn parent_from_receipt<P: RequiredPermission>(
    access: &EntityAccessReceipt<P>,
) -> Result<MessageParent, MessageError> {
    let entity = access.entity();
    let kind = match entity.entity_type {
        EntityType::Channel => "channel",
        EntityType::Document => "document",
        EntityType::Initiative => "initiative",
        EntityType::CrmCompany => "crm_company",
        EntityType::CrmContact => "crm_contact",
        EntityType::Call => "call",
        _ => return Err(MessageError::Forbidden),
    };
    MessageParent::parse(kind, &entity.entity_id)
        .map_err(|_| MessageError::Invalid("invalid message parent"))
}

/// A call's root stands for the call, so nobody can change it, its author
/// included. People talk about the call in its thread.
fn reject_call_root(message: &Message) -> Result<(), MessageError> {
    if message.kind == MessageKind::CallRoot {
        return Err(MessageError::Forbidden);
    }
    Ok(())
}

fn actor_from_receipt<P: RequiredPermission>(
    access: &EntityAccessReceipt<P>,
    _parent: &MessageParent,
) -> Result<ChannelSender<'static>, MessageError> {
    let id = match access.auth() {
        EntityAccessAuth::Authenticated(user) => user.as_ref(),
        EntityAccessAuth::Bot(bot) => bot.bot_id_str().as_ref(),
        _ => return Err(MessageError::Forbidden),
    };
    ChannelSender::try_from(id.to_owned()).map_err(|_| MessageError::Forbidden)
}

fn validate_post(parent: &MessageParent, input: &PostMessage) -> Result<(), MessageError> {
    if input.content.trim().is_empty() && input.attachments.is_empty() {
        return Err(MessageError::Invalid(
            "a message needs content or an attachment",
        ));
    }
    if input.anchor.is_some()
        && (input.thread_id.is_some() || !matches!(parent, MessageParent::Document(_)))
    {
        return Err(MessageError::Invalid(
            "only root document messages may have anchors",
        ));
    }
    if let Some(NewThreadAnchor::Spreadsheet {
        sheet_id, range, ..
    }) = &input.anchor
        && (sheet_id.trim().is_empty() || !valid_spreadsheet_range(range))
    {
        return Err(MessageError::Invalid("invalid spreadsheet comment range"));
    }
    if let Some(NewThreadAnchor::PdfPlaceable {
        page,
        x_pct,
        y_pct,
        width_pct,
        height_pct,
        ..
    }) = input.anchor
        && (page < 0
            || ![x_pct, y_pct, width_pct, height_pct]
                .iter()
                .all(|x| x.is_finite())
            || width_pct <= 0.0
            || height_pct <= 0.0)
    {
        return Err(MessageError::Invalid("invalid PDF comment geometry"));
    }
    if let Some(NewThreadAnchor::Fig {
        page_id,
        node_id,
        x,
        y,
    }) = &input.anchor
        && (!valid_fig_anchor_id(page_id)
            || !node_id.as_deref().is_none_or(valid_fig_anchor_id)
            || !x.is_finite()
            || !y.is_finite())
    {
        return Err(MessageError::Invalid("invalid design comment position"));
    }
    Ok(())
}

/// Longest page or layer id a design anchor may carry. Figma ids are short
/// (`12:34`, or a `;`-joined path for a layer inside nested instances).
/// What a call's root says to anything that reads it as a plain message: search
/// results, notification previews, agents and the channel list.
const CALL_ROOT_TEXT: &str = "started a call";

const FIG_ANCHOR_ID_LIMIT: usize = 512;

/// The document file type an anchor kind belongs to, with the error for any
/// other document. Markdown and PDF anchors are tied to their documents by
/// the annotations and marks they name instead.
fn required_file_type(anchor: &NewThreadAnchor) -> Option<(&'static str, &'static str)> {
    match anchor {
        NewThreadAnchor::Spreadsheet { .. } => Some((
            "spreadsheet",
            "spreadsheet anchors require a native spreadsheet",
        )),
        NewThreadAnchor::Fig { .. } => Some(("fig", "fig anchors require a design")),
        NewThreadAnchor::Markdown { .. }
        | NewThreadAnchor::PdfHighlight { .. }
        | NewThreadAnchor::PdfPlaceable { .. } => None,
    }
}

fn valid_fig_anchor_id(id: &str) -> bool {
    !id.trim().is_empty() && id.len() <= FIG_ANCHOR_ID_LIMIT
}

fn valid_spreadsheet_range(range: &str) -> bool {
    let cells: Vec<_> = range.split(':').collect();
    (1..=2).contains(&cells.len())
        && cells.iter().all(|cell| {
            let column_len = cell.bytes().take_while(u8::is_ascii_uppercase).count();
            let (column, row) = cell.split_at(column_len);
            !column.is_empty()
                && !row.starts_with('0')
                && row.bytes().all(|byte| byte.is_ascii_digit())
                && row.parse::<u32>().is_ok_and(|value| value > 0)
                && column
                    .bytes()
                    .try_fold(0_u32, |value, byte| {
                        value
                            .checked_mul(26)?
                            .checked_add(u32::from(byte - b'A') + 1)
                    })
                    .is_some()
        })
}

fn validate_event_message(
    message: Message,
    parent: &MessageParent,
    actor: &ChannelSender<'static>,
    thread_id: Option<Uuid>,
) -> Result<Message, MessageError> {
    if message.parent != *parent || message.sender_id != *actor || message.thread_id != thread_id {
        return Err(MessageError::Conflict);
    }
    Ok(message)
}

fn validate_uuid_v7(id: Uuid) -> Result<chrono::DateTime<chrono::Utc>, MessageError> {
    id.get_timestamp()
        .filter(|_| id.get_version_num() == 7)
        .and_then(|timestamp| {
            let (seconds, nanos) = timestamp.to_unix();
            chrono::DateTime::from_timestamp(i64::try_from(seconds).ok()?, nanos)
        })
        .ok_or(MessageError::Invalid("message id must be a UUIDv7"))
}

/// How far a client-minted id's timestamp may drift from the server clock.
/// Ordering uses the server's `created_at`, so this only needs to catch forged
/// ids; it is wide so a device with a wrong clock can still post.
const CLIENT_ID_MAX_SKEW: chrono::TimeDelta = chrono::TimeDelta::days(1);

/// A client-minted id must be a UUIDv7 stamped near now, so its embedded time
/// stays roughly the message's creation time.
fn validate_client_id(id: Uuid, now: chrono::DateTime<chrono::Utc>) -> Result<(), MessageError> {
    let minted_at = validate_uuid_v7(id)?;
    if (now - minted_at).abs() > CLIENT_ID_MAX_SKEW {
        return Err(MessageError::Invalid(
            "message id timestamp is too far from the server clock",
        ));
    }
    Ok(())
}