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.

53.9 KB
Raw Blame
use super::*;

#[cfg(feature = "admission")]
mod admission;
mod call;
mod configured_agent;
mod task_assignment;

use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{AgentSession, AgentSessionId, SessionStatus, ThreadSession};
use agent_session::domain::ports::MockAgentSessionRepo;
use bots::domain::models::{Agent, AgentChannelScope, AgentMcpServers, Bot, BotKind, BotOwner};
use channel_sender::ChannelSender;
use chrono::Utc;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use messages::domain::models::SimpleMention;

use crate::domain::broker_events::TriggerDecision;

fn user() -> MacroUserIdStr<'static> {
    MacroUserIdStr::parse_from_str("macro|[email protected]")
        .expect("valid user id")
        .into_owned()
}

fn mention_of(bot: BotId) -> SimpleMention {
    SimpleMention {
        entity_type: "bot".to_owned(),
        entity_id: bot.into_storage_id().as_ref().to_owned(),
    }
}

fn owned_bot(bot_id: BotId, owner: BotOwner) -> Bot {
    Bot {
        id: bot_id,
        kind: BotKind::Owned,
        owner: Some(owner),
        name: format!("Agent {bot_id}"),
        handle: format!("agent-{bot_id}"),
        description: None,
        avatar_url: None,
        created_by: Some(user().as_ref().to_owned()),
        created_at: Utc::now(),
        updated_at: Utc::now(),
        deleted_at: None,
        has_agent: true,
    }
}

fn private_agent(bot_id: BotId) -> Agent {
    agent_with(
        bot_id,
        BotOwner::User {
            user_id: user().as_ref().to_owned(),
        },
        AgentChannelScope::All,
    )
}

fn agent_with(bot_id: BotId, owner: BotOwner, channel_scope: AgentChannelScope) -> Agent {
    Agent {
        bot: owned_bot(bot_id, owner),
        instructions: String::new(),
        harness: "in-memory".to_owned(),
        harness_id: None,
        default_model: "model".to_owned(),
        channel_scope,
        channel_ids: vec![],
        mcp: AgentMcpServers::OwnerConnections,
        auto_accept_permissions: None,
        is_coding: false,
    }
}

fn system_bot(bot_id: BotId) -> Bot {
    Bot {
        id: bot_id,
        kind: BotKind::System,
        owner: None,
        name: "System agent".to_owned(),
        handle: "system-agent".to_owned(),
        description: None,
        avatar_url: None,
        created_by: None,
        created_at: Utc::now(),
        updated_at: Utc::now(),
        deleted_at: None,
        has_agent: true,
    }
}

fn message(mentions: Vec<SimpleMention>) -> MessagePostedMetadata {
    MessagePostedMetadata {
        parent: messages::domain::models::MessageParent::Channel(Uuid::from_u128(1)),
        message_id: Uuid::from_u128(2),
        thread_id: Some(Uuid::from_u128(3)),
        root_id: Uuid::from_u128(3),
        sender: ChannelSender::new_from_user(user()),
        triggered_by: None,
        content: "hello".to_owned(),
        mentions,
        attachments: vec![],
        created_at: Utc::now(),
    }
}

fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
    AgentSession {
        origin: Default::default(),
        repo_branch: None,
        pull_request_url: None,
        task_id: None,
        id,
        name: agent_session::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),
        archived: None,
        owner_id: model_owner::Owner::User(
            MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),
        ),
        thread_id: Some(Uuid::from_u128(3)),
        thread_parent: Some(MessageParent::Channel(Uuid::from_u128(1))),
        originating_message_id: None,
        bot_id,
        model: "model".to_owned(),
        harness: "harness".to_owned(),
        repo_url: Some("https://example.com/repo".to_owned()),
        workspace: "/workspace".to_owned(),
        sandbox_size: agent_session::domain::model::SandboxSize::Default,
        instructions: None,
        mcp_servers: Default::default(),
        acp_session_id: None,
        external: None,
        status: SessionStatus::NoMessages,
        created_at: Utc::now(),
        modified_at: Utc::now(),
        source: agent_session::domain::model::SessionSource::User,
        visibility: agent_session::domain::model::SessionVisibility::Listed,
    }
}

/// A session rooted at the test message's thread.
fn thread_session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
    AgentSession {
        origin: Default::default(),
        thread_id: Some(Uuid::from_u128(3)),
        originating_message_id: Some(Uuid::from_u128(3)),
        ..session(id, bot_id)
    }
}

type TestService = AgentTriggerService<
    MockAgentSessionRepo,
    MockAgentBotLookup,
    MockTeamMembershipLookup,
    MockChannelParticipationLookup,
    MockExplicitReplyExtractor,
    MockImplicitTriggerJudge,
    MockThreadHistory,
>;

/// Mocks holding the three fact ports one test scenario needs. Defaults to no
/// expectations, so any unplanned membership or participation call fails.
struct FactMocks {
    bots: MockAgentBotLookup,
    teams: MockTeamMembershipLookup,
    channels: MockChannelParticipationLookup,
}

impl From<MockAgentBotLookup> for FactMocks {
    fn from(bots: MockAgentBotLookup) -> Self {
        Self {
            bots,
            teams: MockTeamMembershipLookup::new(),
            channels: MockChannelParticipationLookup::new(),
        }
    }
}

