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.

35.1 KB
Raw Blame
use super::*;
use connection_gateway::model::connection::StoredConnectionEntity;
use connection_gateway::model::tracking::{EntityConnection, UserEntityConnection};
use connection_gateway::service::connection::ConnectionRepo;
use std::sync::Arc;
use stream::domain::{
    ItemId, ItemStream, Result as StreamResult, StreamEvent, StreamId, StreamRepo,
};
use tokio::sync::broadcast::{self, Receiver};
use tokio_util::task::TaskTracker;

pub const ADMISSION_TEST_USER: &str = "macro|[email protected]";

pub struct TestAdmission {
    pub result: Result<(), ai_billing::AiAdmissionError>,
    pub calls: std::sync::Mutex<Vec<(String, ai_usage::AiFeature)>>,
}

impl TestAdmission {
    pub fn rejecting(error: ai_billing::AiAdmissionError) -> Arc<Self> {
        Arc::new(Self {
            result: Err(error),
            calls: Default::default(),
        })
    }
}

impl ai_billing::AiAdmissionService for TestAdmission {
    fn admit<'a>(
        &'a self,
        user: &'a macro_user_id::user_id::MacroUserIdStr<'_>,
        feature: ai_usage::AiFeature,
    ) -> ai_billing::domain::admission::AdmissionFuture<'a> {
        self.calls.lock().unwrap().push((user.to_string(), feature));
        Box::pin(async { self.result })
    }
}

pub fn admission_errors() -> [ai_billing::AiAdmissionError; 4] {
    use ai_billing::{AiAdmissionError, DenyReason};
    [
        AiAdmissionError::Denied(DenyReason::AllowanceExhausted),
        AiAdmissionError::Denied(DenyReason::OverageLimitReached),
        AiAdmissionError::Denied(DenyReason::OveragePaymentFailed),
        AiAdmissionError::Unavailable,
    ]
}

pub fn authorized_request(path: &str, body: serde_json::Value) -> axum::extract::Request {
    axum::http::Request::builder()
        .method("POST")
        .uri(path)
        .header("content-type", "application/json")
        .header("x-internal-auth-key", "testing")
        .header("x-internal-macro-user-id", ADMISSION_TEST_USER)
        .body(axum::body::Body::from(body.to_string()))
        .unwrap()
}

pub async fn test_model_access(ctx: &ApiContext) -> DcsChatModelAccess {
    use axum::extract::FromRequestParts;
    let (mut parts, _) = authorized_request("/", serde_json::json!({})).into_parts();
    DcsChatModelAccess::from_request_parts(&mut parts, ctx)
        .await
        .unwrap_or_else(|_| panic!("test model access should resolve"))
}

pub struct MockConnectionRepo;

impl MockConnectionRepo {
    #[expect(
        clippy::new_ret_no_self,
        reason = "tests take the mock as the trait object ApiContext stores"
    )]
    pub fn new() -> Arc<dyn ConnectionRepo> {
        Arc::new(Self)
    }
}

#[async_trait::async_trait]
impl ConnectionRepo for MockConnectionRepo {
    async fn insert_connection_entry(
        &self,
        _connection: UserEntityConnection<'_>,
    ) -> anyhow::Result<StoredConnectionEntity> {
        unimplemented!()
    }
    async fn get_entries_by_entity(
        &self,
        _entity: &model_entity::Entity<'_>,
    ) -> anyhow::Result<Vec<StoredConnectionEntity>> {
        Ok(vec![])
    }
    async fn get_entries_by_connection_id(
        &self,
        _connection_id: &str,
    ) -> anyhow::Result<Vec<StoredConnectionEntity>> {
        Ok(vec![])
    }
    async fn get_connection(&self, _connection_id: &str) -> anyhow::Result<StoredConnectionEntity> {
        unimplemented!()
    }
    async fn get_entry_for_connection_entity(
        &self,
        _entity: EntityConnection<'_>,
    ) -> anyhow::Result<Option<StoredConnectionEntity>> {
        Ok(None)
    }
    async fn remove_all_entries_for_by_connection_id(
        &self,
        _connection_id: &str,
    ) -> anyhow::Result<()> {
        Ok(())
    }
    async fn remove_entity(&self, _entity: &EntityConnection<'_>) -> anyhow::Result<()> {
        Ok(())
    }
    async fn update_last_entity_ping(
        &self,
        _entity: &EntityConnection<'_>,
        _timestamp: u64,
    ) -> anyhow::Result<Option<StoredConnectionEntity>> {
        unimplemented!()
    }
    async fn update_user_connection_last_ping(
        &self,
        _connection_id: &str,
        _user: &str,
        _timestamp: u64,
    ) -> anyhow::Result<()> {
        Ok(())
    }
}