/// A service over a thread that reads as empty; tests that care about thread
/// context pass their own history with [`service_reading`].
fn service(
    sessions: MockAgentSessionRepo,
    facts: impl Into<FactMocks>,
    replies: MockExplicitReplyExtractor,
    judge: MockImplicitTriggerJudge,
) -> TestService {
    service_reading(sessions, facts, replies, judge, thread_of(vec![]))
}

fn service_reading(
    sessions: MockAgentSessionRepo,
    facts: impl Into<FactMocks>,
    replies: MockExplicitReplyExtractor,
    judge: MockImplicitTriggerJudge,
    history: MockThreadHistory,
) -> TestService {
    let facts = facts.into();
    AgentTriggerService::new(
        sessions,
        facts.bots,
        facts.teams,
        facts.channels,
        replies,
        judge,
        history,
    )
}

fn allow_invocation(
    user: &MacroUserIdStr<'static>,
    parent: &MessageParent,
    root_id: Uuid,
) -> std::pin::Pin<Box<dyn Future<Output = Result<Option<AuthorizedInvocation>>> + Send>> {
    use entity_access::domain::models::{AccessLevel, Entity, EntityPermission, ParticipantRole};
    let access = EntityAccessReceipt::try_new_authenticated_user(
        user.clone(),
        Entity {
            entity_type: parent.access_entity_type(),
            entity_id: parent.entity_id(),
        },
        match parent {
            MessageParent::Channel(_) => EntityPermission::ChannelRole {
                role: ParticipantRole::Member,
            },
            MessageParent::Document(_)
            | MessageParent::Call(_)
            | MessageParent::Initiative(_)
            | MessageParent::CrmCompany(_)
            | MessageParent::CrmContact(_) => EntityPermission::AccessLevel {
                access_level: AccessLevel::Comment,
            },
        },
    )
    .unwrap();
    Box::pin(async move { Ok(Some(AuthorizedInvocation { access, root_id })) })
}

/// A history that reads the given messages for any thread.
fn thread_of(messages: Vec<ThreadMessage>) -> MockThreadHistory {
    let mut history = MockThreadHistory::new();
    history
        .expect_authorize_invocation()
        .returning(allow_invocation);
    history.expect_thread_messages().returning(move |_| {
        let messages = messages.clone();
        Box::pin(async move { Ok(messages) })
    });
    history
}

/// Mocks for tests whose message never reaches the implicit path; any call is
/// a test failure.
fn no_implicit() -> (MockExplicitReplyExtractor, MockImplicitTriggerJudge) {
    (
        MockExplicitReplyExtractor::new(),
        MockImplicitTriggerJudge::new(),
    )
}

/// The one existing-session decision an evaluation yielded.
struct ExistingDecision {
    bot_id: BotId,
    session_id: AgentSessionId,
    kind: ThreadMessageKind,
    message: MessagePostedMetadata,
}

fn existing_channel_metadata(events: &[TriggerDecision]) -> ExistingDecision {
    assert_eq!(events.len(), 1);
    let TriggerDecision::Existing {
        bot_id,
        session_id,
        kind,
        message,
    } = &events[0]
    else {
        panic!("expected an existing-session decision, got {:?}", events[0]);
    };
    ExistingDecision {
        bot_id: *bot_id,
        session_id: *session_id,
        kind: *kind,
        message: message.clone(),
    }
}

fn sessions_without_existing() -> MockAgentSessionRepo {
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .once()
        .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
    sessions
}

async fn mention_yields_event(posted: &MessagePostedMetadata, facts: impl Into<FactMocks>) -> bool {
    let (replies, judge) = no_implicit();
    !service(sessions_without_existing(), facts, replies, judge)
        .evaluate(posted)
        .await
        .expect("evaluate message")
        .is_empty()
}

#[tokio::test]
async fn a_private_global_agent_is_unavailable_to_another_user() {
    let mut posted = message(vec![mention_of(BotId::TEST_A)]);
    posted.sender = ChannelSender::new_from_user(
        MacroUserIdStr::try_from_email("[email protected]").expect("valid user id"),
    );
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));

    assert!(!mention_yields_event(&posted, bots).await);
}

#[tokio::test]
async fn an_unattributed_bot_mention_cannot_trigger_an_agent() {
    let mut posted = message(vec![mention_of(BotId::TEST_A)]);
    posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
    let (replies, judge) = no_implicit();
    let service = service(
        MockAgentSessionRepo::new(),
        MockAgentBotLookup::new(),
        replies,
        judge,
    );
    assert!(service.evaluate(&posted).await.unwrap().is_empty());
}

#[tokio::test]
async fn a_team_global_agent_is_available_to_a_team_member() {
    let team_id = Uuid::from_u128(99);
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent().once().return_once(move |bot_id| {
        Box::pin(async move {
            Ok(Some(agent_with(
                bot_id,
                BotOwner::Team { team_id },
                AgentChannelScope::All,
            )))
        })
    });
    let mut facts = FactMocks::from(bots);
    facts
        .teams
        .expect_user_has_team()
        .with(
            mockall::predicate::eq(user()),
            mockall::predicate::eq(team_id),
        )
        .once()
        .return_once(|_, _| Box::pin(async { Ok(true) }));

    assert!(mention_yields_event(&posted, facts).await);
}

#[tokio::test]
async fn a_team_global_agent_is_unavailable_outside_its_team() {
    let team_id = Uuid::from_u128(99);
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent().once().return_once(move |bot_id| {
        Box::pin(async move {
            Ok(Some(agent_with(
                bot_id,
                BotOwner::Team { team_id },
                AgentChannelScope::All,
            )))
        })
    });
    let mut facts = FactMocks::from(bots);
    facts
        .teams
        .expect_user_has_team()
        .once()
        .return_once(|_, _| Box::pin(async { Ok(false) }));

    assert!(!mention_yields_event(&posted, facts).await);
}

#[tokio::test]
async fn a_selected_agent_requires_active_channel_membership() {
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent().once().return_once(|bot_id| {
        Box::pin(async move {
            Ok(Some(agent_with(
                bot_id,
                BotOwner::User {
                    user_id: "macro|[email protected]".to_owned(),
                },
                AgentChannelScope::Selected,
            )))
        })
    });
    let mut facts = FactMocks::from(bots);
    facts
        .channels
        .expect_bot_active_in_channel()
        .with(
            mockall::predicate::eq(Uuid::from_u128(1)),
            mockall::predicate::eq(BotId::TEST_A),
        )
        .once()
        .return_once(|_, _| Box::pin(async { Ok(false) }));

    assert!(!mention_yields_event(&posted, facts).await);
}

#[tokio::test]
async fn an_active_selected_agent_is_available_to_channel_members() {
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent().once().return_once(|bot_id| {
        Box::pin(async move {
            Ok(Some(agent_with(
                bot_id,
                BotOwner::User {
                    user_id: "macro|[email protected]".to_owned(),
                },
                AgentChannelScope::Selected,
            )))
        })
    });
    let mut facts = FactMocks::from(bots);
    facts
        .channels
        .expect_bot_active_in_channel()
        .with(
            mockall::predicate::eq(Uuid::from_u128(1)),
            mockall::predicate::eq(BotId::TEST_A),
        )
        .once()
        .return_once(|_, _| Box::pin(async { Ok(true) }));

    assert!(mention_yields_event(&posted, facts).await);
}

#[tokio::test]
async fn a_system_agent_is_available_without_channel_membership() {
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .once()
        .return_once(|_| Box::pin(async { Ok(None) }));
    bots.expect_get_bot()
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(system_bot(bot_id))) }));

    assert!(mention_yields_event(&posted, bots).await);
}

#[tokio::test]
async fn forwards_a_mentioned_thread_reply_to_its_session() {
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .with(
            mockall::predicate::eq(posted.thread_id),
            mockall::predicate::eq(Some(BotId::TEST_A)),
        )
        .once()
        .return_once(|_, _| {
            Box::pin(async {
                Ok(ThreadSession::CreatedFromThread(session(
                    AgentSessionId::TEST_A,
                    BotId::TEST_A,
                )))
            })
        });
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    let (replies, judge) = no_implicit();
    let service = service(sessions, bots, replies, judge);

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.bot_id, BotId::TEST_A);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
}