/// Mock StreamRepo for testing - does nothing but satisfies the interface
pub struct MockStreamRepo {
    tx: broadcast::Sender<StreamEvent>,
}

impl MockStreamRepo {
    #[expect(
        clippy::new_ret_no_self,
        reason = "tests take the mock as the trait object ApiContext stores"
    )]
    pub fn new() -> Arc<dyn StreamRepo> {
        let (tx, _) = broadcast::channel(16);
        Arc::new(Self { tx })
    }
}

#[async_trait::async_trait]
impl StreamRepo for MockStreamRepo {
    async fn append(&self, _id: &StreamId, _payload: serde_json::Value) -> StreamResult<ItemId> {
        Ok("mock-item-id".to_string())
    }

    async fn stream_from_beginning(&self, _id: &StreamId) -> StreamResult<ItemStream> {
        Ok(Box::pin(futures::stream::empty()))
    }

    async fn close(&self, _id: &StreamId) -> StreamResult<()> {
        Ok(())
    }

    async fn active_streams(&self, _entity_id: &str) -> StreamResult<Vec<StreamId>> {
        Ok(vec![])
    }

    async fn notify(&self) -> Receiver<StreamEvent> {
        self.tx.subscribe()
    }
}

pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {
    let config = Config::new_empty_for_test();
    let enforcement = config.enable_ai_usage_enforcement;
    let pricing = config.ai_pricing();
    let admission =
        ai_billing::composition::pg_admission_service(pool.clone(), enforcement, pricing);
    let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);
    use aws_sdk_sqs;
    use channels::{
        domain::list_service::ChannelListServiceImpl, outbound::pg_channels_repo::PgChannelsRepo,
    };
    use document_storage_service_client::DocumentStorageServiceClient;
    use email::domain::ports::ReadonlyEmailPreviewAdapter;
    use email::domain::service::EmailServiceImpl;
    use email::outbound::EmailPgRepo;
    use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
    use foreign_entity::{
        domain::service::ForeignEntityServiceImpl,
        outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
    };
    use frecency::domain::services::FrecencyQueryServiceImpl;
    use frecency::outbound::postgres::FrecencyPgStorage;
    use github_pull_requests::{
        domain::service::GithubPullRequestServiceImpl,
        outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
    };
    use lexical_client::LexicalClient;
    use notification::domain::service::{
        NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,
    };
    use notification::outbound::queue::SqsQueue;
    use notification::outbound::repository::DbNotificationRepository;
    use search_service_client::SearchServiceClient;
    use soup::domain::service::SoupImpl;
    use soup::outbound::pg_soup_repo::PgSoupRepo;
    use sqs_client::SQS;
    use sync_service_client::SyncServiceClient;

    let sqs_config = aws_sdk_sqs::Config::builder()
        .behavior_version(aws_sdk_sqs::config::BehaviorVersion::latest())
        .build();
    let aws_sqs_client = aws_sdk_sqs::Client::from_conf(sqs_config.clone());
    let sqs_client = SQS::new(aws_sqs_client).email_scheduled_queue("test-email-scheduled-queue");

    let document_storage_client = Arc::new(DocumentStorageServiceClient::new(
        "dummy_auth_key".into(),
        "http://localhost".into(),
    ));
    let search_service_client =
        SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());
    let sync_service_client = Arc::new(SyncServiceClient::new(
        "dummy_auth_key".into(),
        "http://localhost".into(),
    ));
    let email_service_client = Arc::new(EmailServiceClient::new(
        "dummy_auth_key".into(),
        "http://localhost".into(),
    ));
    let email_service_client_external = Arc::new(EmailServiceClientExternal::new(
        email_service_client.url().to_owned(),
    ));

    // Build soup service dependencies
    let frecency_storage = FrecencyPgStorage::new(pool.clone());
    let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
    let crm_service = crm::domain::service::CrmServiceImpl::new(
        crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),
        crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,
    );
    let email_service = EmailServiceImpl::new(
        EmailPgRepo::new(pool.clone()),
        frecency_service.clone(),
        email::domain::ports::NoOpEnqueuer,
        crm_service.clone(),
        entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
            entity_access_management::outbound::PgRepository::new(pool.clone()),
        ),
        0,
    );
    let channels_service = ChannelListServiceImpl::new(
        PgChannelsRepo::new(pool.clone()),
        PgChannelsRepo::new(pool.clone()),
        frecency_storage,
    );
    let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
    let github_pull_request_service = GithubPullRequestServiceImpl::new(
        ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
        PgGithubPullRequestRepo::new(pool.clone()),
    );
    let favorites_service = ai_tools::build_favorites_service(pool.clone());
    let soup_service = Arc::new(
        SoupImpl::new(
            PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
            frecency_service,
            ReadonlyEmailPreviewAdapter(email_service),
            channels_service,
            call::domain::service::CallRecordQueryServiceImpl::new(
                call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
            ),
            crm::domain::service::NoOpCrmService,
            github_pull_request_service,
        )
        .with_favorites(favorites_service.clone()),
    );

    let ingress_queue = SqsQueue::new(
        aws_sdk_sqs::Client::from_conf(sqs_config.clone()),
        "test-notification-ingress-queue".to_string(),
    );
    let notification_ingress_service = Arc::new(SqsNotificationIngress {
        queue: ingress_queue,
    });

    let notification_reader_queue = SqsQueue::new(
        aws_sdk_sqs::Client::from_conf(sqs_config.clone()),
        "test-notification-queue".to_string(),
    );
    let notification_reader_service = NotificationReaderService {
        repository: DbNotificationRepository::new(pool.clone()),
        queue: ai_tools::ToolNotificationQueue::Sqs(notification_reader_queue),
        sns_endpoint: ai_tools::NoOpSnsEndpointManager,
        platform_config: PlatformArnConfig {
            apns_platform_arn: String::new(),
            fcm_platform_arn: String::new(),
            apns_voip_platform_arn: String::new(),
        },
        realtime: notification::domain::ports::NoopNotificationRealtimePublisher,
    };
    let notification_tool_context =
        notification::inbound::ai_tool::NotificationToolContext::new(notification_reader_service);

    // Build document tool context for AI tools
    let s3_config = aws_sdk_s3::Config::builder()
        .behavior_version(aws_sdk_s3::config::BehaviorVersion::latest())
        .build();
    let s3_client = aws_sdk_s3::Client::from_conf(s3_config);
    let s3_upload_adapter = documents::outbound::s3_upload_url::S3UploadUrlAdapter::new(
        s3_client,
        "test-bucket",
        "test-docx-bucket",
    );
    let owned_entity_registrar = entity_registry_db_utils::OwnedEntityRegistrar::new(
        entity_registry::OwnerGrantPolicy::new(bots::outbound::pg_bots_repo::PgBotsRepo::new(
            pool.clone(),
        )),
    );
    let document_repo = documents::outbound::pg_document_repo::PgDocumentRepo::new(
        pool.clone(),
        owned_entity_registrar.clone(),
    );
    let cloudfront_config = documents::domain::models::CloudFrontConfig {
        distribution_url: "https://test.cloudfront.net".to_string(),
        signer_public_key_id: "test-key-id".to_string(),
        signer_private_key: "test-private-key".to_string(),
        presigned_url_expiry_seconds: 3600,
        browser_cache_expiry_seconds: 86400,
    };
    let entity_access_service = Arc::new(
        entity_access::domain::service::EntityAccessServiceImpl::new(
            entity_access::outbound::PgAccessRepository::new(pool.clone()),
        ),
    );
    // Producer creation is lazy: nothing connects to Kafka unless an event
    // is published, so a dummy broker address is safe for tests.
    let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(
        macro_event_broker::KafkaEventPublisher::new("localhost:9092")
            .expect("kafka producer config is valid"),
        TaskTracker::new(),
    );
    let properties_service = ai_tools::build_properties_service_with_broker(
        pool.clone(),
        entity_access_service.clone(),
        macro_event_broker.clone(),
    );
    let task_properties_service = ai_tools::build_task_properties_adapter(
        pool.clone(),
        properties_service.clone(),
        entity_access_service.clone(),
    );

    let document_service = documents::domain::service::DocumentServiceImpl::new(
        document_repo,
        cloudfront_config,
        sync_service_client.as_ref().clone(),
        s3_upload_adapter,
        task_properties_service,
        ai_tools::NoOpConnectionService,
        entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
            entity_access_management::outbound::PgRepository::new(pool.clone()),
        ),
        ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
        macro_event_broker.clone(),
    );
    let test_lexical_client = LexicalClient::new("test".into(), "http://nofileshere".into());
    let test_editing_client =
        documents::outbound::editing_worker_client::ReqwestEditingWorkerClient::from_url(
            "http://nofileshere".into(),
        );
    let document_tool_context = documents::inbound::toolset::DocumentToolContext::new(
        document_service,
        (*entity_access_service).clone(),
        test_lexical_client.clone(),
        sync_service_client.as_ref().clone(),
        test_editing_client,
        "test-jwt-secret".to_string(),
        ai_tools::build_message_service_without_side_effects(
            pool.clone(),
            std::sync::Arc::new(test_lexical_client.clone()),
        ),
    );

    let search_service_client = Arc::new(search_service_client);

    // Build properties tool context
    let properties_tool_context = ai_tools::build_properties_tool_context(
        properties_service.clone(),
        entity_access_service.clone(),
    );

    let user_email_service = Arc::new(
        email::domain::service::EmailServiceImpl::new(
            email::outbound::EmailPgRepo::new(pool.clone()),
            frecency::domain::services::FrecencyQueryServiceImpl::new(
                frecency::outbound::postgres::FrecencyPgStorage::new(pool.clone()),
            ),
            sqs_client.clone(),
            crm_service.clone(),
            entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
                entity_access_management::outbound::PgRepository::new(pool.clone()),
            ),
            0,
        )
        .with_macro_event_broker(macro_event_broker.clone()),
    );
    let email_tool_context = email::inbound::toolset::EmailToolContext::new(
        user_email_service.clone(),
        Arc::new(email::domain::ports::NoOpGmailTokenProvider),
        entity_access_service.clone(),
        Arc::new(test_lexical_client.clone()),
    );

    let call_service = call::domain::service::CallServiceImpl::new(
        call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
        ai_tools::NoOpCallRtcClient,
        ai_tools::NoOpConnectionService,
        (*entity_access_service).clone(),
        ai_tools::NoOpNotificationIngress,
        None::<call::outbound::s3_recording_storage::S3RecordingStorage>,
        String::new(),
    );
    let call_tool_context = call::inbound::toolset::CallToolContext::new(
        call_service,
        (*entity_access_service).clone(),
    );

    let chat_tool_context = chat::inbound::toolset::ChatToolContext::new(
        chat::domain::service::ChatServiceImpl::new(
            chat::outbound::postgres::PgChatRepo::new(pool.clone(), owned_entity_registrar.clone()),
            Arc::new(ai_toolset::AsyncToolCollection::new()),
            (),
            entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
                entity_access_management::outbound::PgRepository::new(pool.clone()),
            ),
        ),
        (*entity_access_service).clone(),
    );

    let initiative_tool_context = ai_tools::build_initiative_tool_context(
        pool.clone(),
        &document_tool_context,
        properties_service.clone(),
        entity_access_service.clone(),
        macro_event_broker.clone(),
    );

    let databases_tool_context = ai_tools::build_databases_tool_context(
        pool.clone(),
        entity_access_service.clone(),
        ai_tools::ToolTableEventPublisher::NoOp(Default::default()),
        ai_tools::MaybeToolEventBroker::Real(macro_event_broker.clone()),
    );
    let project_tool_context = ai_tools::build_project_tool_context(
        pool.clone(),
        macro_event_broker.clone(),
        entity_access_service.clone(),
        document_tool_context.service.clone(),
        user_email_service.clone(),
        databases_tool_context.service.clone(),
    );
    let databases_sql_tool_context = ai_tools::build_databases_sql_tool_context(
        &databases_tool_context,
        soup_service.clone(),
        pool.clone(),
    );
    let crm_tool_context = ai_tools::build_crm_tool_context(pool.clone());
    let pipeline_tool_context = ai_tools::build_pipeline_tool_context(
        pool.clone(),
        &databases_tool_context,
        &crm_tool_context,
    );
    let crm_transfer_tool_context = ai_tools::build_crm_transfer_tool_context(
        &pipeline_tool_context,
        &crm_tool_context,
        &document_tool_context,
    );

    let calendar_tool_context = ai_tools::build_calendar_tool_context(
        pool.clone(),
        macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
        "test-internal-api-key".to_string(),
        call_tool_context.service.clone(),
        macro_service_urls::AppServiceUrl::local(),
        true,
    );
    let forms_tool_context = ai_tools::build_forms_tool_context(
        pool.clone(),
        &document_tool_context,
        &databases_tool_context,
        &calendar_tool_context,
        None,
        ai_tools::MaybeToolEventBroker::Real(macro_event_broker.clone()),
        ai_tools::FormsToolConfig {
            app_origin: "https://macro.test".into(),
            editing_worker_url: "http://localhost:8933".into(),
            static_files: static_file_service_client::StaticFileServiceClient::new(
                "test-internal-api-key".to_string(),
                "http://localhost:0".to_string(),
            ),
        },
    );

    let tool_service_context = ai_tools::ToolServiceContext {
        memory_tool_context: ai_tools::memory::build_memory_tool_context(
            pool.clone(),
            recorder.clone(),
        ),
        cognition_tool_context: Default::default(),
        connector_tool_context: ai_tools::build_connector_tool_context(pool.clone(), None, None),
        search_service_client: search_service_client.clone(),
        email_service_client: email_service_client_external.clone(),
        soup_service: soup_service.clone(),
        email_service: email_service_for_tools.clone(),
        activity_tool_context: ai_tools::build_activity_tool_context(
            pool.clone(),
            properties_service.clone(),
            entity_access_service.clone(),
        ),
        image_generation_tool_context: ai_tools::build_image_generation_tool_context_test(
            &document_tool_context,
        ),
        message_tool_context: ai_tools::build_message_tool_context(&document_tool_context),
        document_tool_context: document_tool_context.clone(),
        properties_tool_context: properties_tool_context.clone(),
        email_tool_context: email_tool_context.clone(),
        call_tool_context: call_tool_context.clone(),
        booking_management_tool_context: ai_tools::build_booking_management_tool_context(
            macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
            "test-internal-api-key".to_string(),
            macro_env::Environment::Local,
        ),
        booking_link_tool_context: ai_tools::build_booking_link_tool_context(
            pool.clone(),
            macro_env::Environment::Local,
        ),
        calendar_tool_context: ai_tools::build_calendar_tool_context(
            pool.clone(),
            macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
            "test-internal-api-key".to_string(),
            call_tool_context.service.clone(),
            macro_service_urls::AppServiceUrl::local(),
            true,
        ),
        team_calendar_tool_context: ai_tools::build_team_calendar_tool_context(pool.clone(), true),
        notification_tool_context: notification_tool_context.clone(),
        item_notification_preference_tool_context:
            ai_tools::build_item_notification_preference_tool_context(pool.clone()),
        databases_tool_context,
        forms_tool_context,
        databases_sql_tool_context,
        import_tool_context: ai_tools::ToolImportToolContext::unwired(),
        mcp_server_tool_context: ai_tools::ToolMcpServerToolContext::unwired(),
        chat_tool_context,
        channel_tool_context: ai_tools::build_channel_tool_context_without_side_effects(
            pool.clone(),
            std::sync::Arc::new(test_lexical_client),
        ),
        channel_media_upload_tool_context: ai_tools::build_channel_media_upload_tool_context_test(),
        bot_tool_context: ai_tools::build_bot_tool_context(
            pool.clone(),
            ai_tools::MaybeToolEventBroker::Real(macro_event_broker.clone()),
            entity_access_service.clone(),
            "http://localhost:8086".to_string(),
            None,
        ),
        read_agent_session_context: ai_tools::build_read_agent_session_context(
            pool.clone(),
            entity_access_service.clone(),
        ),
        coding_agent_tool_context: ai_tools::build_coding_agent_tool_context(
            macro_service_urls::ServiceUrl::owned("http://localhost:0").into(),
            "test-internal-api-key".to_string(),
        )
        .expect("valid test coding agent context"),
        project_tool_context,
        favorites_tool_context: ai_tools::build_favorites_tool_context(
            favorites_service,
            entity_access_service.clone(),
        ),
        initiative_tool_context,
        team_tool_context: ai_tools::build_team_tool_context(pool.clone()),
        crm_tool_context,
        pipeline_tool_context,
        crm_transfer_tool_context,
        skill_tool_context: ai_tools::build_skill_tool_context(
            search_service_client.clone(),
            soup_service.clone(),
            &document_tool_context,
        ),
        schedule_tool_context: ai_tools::no_op_schedule_context(),
        anthropic_tool_context: ai_tools::build_anthropic_tool_context_test(),
        web_search_provider: std::sync::Arc::new(web_search::outbound::tavily::TavilyClient::new(
            &web_search::outbound::tavily::TavilyApiKey::new_unset(),
        )),
        admission: admission.clone(),
        recorder: recorder.clone(),
        usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),
    };
    let all_tools = ai_tools::tools_for(ai_tools::AiHost::Chat);
    let all_tools_toolset = all_tools.toolset.clone();
    let all_tools_prompt: Arc<dyn std::fmt::Display + Send + Sync> =
        Arc::new(all_tools.prompt.to_string());

    let (import_service, onboarding_service, mcp_selector) = {
        let mcp_key =
            mcp_client::domain::models::AesKey::try_from(vec![0u8; 32]).expect("valid test key");
        let mcp_repo = mcp_client::outbound::NativeServerStore::new(
            mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key),
            None,
        );
        let creator = ai_tools::ToolEntityCreator {
            document_creator: document_tool_context.creator.clone(),
            entity_access_service: entity_access_service.clone(),
            channel_service: tool_service_context.channel_tool_context.service.clone(),
            task_properties: ai_tools::build_task_properties_adapter(
                pool.clone(),
                properties_service.clone(),
                entity_access_service.clone(),
            ),
            document_properties:
                import::outbound::document_properties::DocumentPropertiesApplicator::new(
                    properties_service.clone(),
                ),
            team_repository: ai_tools::build_team_repository(pool.clone()),
            initiative_service: tool_service_context.initiative_tool_context.service.clone(),
            project_service: tool_service_context.project_tool_context.service.clone(),
            databases_service: tool_service_context.databases_tool_context.service.clone(),
            document_service: document_tool_context.service.clone(),
        };
        let pipedream_connections = Arc::new(
            pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool.clone()),
        );
        let mcp_selector: Arc<ai_tools::ToolMcpSelector> =
            Arc::new(mcp_select::McpToolSelector::new(
                Arc::new(mcp_repo.clone()),
                pipedream_connections.clone(),
                Arc::new(None),
            ));
        let import_service = Arc::new(
            import::domain::service::ImportServiceImpl::new(
                import::outbound::pg_import_repo::PgImportRepo::new(pool.clone()),
                mcp_selector.clone(),
                Arc::new(creator),
                recorder.clone(),
            )
            .with_slack_source(Arc::new(
                import::outbound::mcp_slack_source::McpSlackSource::new(mcp_selector.clone()),
            ))
            .with_notion_connections(Arc::new(
                import_notion::outbound::pipedream::PipedreamNotionConnections::new(
                    pipedream_connections,
                    None,
                ),
            ))
            .with_admission(admission.clone()),
        );
        let onboarding_service = Arc::new(onboarding::domain::service::OnboardingServiceImpl::new(
            onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo::new(pool.clone()),
            Arc::new(mcp_repo),
        ));
        (import_service, onboarding_service, mcp_selector)
    };

    let memory_service = Arc::new(ai_tools::memory::build_memory_service(
        pool.clone(),
        tool_service_context.clone(),
    ));

    let usage_service = Arc::new(
        ai_usage::domain::service::UsageServiceImpl::new(ai_usage::outbound::PgUsageRepo::new(
            pool.clone(),
        ))
        .with_enforcement(enforcement),
    );

    let projection_generator =
        ai_projections::outbound::agent_generator::AgentProjectionGenerator::new(
            tool_service_context.clone(),
            ai_tools::tools_for(ai_tools::AiHost::Chat),
        );

    let projection_notifier =
        ai_projections::outbound::gateway_notifier::GatewayProjectionNotifier::new(Arc::new(
            connection_gateway_client::ConnectionGatewayClient::new(
                "testing".to_string(),
                "http://localhost".to_string(),
            ),
        ));

    let ai_projections_service = Arc::new(
        ai_projections::domain::ai_projection_service::AiProjectionServiceImpl::new(
            ai_projections::outbound::ai_projection_repo::AiProjectionRepositoryImpl::new(
                pool.clone(),
            ),
            sqs_client.clone(),
            projection_generator,
            projection_notifier,
        ),
    );

    let authorization_state =
        MacroAuthorizationState::new(Arc::new(MacroAuthorizationServiceImpl::new(
            MacroAuthJwtValidator::new(
                macro_auth::middleware::decode_jwt::JwtValidationArgs::new_testing(),
            ),
            macro_authorization::InternalAuthConfig {
                api_key: "testing".to_string(),
                default_user_id: None,
            },
            macro_authorization::NoBotAuthorizer,
            macro_authorization::NoUserApiKeyAuthorizer,
        )));

    let user_permissions_service = Arc::new(
        roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
            roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
            roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),
        ),
    );

    let api_context = ApiContext {
        db: pool.clone(),
        sqs_client: Arc::new(sqs_client),
        document_storage_client,
        search_service_client,
        email_service_client_external,
        authorization_state: authorization_state.clone(),

        decisions: Arc::new(jev::domain::decisions::DecisionServiceImpl::<
            jev::domain::JevClassifier<jev::outbound::SystemOneJev>,
        >::new(None, admission.clone())),
        tool_free_completions: Arc::new(
            crate::cognition::service::structured_completion::ToolFreeCompletionService::new(
                recorder.clone(),
            ),
        ),
        ai_admission: admission,
        ai_billing: Arc::new(
            ai_billing::domain::BillingServiceImpl::new(
                ai_billing::outbound::RolesTeamsEntitlementSource::new(
                    (*user_permissions_service).clone(),
                    teams::outbound::team_repo::TeamRepositoryImpl::new(pool.clone()),
                ),
                ai_billing::outbound::PgUsageReader::new(pool.clone()),
                ai_billing::outbound::PgBillingRepo::new(pool.clone(), pricing),
                ai_billing::outbound::HttpPaymentGateway::new(Arc::new(
                    authentication_service_client::AuthServiceClient::new(
                        "testing".to_string(),
                        "http://127.0.0.1:9".to_string(),
                    ),
                )),
                pricing,
            )
            .with_enforcement(enforcement),
        ),
        user_permissions_service,
        non_user_owners: NonUserOwners::Disabled,
        config: Arc::new(config),
        internal_api_key: InternalApiKey::Comptime("testing"),
        notification_ingress_service,
        connection_repo: MockConnectionRepo::new(),
        connection_gateway_client: Arc::new(
            notification::outbound::websocket::ConnectionGatewayClient::new(
                "testing".to_string(),
                "http://localhost".to_string(),
            ),
        ),
        soup_service,
        email_service: email_service_for_tools.clone(),
        stream_repo: MockStreamRepo::new(),
        document_tool_context: document_tool_context.clone(),
        memory_service,
        usage_service,
        ai_projections_service,
        properties_tool_context,
        email_tool_context,
        call_tool_context,
        tool_service_context,
        all_tools: all_tools_toolset,
        all_tools_prompt,
        entity_access_service: entity_access_service.clone(),
        message_service: Arc::new(
            chat::domain::service::MessageServiceImpl::new(
                chat::outbound::postgres::PgChatRepo::new(
                    pool.clone(),
                    owned_entity_registrar.clone(),
                ),
                attachment::provider::AttachmentProvider {
                    document: documents::inbound::attachment::DocumentAttachmentService::new(
                        document_tool_context.service.clone(),
                        document_tool_context.entity_access_service.clone(),
                        document_tool_context.lexical_client.clone(),
                    ),
                    email_thread: email::inbound::attachment::EmailAttachmentService::new(
                        email_service_for_tools.clone(),
                        entity_access_service.clone(),
                    ),
                    chat: chat::inbound::attachment::ChatAttachmentService::new(
                        Arc::new(chat::outbound::postgres::PgChatRepo::new(
                            pool.clone(),
                            owned_entity_registrar.clone(),
                        )),
                        entity_access_service.clone(),
                    ),
                    channel: channels::inbound::attachment::ChannelAttachmentService::new(
                        Arc::new(PgChannelsRepo::new(pool.clone())),
                        entity_access_service.clone(),
                    ),
                    static_file: static_file::inbound::attachment::StaticFileAttachmentService::new(
                        Arc::new(static_file::outbound::CdnStaticFileRepo::new(
                            "http://localhost".into(),
                        )),
                    ),
                },
            )
            .with_event_broker(macro_event_broker.clone()),
        ),
        ai_stream_registry: crate::cognition::service::ai_stream_registry::AiStreamRegistry::new(
            Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url")),
        ),
        web_rate_limiter: rate_limit::RateLimitServiceImpl {
            repo: rate_limit::RedisRateLimitAdapter {
                redis: redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),
            },
        },
        granola_sync: None,
        pipedream_state: pipedream_mcp::inbound::PipedreamRouterState::new(
            pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool.clone()),
            None,
            authorization_state.clone(),
        ),
        mcp_selector,
        mcp_state: {
            let redis_client =
                Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"));
            let mcp_key = mcp_client::domain::models::AesKey::try_from(vec![0u8; 32])
                .expect("valid test key");
            let mcp_repo = mcp_client::outbound::NativeServerStore::new(
                mcp_client::outbound::pg_server_repo::PgServerRepo::new(pool.clone(), mcp_key),
                None,
            );
            let mcp_state_store =
                mcp_client::outbound::redis_state_store::RedisOAuthStateStore::new(redis_client);
            let client_metadata = mcp_client::domain::models::OAuthClientMetadata::new(
                "http://localhost/mcp/servers/auth/client-metadata".to_string(),
                "http://localhost/mcp/servers/auth/callback".to_string(),
            );
            let mcp_oauth = mcp_client::outbound::oauth::OAuthService::new(
                mcp_repo.clone(),
                mcp_state_store,
                client_metadata.clone(),
                mcp_client::domain::provider_registry::PreRegisteredProviders::empty(),
            );
            mcp_client::inbound::McpRouterState::new(
                mcp_repo,
                mcp_oauth,
                authorization_state,
                client_metadata,
            )
        },
        import_service: import_service.clone(),
        onboarding_service,
        macro_event_broker,
    };
    Arc::new(api_context)
}