/// A reply in a session's originating thread that does not mention the bot
/// stays a normal channel message.
#[tokio::test]
async fn a_thread_reply_without_a_mention_does_not_forward() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![]);
    let (replies, judge) = no_implicit();
    let service = service(sessions, MockAgentBotLookup::new(), replies, judge);

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn evaluates_every_mentioned_agent_bot() {
    let posted = message(vec![mention_of(BotId::TEST_B), mention_of(BotId::TEST_A)]);
    let thread_id = posted.thread_id;
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .withf(move |actual_thread_id, bot_id| *actual_thread_id == thread_id && bot_id.is_some())
        .times(2)
        .returning(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .times(2)
        .returning(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    let (replies, judge) = no_implicit();
    let service = service(sessions, bots, replies, judge);

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(events.len(), 2);
    let mut event_bots: Vec<_> = events
        .iter()
        .map(|event| match event {
            TriggerDecision::Open { bot_id, .. } => *bot_id,
            other => panic!("expected a new-session decision, got {other:?}"),
        })
        .collect();
    event_bots.sort_by_key(ToString::to_string);
    assert_eq!(event_bots, vec![BotId::TEST_A, BotId::TEST_B]);
}

#[tokio::test]
async fn evaluates_a_repeated_bot_mention_once() {
    let posted = message(vec![mention_of(BotId::TEST_A), mention_of(BotId::TEST_A)]);
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .with(
            mockall::predicate::eq(posted.thread_id),
            mockall::predicate::eq(Some(BotId::TEST_A)),
        )
        .once()
        .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    let (replies, judge) = no_implicit();
    let service = service(sessions, bots, replies, judge);

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(events.len(), 1);
    let TriggerDecision::Open { bot_id, .. } = &events[0] else {
        panic!("expected a new-session decision");
    };
    assert_eq!(*bot_id, BotId::TEST_A);
}

#[tokio::test]
async fn ignores_a_mentioned_bot_without_an_agent() {
    let posted = message(vec![mention_of(BotId::TEST_A)]);
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .once()
        .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|_| Box::pin(async { Ok(None) }));
    bots.expect_get_bot()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|_| Box::pin(async { Ok(None) }));
    let (replies, judge) = no_implicit();
    let service = service(sessions, bots, replies, judge);

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn deduplicates_a_session_found_for_multiple_mentions() {
    let posted = message(vec![mention_of(BotId::TEST_A), mention_of(BotId::TEST_B)]);
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .times(2)
        .returning(|_, _| {
            Box::pin(async {
                Ok(ThreadSession::CreatedFromThread(session(
                    AgentSessionId::TEST_A,
                    BotId::TEST_A,
                )))
            })
        });
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    let (replies, judge) = no_implicit();
    let service = service(sessions, bots, replies, judge);

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
}

/// Session repo mocks for the implicit path: no session owns the message's
/// channel, and its thread carries the given sessions.
fn implicit_sessions(found: Vec<AgentSession>) -> MockAgentSessionRepo {
    let mut sessions = MockAgentSessionRepo::new();
    sessions
        .expect_find_for_thread()
        .once()
        .return_once(|_, _| Box::pin(async { Ok(ThreadSession::None) }));
    sessions
        .expect_find_all_for_thread()
        .with(mockall::predicate::eq(Uuid::from_u128(3)))
        .once()
        .return_once(move |_| Box::pin(async move { Ok(found) }));
    sessions
}

fn agent_bots() -> MockAgentBotLookup {
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .returning(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    bots
}

fn extractor(result: Result<Option<ExtractedExplicitReply>>) -> MockExplicitReplyExtractor {
    let mut replies = MockExplicitReplyExtractor::new();
    replies
        .expect_extract_explicit_reply()
        .once()
        .return_once(move |_| Box::pin(async move { result }));
    replies
}

fn reply_to_bot(bot_id: BotId) -> ExtractedExplicitReply {
    ExtractedExplicitReply {
        parent: MessageParent::Channel(Uuid::from_u128(1)),
        target_message_id: Uuid::from_u128(10).to_string(),
        target_thread_id: Uuid::from_u128(3).to_string(),
        display_text: "please fix this".to_owned(),
        sender_id: bot_id.into_storage_id().as_ref().to_owned(),
    }
}

fn reply_to_user() -> ExtractedExplicitReply {
    reply_to_user_message(Uuid::from_u128(10))
}

fn reply_to_user_message(target_message_id: Uuid) -> ExtractedExplicitReply {
    ExtractedExplicitReply {
        parent: MessageParent::Channel(Uuid::from_u128(1)),
        target_message_id: target_message_id.to_string(),
        target_thread_id: Uuid::from_u128(3).to_string(),
        display_text: "please fix this".to_owned(),
        sender_id: user().as_ref().to_owned(),
    }
}

fn judge_saying(result: Result<Vec<f32>>) -> MockImplicitTriggerJudge {
    let mut judge = MockImplicitTriggerJudge::new();
    judge
        .expect_addressee_probabilities()
        .once()
        .return_once(move |_, _, _| Box::pin(async move { result }));
    judge
}

/// A judge that asserts on the transcript it was handed, and says yes.
fn judge_expecting(transcript: &'static str) -> MockImplicitTriggerJudge {
    let mut judge = MockImplicitTriggerJudge::new();
    judge
        .expect_addressee_probabilities()
        .once()
        .return_once(move |_, given, _| {
            assert_eq!(given, transcript);
            Box::pin(async { Ok(vec![0.9]) })
        });
    judge
}

fn thread_message(id: u128, sender: ChannelSender<'static>, content: &str) -> ThreadMessage {
    ThreadMessage {
        id: Uuid::from_u128(id),
        sender,
        content: content.to_owned(),
        created_at: Utc::now(),
    }
}

#[tokio::test]
async fn an_explicit_reply_in_a_session_thread_triggers_without_a_mention() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),
        MockImplicitTriggerJudge::new(),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
    assert_eq!(metadata.bot_id, BotId::TEST_A);
    assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}

#[tokio::test]
async fn a_message_the_judge_reads_as_addressed_triggers_as_inferred() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Ok(vec![0.9])),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.kind, ThreadMessageKind::Inferred);
}

#[tokio::test]
async fn a_message_addressed_to_nobody_yields_nothing() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Ok(vec![0.1])),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn a_thread_without_sessions_never_consults_the_judge() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![]);
    let (replies, judge) = no_implicit();
    let service = service(sessions, MockAgentBotLookup::new(), replies, judge);

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn a_bot_sender_never_triggers_implicitly() {
    let mut posted = message(vec![]);
    posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
    let sessions = MockAgentSessionRepo::new();
    let (replies, judge) = no_implicit();
    let service = service(sessions, MockAgentBotLookup::new(), replies, judge);

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn implicit_triggering_skips_sessions_of_agentless_bots() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![
        thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
        thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
    ]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|_| Box::pin(async { Ok(None) }));
    bots.expect_get_agent()
        .with(mockall::predicate::eq(BotId::TEST_B))
        .once()
        .return_once(|bot_id| Box::pin(async move { Ok(Some(private_agent(bot_id))) }));
    bots.expect_get_bot()
        .with(mockall::predicate::eq(BotId::TEST_A))
        .once()
        .return_once(|_| Box::pin(async { Ok(None) }));
    let service = service(
        sessions,
        bots,
        extractor(Ok(Some(reply_to_bot(BotId::TEST_B)))),
        MockImplicitTriggerJudge::new(),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_B);
    assert_eq!(metadata.bot_id, BotId::TEST_B);
}

fn two_live_sessions() -> MockAgentSessionRepo {
    implicit_sessions(vec![
        thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
        thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
    ])
}

#[tokio::test]
async fn the_judge_picks_which_of_two_live_agents_a_message_is_for() {
    let posted = message(vec![]);
    let service = service(
        two_live_sessions(),
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Ok(vec![0.2, 0.8])),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_B);
    assert_eq!(metadata.bot_id, BotId::TEST_B);
    assert_eq!(metadata.kind, ThreadMessageKind::Inferred);
}

#[tokio::test]
async fn a_message_the_judge_reads_as_for_both_live_agents_yields_nothing() {
    let posted = message(vec![]);
    let service = service(
        two_live_sessions(),
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Ok(vec![0.7, 0.8])),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn a_judge_answering_for_the_wrong_number_of_agents_yields_nothing() {
    let posted = message(vec![]);
    let service = service(
        two_live_sessions(),
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Ok(vec![0.9])),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn the_judge_reads_every_live_agent_numbered_in_the_thread() {
    let posted = message(vec![]);
    let history = thread_of(vec![
        thread_message(0, ChannelSender::new_from_bot(BotId::TEST_A), "on it"),
        thread_message(1, ChannelSender::new_from_bot(BotId::TEST_B), "me too"),
        thread_message(2, ChannelSender::new_from_user(user()), "hello"),
    ]);
    let mut judge = MockImplicitTriggerJudge::new();
    judge
        .expect_addressee_probabilities()
        .once()
        .return_once(|_, transcript, agents| {
            assert_eq!(agents, 2);
            assert_eq!(
                transcript,
                "[agent 1] on it\n\
                 [agent 2] me too\n\
                 [user macro|[email protected]] hello\n"
            );
            Box::pin(async { Ok(vec![0.9, 0.1]) })
        });
    let service = service_reading(
        two_live_sessions(),
        agent_bots(),
        extractor(Ok(None)),
        judge,
        history,
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).session_id,
        AgentSessionId::TEST_A
    );
}

#[tokio::test]
async fn a_failing_extractor_falls_through_to_the_judge() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Err(AgentSessionError::Unknown(anyhow::anyhow!(
            "lexical service unavailable"
        )))),
        judge_saying(Ok(vec![0.9])),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).kind,
        ThreadMessageKind::Inferred
    );
}

#[tokio::test]
async fn a_failing_judge_yields_nothing_instead_of_an_error() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(None)),
        judge_saying(Err(AgentSessionError::Unknown(anyhow::anyhow!(
            "model unavailable"
        )))),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn the_judge_reads_the_thread_around_the_agent() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    // Message 2 is the one being evaluated, so both it and the agent's own
    // message anchor a window; message 0 falls outside both.
    let history = thread_of(vec![
        thread_message(0, ChannelSender::new_from_user(user()), "unrelated chatter"),
        thread_message(1, ChannelSender::new_from_bot(BotId::TEST_A), "on it"),
        thread_message(2, ChannelSender::new_from_user(user()), "hello"),
    ]);
    let service = service_reading(
        sessions,
        agent_bots(),
        extractor(Ok(None)),
        judge_expecting(
            "[user macro|[email protected]] unrelated chatter\n\
             [agent 1] on it\n\
             [user macro|[email protected]] hello\n",
        ),
        history,
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).kind,
        ThreadMessageKind::Inferred
    );
}

#[tokio::test]
async fn an_explicit_reply_never_reads_the_thread() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let mut history = MockThreadHistory::new();
    history
        .expect_authorize_invocation()
        .returning(allow_invocation);
    history.expect_thread_messages().never();
    let service = service_reading(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),
        MockImplicitTriggerJudge::new(),
        history,
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).kind,
        ThreadMessageKind::ExplicitReply
    );
}

#[tokio::test]
async fn an_unreadable_thread_still_judges_the_message_alone() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let mut history = MockThreadHistory::new();
    history
        .expect_authorize_invocation()
        .returning(allow_invocation);
    history.expect_thread_messages().once().return_once(|_| {
        Box::pin(async {
            Err(AgentSessionError::Unknown(anyhow::anyhow!(
                "channels database unavailable"
            )))
        })
    });
    let service = service_reading(
        sessions,
        agent_bots(),
        extractor(Ok(None)),
        judge_expecting(""),
        history,
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).kind,
        ThreadMessageKind::Inferred
    );
}

#[tokio::test]
async fn an_explicit_reply_to_the_originating_message_triggers_without_a_mention() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_user_message(Uuid::from_u128(3))))),
        MockImplicitTriggerJudge::new(),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
    assert_eq!(metadata.bot_id, BotId::TEST_A);
    assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}

#[tokio::test]
async fn an_explicit_reply_to_another_user_falls_through_to_the_judge() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_user()))),
        judge_saying(Ok(vec![0.9])),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    assert_eq!(
        existing_channel_metadata(&events).kind,
        ThreadMessageKind::Inferred
    );
}

#[tokio::test]
async fn an_explicit_reply_to_one_of_two_live_agents_routes_to_that_agent() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![
        thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
        thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
    ]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_bot(BotId::TEST_B)))),
        MockImplicitTriggerJudge::new(),
    );

    let events = service.evaluate(&posted).await.expect("evaluate message");
    let metadata = existing_channel_metadata(&events);
    assert_eq!(metadata.session_id, AgentSessionId::TEST_B);
    assert_eq!(metadata.bot_id, BotId::TEST_B);
    assert_eq!(metadata.kind, ThreadMessageKind::ExplicitReply);
}

#[tokio::test]
async fn an_explicit_reply_to_neither_of_two_live_agents_is_left_to_the_judge() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![
        thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
        thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
    ]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_user()))),
        judge_saying(Ok(vec![0.1, 0.1])),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn an_explicit_reply_to_a_shared_originating_message_is_left_to_the_judge() {
    let posted = message(vec![]);
    let sessions = implicit_sessions(vec![
        thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
        thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
    ]);
    let service = service(
        sessions,
        agent_bots(),
        extractor(Ok(Some(reply_to_user_message(Uuid::from_u128(3))))),
        judge_saying(Ok(vec![0.1, 0.1])),
    );

    assert!(
        service
            .evaluate(&posted)
            .await
            .expect("evaluate message")
            .is_empty()
    );
}

#[tokio::test]
async fn discussion_mentions_use_owned_agents_without_channel_participation() {
    for parent in [
        MessageParent::parse("document", "doc").unwrap(),
        MessageParent::Initiative(Uuid::from_u128(901)),
    ] {
        for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {
            let mut posted = message(vec![mention_of(BotId::TEST_A)]);
            posted.parent = parent.clone();
            let mut bots = MockAgentBotLookup::new();
            bots.expect_get_agent().once().return_once(move |id| {
                Box::pin(async move {
                    let mut agent = private_agent(id);
                    agent.channel_scope = scope;
                    Ok(Some(agent))
                })
            });
            assert!(mention_yields_event(&posted, bots).await);
        }
    }
}

#[tokio::test]
async fn discussion_agents_respect_team_membership() {
    for parent in [
        MessageParent::parse("document", "doc").unwrap(),
        MessageParent::Initiative(Uuid::from_u128(901)),
    ] {
        for allowed in [true, false] {
            let mut posted = message(vec![mention_of(BotId::TEST_A)]);
            posted.parent = parent.clone();
            let team_id = Uuid::from_u128(99);
            let mut facts = FactMocks::from(MockAgentBotLookup::new());
            facts.bots.expect_get_agent().once().return_once(move |id| {
                Box::pin(async move {
                    Ok(Some(agent_with(
                        id,
                        BotOwner::Team { team_id },
                        AgentChannelScope::Selected,
                    )))
                })
            });
            facts
                .teams
                .expect_user_has_team()
                .once()
                .return_once(move |_, _| Box::pin(async move { Ok(allowed) }));
            assert_eq!(mention_yields_event(&posted, facts).await, allowed);
        }
    }
}

#[tokio::test]
async fn a_discussion_cannot_invoke_another_users_private_agent() {
    for parent in [
        MessageParent::parse("document", "doc").unwrap(),
        MessageParent::Initiative(Uuid::from_u128(901)),
    ] {
        let mut posted = message(vec![mention_of(BotId::TEST_A)]);
        posted.parent = parent.clone();
        posted.sender = ChannelSender::new_from_user(
            MacroUserIdStr::try_from_email("[email protected]").unwrap(),
        );
        let mut bots = MockAgentBotLookup::new();
        bots.expect_get_agent()
            .once()
            .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
        assert!(!mention_yields_event(&posted, bots).await);
    }
}

#[tokio::test]
async fn a_queued_discussion_mention_cannot_invoke_after_access_is_revoked() {
    for parent in [
        MessageParent::parse("document", "doc").unwrap(),
        MessageParent::Initiative(Uuid::from_u128(901)),
    ] {
        let mut posted = message(vec![mention_of(BotId::TEST_A)]);
        posted.parent = parent.clone();
        let mut history = MockThreadHistory::new();
        history
            .expect_authorize_invocation()
            .once()
            .return_once(|_, _, _| Box::pin(async { Ok(None) }));
        let (replies, judge) = no_implicit();
        let service = service_reading(
            MockAgentSessionRepo::new(),
            MockAgentBotLookup::new(),
            replies,
            judge,
            history,
        );
        assert!(service.evaluate(&posted).await.unwrap().is_empty());
    }
}

#[tokio::test]
async fn document_explicit_followups_route_to_the_existing_agent() {
    let mut posted = message(vec![]);
    posted.parent = MessageParent::parse("document", "doc").unwrap();
    let mut reply = reply_to_bot(BotId::TEST_A);
    reply.parent = posted.parent.clone();
    let mut session = thread_session(AgentSessionId::TEST_A, BotId::TEST_A);
    session.thread_parent = Some(posted.parent.clone());
    let sessions = implicit_sessions(vec![session]);
    let mut bots = MockAgentBotLookup::new();
    bots.expect_get_agent()
        .returning(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
    let service = service(
        sessions,
        bots,
        extractor(Ok(Some(reply))),
        MockImplicitTriggerJudge::new(),
    );
    let events = service.evaluate(&posted).await.unwrap();
    assert_eq!(
        existing_channel_metadata(&events).message.parent,
        posted.parent
    );
}

#[tokio::test]
async fn explicit_reply_cannot_select_a_session_from_a_different_parent_or_root() {
    for wrong_parent in [true, false] {
        let posted = message(vec![]);
        let mut reply = reply_to_bot(BotId::TEST_A);
        if wrong_parent {
            reply.parent = MessageParent::parse("document", "another-document").unwrap();
        } else {
            reply.target_thread_id = Uuid::from_u128(999).to_string();
        }
        let service = service(
            MockAgentSessionRepo::new(),
            MockAgentBotLookup::new(),
            extractor(Ok(Some(reply))),
            MockImplicitTriggerJudge::new(),
        );
        assert!(
            service
                .explicit_reply_session(
                    &posted,
                    &[thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]
                )
                .await
                .is_none()
        );
    }
}

#[tokio::test]
async fn a_session_from_another_parent_cannot_receive_a_document_followup() {
    let mut posted = message(vec![]);
    posted.parent = MessageParent::parse("document", "doc").unwrap();
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let service = service(
        sessions,
        MockAgentBotLookup::new(),
        MockExplicitReplyExtractor::new(),
        MockImplicitTriggerJudge::new(),
    );
    assert!(service.evaluate(&posted).await.unwrap().is_empty());
}

fn crm_parents() -> [MessageParent; 2] {
    [
        MessageParent::CrmCompany(Uuid::from_u128(902)),
        MessageParent::CrmContact(Uuid::from_u128(903)),
    ]
}

#[tokio::test]
async fn crm_mentions_use_owned_agents_like_documents() {
    for parent in crm_parents() {
        for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {
            let mut posted = message(vec![mention_of(BotId::TEST_A)]);
            posted.parent = parent.clone();
            let mut bots = MockAgentBotLookup::new();
            bots.expect_get_agent().once().return_once(move |id| {
                Box::pin(async move {
                    let mut agent = private_agent(id);
                    agent.channel_scope = scope;
                    Ok(Some(agent))
                })
            });
            assert!(mention_yields_event(&posted, bots).await);
        }
    }
}

#[tokio::test]
async fn crm_agents_respect_team_membership() {
    for parent in crm_parents() {
        for allowed in [true, false] {
            let mut posted = message(vec![mention_of(BotId::TEST_A)]);
            posted.parent = parent.clone();
            let team_id = Uuid::from_u128(99);
            let mut facts = FactMocks::from(MockAgentBotLookup::new());
            facts.bots.expect_get_agent().once().return_once(move |id| {
                Box::pin(async move {
                    Ok(Some(agent_with(
                        id,
                        BotOwner::Team { team_id },
                        AgentChannelScope::Selected,
                    )))
                })
            });
            facts
                .teams
                .expect_user_has_team()
                .once()
                .return_once(move |_, _| Box::pin(async move { Ok(allowed) }));
            assert_eq!(mention_yields_event(&posted, facts).await, allowed);
        }
    }
}

#[tokio::test]
async fn a_crm_discussion_cannot_invoke_another_users_private_agent() {
    for parent in crm_parents() {
        let mut posted = message(vec![mention_of(BotId::TEST_A)]);
        posted.parent = parent;
        posted.sender = ChannelSender::new_from_user(
            MacroUserIdStr::try_from_email("[email protected]").unwrap(),
        );
        let mut bots = MockAgentBotLookup::new();
        bots.expect_get_agent()
            .once()
            .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));
        assert!(!mention_yields_event(&posted, bots).await);
    }
}

#[tokio::test]
async fn attributed_bot_mentions_open_or_resume_the_target_session() {
    for (source, target) in [
        (bot_id::MACRO_NEW_BOT_ID, bot_id::CURSOR_BOT_ID),
        (bot_id::CURSOR_BOT_ID, bot_id::MACRO_NEW_BOT_ID),
        (BotId::TEST_A, bot_id::MACRO_NEW_BOT_ID),
    ] {
        for existing in [false, true] {
            let mut posted = message(vec![mention_of(target)]);
            posted.sender = ChannelSender::new_from_bot(source);
            posted.triggered_by = Some(user().to_string());
            let mut sessions = MockAgentSessionRepo::new();
            let id = AgentSessionId::TEST_A;
            sessions
                .expect_find_for_thread()
                .once()
                .returning(move |thread, bot| {
                    assert_eq!(thread, Some(Uuid::from_u128(3)));
                    assert_eq!(bot, Some(target));
                    Box::pin(async move {
                        Ok(if existing {
                            ThreadSession::CreatedFromThread(thread_session(id, target))
                        } else {
                            ThreadSession::None
                        })
                    })
                });
            let mut bots = MockAgentBotLookup::new();
            bots.expect_get_agent()
                .returning(|_| Box::pin(async { Ok(None) }));
            bots.expect_get_bot()
                .returning(|bot| Box::pin(async move { Ok(Some(system_bot(bot))) }));
            let mut history = MockThreadHistory::new();
            history
                .expect_authorize_invocation()
                .once()
                .returning(|actor, parent, root| {
                    assert_eq!(actor, &user());
                    allow_invocation(actor, parent, root)
                });
            history
                .expect_thread_messages()
                .once()
                .returning(|_| Box::pin(async { Ok(vec![]) }));
            let (replies, judge) = no_implicit();
            let events = service_reading(sessions, bots, replies, judge, history)
                .evaluate(&posted)
                .await
                .unwrap();
            assert_eq!(
                events,
                vec![if existing {
                    TriggerDecision::Existing {
                        bot_id: target,
                        session_id: id,
                        kind: ThreadMessageKind::MentionThread,
                        message: posted,
                    }
                } else {
                    TriggerDecision::Open {
                        bot_id: target,
                        message: posted,
                    }
                }]
            );
        }
    }
}

#[tokio::test]
async fn attributed_bots_cannot_bypass_access_or_trigger_themselves() {
    let mut posted = message(vec![mention_of(BotId::TEST_A)]);
    posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
    posted.triggered_by = Some(user().to_string());
    let mut history = MockThreadHistory::new();
    history
        .expect_authorize_invocation()
        .once()
        .returning(|_, _, _| Box::pin(async { Ok(None) }));
    let (replies, judge) = no_implicit();
    assert!(
        service_reading(
            MockAgentSessionRepo::new(),
            MockAgentBotLookup::new(),
            replies,
            judge,
            history
        )
        .evaluate(&posted)
        .await
        .unwrap()
        .is_empty()
    );

    for (source, actor) in [
        (BotId::TEST_A, user().to_string()),
        (BotId::TEST_B, "macro|[email protected]".into()),
    ] {
        posted.sender = ChannelSender::new_from_bot(source);
        posted.triggered_by = Some(actor);
        let mut bots = MockAgentBotLookup::new();
        bots.expect_get_agent()
            .once()
            .returning(|bot| Box::pin(async move { Ok(Some(private_agent(bot))) }));
        assert!(!mention_yields_event(&posted, bots).await);
    }
}

#[tokio::test]
async fn unattributed_bot_messages_do_not_trigger() {
    for (attribution, mentions) in [
        (None, vec![mention_of(BotId::TEST_A)]),
        (None, vec![]),
        (Some("invalid".to_owned()), vec![mention_of(BotId::TEST_A)]),
    ] {
        let mut posted = message(mentions);
        posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
        posted.triggered_by = attribution;
        let (replies, judge) = no_implicit();
        assert!(
            service_reading(
                MockAgentSessionRepo::new(),
                MockAgentBotLookup::new(),
                replies,
                judge,
                MockThreadHistory::new()
            )
            .evaluate(&posted)
            .await
            .unwrap()
            .is_empty()
        );
    }
}

#[tokio::test]
async fn agents_mentioning_each_other_stop_at_the_hop_limit_without_a_person() {
    let macro_ai = ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);
    let cursor = ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);
    // The agent posting hop `n`, alternating from Macro's first handoff.
    let agent = |n: usize| {
        if n % 2 == 1 {
            (macro_ai.clone(), bot_id::CURSOR_BOT_ID)
        } else {
            (cursor.clone(), bot_id::MACRO_NEW_BOT_ID)
        }
    };
    let thread: Vec<ThreadMessage> = std::iter::once(thread_message(
        100,
        ChannelSender::new_from_user(user()),
        "@macro go",
    ))
    .chain((1..=MAX_AGENT_HOPS).map(|n| thread_message(100 + n as u128, agent(n).0, "over to you")))
    .collect();
    for (hop, triggers) in [(MAX_AGENT_HOPS, true), (MAX_AGENT_HOPS + 1, false)] {
        let (sender, target) = agent(hop);
        let read = hop;
        let mut posted = message(vec![mention_of(target)]);
        posted.sender = sender;
        posted.triggered_by = Some(user().to_string());
        let mut bots = MockAgentBotLookup::new();
        bots.expect_get_agent()
            .returning(|_| Box::pin(async { Ok(None) }));
        bots.expect_get_bot()
            .returning(|bot| Box::pin(async move { Ok(Some(system_bot(bot))) }));
        let (replies, judge) = no_implicit();
        let sessions = if triggers {
            sessions_without_existing()
        } else {
            MockAgentSessionRepo::new()
        };
        let events = service_reading(
            sessions,
            bots,
            replies,
            judge,
            thread_of(thread[..read].to_vec()),
        )
        .evaluate(&posted)
        .await
        .unwrap();
        assert_eq!(!events.is_empty(), triggers, "hop {hop}");
    }
}

#[tokio::test]
async fn an_agents_unmentioned_follow_up_reaches_another_agents_session() {
    for (replies, judge, kind) in [
        (
            extractor(Ok(None)),
            judge_saying(Ok(vec![0.9])),
            ThreadMessageKind::Inferred,
        ),
        (
            extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),
            MockImplicitTriggerJudge::new(),
            ThreadMessageKind::ExplicitReply,
        ),
    ] {
        let mut posted = message(vec![]);
        posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);
        posted.triggered_by = Some(user().to_string());
        let sessions = implicit_sessions(vec![
            thread_session(AgentSessionId::TEST_A, BotId::TEST_A),
            thread_session(AgentSessionId::TEST_B, BotId::TEST_B),
        ]);

        let events = service(sessions, agent_bots(), replies, judge)
            .evaluate(&posted)
            .await
            .unwrap();

        let metadata = existing_channel_metadata(&events);
        assert_eq!(metadata.bot_id, BotId::TEST_A);
        assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
        assert_eq!(metadata.kind, kind);
    }
}

#[tokio::test]
async fn an_agent_never_infers_into_its_own_session() {
    let mut posted = message(vec![]);
    posted.sender = ChannelSender::new_from_bot(BotId::TEST_A);
    posted.triggered_by = Some(user().to_string());
    let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
    let (replies, judge) = no_implicit();

    let events = service(sessions, agent_bots(), replies, judge)
        .evaluate(&posted)
        .await
        .unwrap();

    assert!(events.is_empty());
}

#[tokio::test]
async fn an_inferred_agent_chain_stops_at_the_hop_limit_before_judging() {
    let agent = |n: usize| {
        ChannelSender::new_from_bot(if n % 2 == 1 {
            BotId::TEST_A
        } else {
            BotId::TEST_B
        })
    };
    let thread: Vec<ThreadMessage> = std::iter::once(thread_message(
        100,
        ChannelSender::new_from_user(user()),
        "work it out between you",
    ))
    .chain((1..=MAX_AGENT_HOPS).map(|n| thread_message(100 + n as u128, agent(n), "your turn")))
    .collect();
    let mut posted = message(vec![]);
    posted.sender = agent(MAX_AGENT_HOPS + 1);
    posted.triggered_by = Some(user().to_string());
    let (replies, judge) = no_implicit();

    let events = service_reading(
        MockAgentSessionRepo::new(),
        MockAgentBotLookup::new(),
        replies,
        judge,
        thread_of(thread),
    )
    .evaluate(&posted)
    .await
    .unwrap();

    assert!(events.is_empty());
}