Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore: purge sqlx from domain (#5854)
teobb2d0409893a
diff --git a/Cargo.lock b/Cargo.lockindex d5e30749bd..484d66e5b0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -598,6 +598,7 @@ dependencies = ["macro_db_migrator","macro_user_id","macro_uuid",+ "rootcause","serde","serde_json","sqlx",@@ -8048,6 +8049,7 @@ dependencies = ["models_properties","properties","regex",+ "rootcause","schemars 1.2.1","serde","serde_json",@@ -9869,6 +9871,7 @@ dependencies = ["notification","readonly_pool","reminders",+ "rootcause","search_service_client","serde","serde_json",@@ -11137,6 +11140,7 @@ dependencies = ["macro_user_id","mcp_client","mcp_select",+ "rootcause","serde","serde_json","sqlx",@@ -13297,6 +13301,7 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4fc4bd36159c7ce180fe2de1e5371ef107a2885f0048430f631e78202e2255d4"dependencies = [+ "anyhow","hashbrown 0.16.1","indexmap 2.14.0","rootcause-internals",@@ -15596,6 +15601,7 @@ dependencies = ["macro_user_id","macro_uuid","models_properties",+ "rootcause","serde","serde_json","sqlx",@@ -15677,6 +15683,7 @@ dependencies = ["macro_service_urls","model-entity","reqwest 0.13.4",+ "rootcause","secretsmanager_client","serde","serde_json",@@ -17951,6 +17958,7 @@ dependencies = ["aes-gcm","ahash","aho-corasick",+ "anyhow","aws-config","aws-credential-types","aws-runtime",diff --git a/Cargo.toml b/Cargo.tomlindex 2fdadf6753..05c4b4c5bd 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -248,7 +248,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls",] }rmcp = "1.6.0"-rootcause = { version = "0.12" }+rootcause = { version = "0.12", features = ["compat-anyhow1"] }rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs"] }rootcause-tracing = "0.12.1"schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }diff --git a/crates/ai_usage/Cargo.toml b/crates/ai_usage/Cargo.tomlindex 786cea672d..209dc98147 100644--- a/crates/ai_usage/Cargo.toml+++ b/crates/ai_usage/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+rootcause = { workspace = true }anyhow = { workspace = true }axum = { workspace = true }chrono = { workspace = true }diff --git a/crates/ai_usage/src/domain/ports.rs b/crates/ai_usage/src/domain/ports.rsindex e4607e598b..8608b3707c 100644--- a/crates/ai_usage/src/domain/ports.rs+++ b/crates/ai_usage/src/domain/ports.rs@@ -224,8 +224,8 @@ impl UsageContext {#[derive(Debug, Error)]pub enum UsageError {/// A database error.- #[error(transparent)]- Db(#[from] sqlx::Error),+ #[error("database error: {0}")]+ Db(rootcause::Report),/// Any other error.#[error(transparent)]Other(#[from] anyhow::Error),diff --git a/crates/ai_usage/src/outbound/pg_usage_repo.rs b/crates/ai_usage/src/outbound/pg_usage_repo.rsindex 886d0d0e92..c7e971322f 100644--- a/crates/ai_usage/src/outbound/pg_usage_repo.rs+++ b/crates/ai_usage/src/outbound/pg_usage_repo.rs@@ -190,3 +190,12 @@ impl UsageRepo for PgUsageRepo {.collect()}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for crate::domain::ports::UsageError {+ fn from(e: sqlx::Error) -> Self {+ Self::Db(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/bots/src/inbound/toolset/mod.rs b/crates/bots/src/inbound/toolset/mod.rsindex e9274dc535..fa71745bcc 100644--- a/crates/bots/src/inbound/toolset/mod.rs+++ b/crates/bots/src/inbound/toolset/mod.rs@@ -106,7 +106,7 @@ fn channel_access_error(error: AccessError) -> ToolCallError {}AccessError::NotFound(_) => "channel not found",AccessError::BadRequest(_) => "invalid channel id",- AccessError::DatabaseError(_) | AccessError::Internal => {+ AccessError::Unavailable(_) | AccessError::Internal(_) => {"failed to verify channel membership"}};diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rsindex a8e04743d4..862cbe085e 100644--- a/crates/bots/src/inbound/toolset/test.rs+++ b/crates/bots/src/inbound/toolset/test.rs@@ -242,7 +242,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_access_level(@@ -251,7 +251,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -261,7 +261,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -270,7 +270,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -280,7 +280,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -289,7 +289,7 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -297,21 +297,21 @@ impl EntityAccessService for AllowingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(diff --git a/crates/call/src/domain/entity_mutation.rs b/crates/call/src/domain/entity_mutation.rsindex 072d1f9bf2..2f2bb55484 100644--- a/crates/call/src/domain/entity_mutation.rs+++ b/crates/call/src/domain/entity_mutation.rs@@ -49,7 +49,7 @@ fn access_error(error: AccessError) -> EntityMutationErrorCode {error @ AccessError::BadRequest(_) => {EntityMutationErrorCode::invalid(rootcause::report!(error))}- error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {+ error @ (AccessError::Unavailable(_) | AccessError::Internal(_)) => {EntityMutationErrorCode::internal(rootcause::report!(error))}}diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rsindex dfd306d6a8..25430a0672 100644--- a/crates/channels/src/inbound/axum_router.rs+++ b/crates/channels/src/inbound/axum_router.rs@@ -977,15 +977,9 @@ fn map_access_error(err: AccessError) -> ChannelsHandlerErr {AccessError::UnauthorizedWithMessage(msg) => ChannelsHandlerErr::Unauthorized(msg),AccessError::BadRequest(msg) => ChannelsHandlerErr::BadRequest(msg),AccessError::NotFound(msg) => ChannelsHandlerErr::NotFound(msg),- AccessError::DatabaseError(e) => {- tracing::error!(error=?e, "entity access database error");- ChannelsHandlerErr::Internal(ChannelMessagesErr::Repo(anyhow::Error::from(e)))- }- AccessError::Internal => {- tracing::error!("entity access internal error");- ChannelsHandlerErr::Internal(ChannelMessagesErr::Repo(anyhow::anyhow!(- "entity access internal error"- )))+ AccessError::Unavailable(report) | AccessError::Internal(report) => {+ tracing::error!(error=?report, "entity access error");+ ChannelsHandlerErr::Internal(ChannelMessagesErr::Repo(anyhow::Error::from(report)))}}}diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rsindex bda6a86ed8..e349411abb 100644--- a/crates/channels/src/inbound/axum_router/test.rs+++ b/crates/channels/src/inbound/axum_router/test.rs@@ -108,7 +108,7 @@ impl TestAccessService {fn access_err(&self) -> AccessError {match self.mode {- AccessMode::Allow => AccessError::Internal,+ AccessMode::Allow => AccessError::internal("test access failure"),AccessMode::Deny => AccessError::Unauthorized,AccessMode::NotFound => AccessError::NotFound("Channel not found"),}diff --git a/crates/channels/src/inbound/toolset/mod.rs b/crates/channels/src/inbound/toolset/mod.rsindex a0c4d6910b..fe1d09d934 100644--- a/crates/channels/src/inbound/toolset/mod.rs+++ b/crates/channels/src/inbound/toolset/mod.rs@@ -90,7 +90,7 @@ fn channel_access_error(err: AccessError) -> ToolCallError {}AccessError::NotFound(_) => "channel not found",AccessError::BadRequest(_) => "invalid channel id",- AccessError::DatabaseError(_) | AccessError::Internal => {+ AccessError::Unavailable(_) | AccessError::Internal(_) => {"failed to verify channel membership"}};diff --git a/crates/chat/src/domain/service/entity_mutation.rs b/crates/chat/src/domain/service/entity_mutation.rsindex 6a6071460d..11142c5cc6 100644--- a/crates/chat/src/domain/service/entity_mutation.rs+++ b/crates/chat/src/domain/service/entity_mutation.rs@@ -44,7 +44,7 @@ fn access_error(error: AccessError) -> EntityMutationErrorCode {error @ AccessError::BadRequest(_) => {EntityMutationErrorCode::invalid(rootcause::report!(error))}- error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {+ error @ (AccessError::Unavailable(_) | AccessError::Internal(_)) => {EntityMutationErrorCode::internal(rootcause::report!(error))}}diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 72e87996c6..ec3ce9c0d8 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -670,7 +670,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn generate_bot_entity_access_receipt<T: RequiredPermission>(@@ -680,7 +680,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_access_level(@@ -689,7 +689,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -699,7 +699,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -708,7 +708,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -718,7 +718,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -727,7 +727,7 @@ impl EntityAccessService for CountingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -735,21 +735,21 @@ impl EntityAccessService for CountingEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(diff --git a/crates/crm/src/inbound/toolset/mod.rs b/crates/crm/src/inbound/toolset/mod.rsindex d86bd49330..ae0408c382 100644--- a/crates/crm/src/inbound/toolset/mod.rs+++ b/crates/crm/src/inbound/toolset/mod.rs@@ -365,7 +365,9 @@ pub(crate) fn team_access_error(err: AccessError) -> ToolCallError {}AccessError::NotFound(_) => "team not found",AccessError::BadRequest(_) => "invalid team membership",- AccessError::DatabaseError(_) | AccessError::Internal => "failed to verify team membership",+ AccessError::Unavailable(_) | AccessError::Internal(_) => {+ "failed to verify team membership"+ }};ToolCallError {diff --git a/crates/entity_access/Cargo.toml b/crates/entity_access/Cargo.tomlindex fcb0f71579..9d36e53aca 100644--- a/crates/entity_access/Cargo.toml+++ b/crates/entity_access/Cargo.toml@@ -29,6 +29,7 @@ uuid = { workspace = true }# Domain models (always included)bot_id = { path = "../bot_id" }+rootcause = { workspace = true }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }models_permissions = { path = "../models_permissions" }diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rsindex a109ead31c..98318c7439 100644--- a/crates/entity_access/src/domain/models.rs+++ b/crates/entity_access/src/domain/models.rs@@ -631,6 +631,11 @@ pub struct CallChannelInfo {}/// Errors that can occur during access checking.+///+/// The variants are the domain's failure vocabulary; causes never appear as+/// typed payloads. Where a cause exists (a database error, a failed lookup)+/// it travels inside a [`rootcause::Report`] attached to the variant, so it+/// is visible in logs but structurally opaque to domain logic.#[derive(Debug, thiserror::Error)]pub enum AccessError {/// User does not have access to the requested resource.@@ -641,9 +646,10 @@ pub enum AccessError {#[error("{0}")]UnauthorizedWithMessage(&'static str),- /// Database error during access check.- #[error("Database error: {0}")]- DatabaseError(#[from] sqlx::Error),+ /// Access could not be checked because a backing service failed+ /// transiently; retrying may succeed. The cause is attached.+ #[error("access check temporarily unavailable: {0}")]+ Unavailable(rootcause::Report),/// Bad request parameters.#[error("Bad request: {0}")]@@ -653,7 +659,15 @@ pub enum AccessError {#[error("Not found: {0}")]NotFound(&'static str),- /// Internal server error.- #[error("Internal error")]- Internal,+ /// Internal server error; retrying will not help. The cause is attached.+ #[error("Internal error: {0}")]+ Internal(rootcause::Report),+}++impl AccessError {+ /// Non-retryable internal failure with a short reason attached to the+ /// report, for sites that have no underlying cause to carry.+ pub fn internal(reason: &'static str) -> Self {+ Self::Internal(rootcause::report!(reason).into_dynamic())+ }}diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rsindex 9d1e7f7432..c7d4c5f940 100644--- a/crates/entity_access/src/domain/ports.rs+++ b/crates/entity_access/src/domain/ports.rs@@ -423,7 +423,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn generate_bot_entity_access_receipt<T: RequiredPermission>(@@ -433,7 +435,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_access_level(@@ -442,7 +446,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn check_access(@@ -452,7 +458,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn check_public_access(@@ -461,7 +469,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_entity_permission(@@ -471,7 +481,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_crm_entity_permission_with_team(@@ -480,7 +492,9 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_users_by_entity(@@ -488,21 +502,27 @@ impl EntityAccessService for NoOpEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal(+ "entity access service not configured",+ ))}async fn get_user_team(diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rsindex b50b535ed6..802bfa737e 100644--- a/crates/entity_access/src/domain/service.rs+++ b/crates/entity_access/src/domain/service.rs@@ -316,7 +316,12 @@ whereErr(error) => {tracing::error!(?error, "bulk email thread ownership check failed");for (thread_id, _) in valid_ids {- receipts.insert(thread_id, Err(AccessError::Internal));+ receipts.insert(+ thread_id,+ Err(AccessError::internal(+ "bulk email thread ownership check failed",+ )),+ );}return receipts;}diff --git a/crates/entity_access/src/inbound/axum_extractors/call/test.rs b/crates/entity_access/src/inbound/axum_extractors/call/test.rsindex f1970dcac2..c332160441 100644--- a/crates/entity_access/src/inbound/axum_extractors/call/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/call/test.rs@@ -255,7 +255,7 @@ impl EntityAccessService for FakeEntityAccessService {_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {if self.call_lookup_fails {- return Err(AccessError::Internal);+ return Err(AccessError::internal("test access failure"));}Ok(self.call_info.clone())}@@ -265,7 +265,7 @@ impl EntityAccessService for FakeEntityAccessService {_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {if self.call_lookup_fails {- return Err(AccessError::Internal);+ return Err(AccessError::internal("test access failure"));}Ok(self.call_info.clone())}diff --git a/crates/entity_access/src/inbound/axum_extractors/mod.rs b/crates/entity_access/src/inbound/axum_extractors/mod.rsindex bbeca2c47b..c9e26484fb 100644--- a/crates/entity_access/src/inbound/axum_extractors/mod.rs+++ b/crates/entity_access/src/inbound/axum_extractors/mod.rs@@ -98,8 +98,8 @@ impl From<AccessError> for ExtractorError {}AccessError::BadRequest(msg) => ExtractorError::BadRequest(msg),AccessError::NotFound(msg) => ExtractorError::NotFound(msg),- AccessError::DatabaseError(_) => ExtractorError::Database,- AccessError::Internal => ExtractorError::Internal,+ AccessError::Unavailable(_) => ExtractorError::Database,+ AccessError::Internal(_) => ExtractorError::Internal,}}}diff --git a/crates/entity_access/src/inbound/axum_extractors/team/test.rs b/crates/entity_access/src/inbound/axum_extractors/team/test.rsindex 46ed836b31..e144c7b680 100644--- a/crates/entity_access/src/inbound/axum_extractors/team/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/team/test.rs@@ -153,7 +153,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -163,7 +163,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -172,7 +172,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -182,7 +182,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -191,7 +191,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -199,21 +199,21 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(diff --git a/crates/entity_access/src/outbound/pg_access_repo/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/mod.rsindex d20d1aa8b5..a1a9014aa3 100644--- a/crates/entity_access/src/outbound/pg_access_repo/mod.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/mod.rs@@ -70,7 +70,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid document ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::document_access::get_document_access(&self.pool, &document_uuid, &source_ids).await?,@@ -88,7 +88,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid chat ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::chat_access::get_chat_access(&self.pool, &chat_uuid, &source_ids).await?)}@@ -103,7 +103,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid project ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::project_access::get_project_access(&self.pool, &project_uuid, &source_ids).await?,@@ -121,7 +121,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid thread ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::thread_access::get_thread_access(&self.pool,&thread_uuid,@@ -198,7 +198,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid call ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::call_access::get_call_access(&self.pool, &call_uuid, &source_ids).await?)}@@ -212,7 +212,7 @@ impl AccessRepository for PgAccessRepository {.map_err(|_| AccessError::BadRequest("Invalid agent session ID format"))?;let source_ids = queries::get_user_source_ids(&self.pool, user_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;Ok(queries::agent_session_access::get_agent_session_access(&self.pool,&agent_session_uuid,@@ -246,7 +246,7 @@ impl AccessRepository for PgAccessRepository {).fetch_one(&self.pool).await- .map_err(|_| AccessError::Internal)?;+ .map_err(AccessError::from)?;// Owner or nothing: a reminder has no sharing model to grade.Ok(owns.then_some(AccessLevel::Owner))@@ -266,7 +266,7 @@ impl AccessRepository for PgAccessRepository {let bot_principal = bot_id.into_storage_id();let source_ids = queries::get_team_scope_source_ids(&self.pool, &bot_principal, &team_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;let access = match entity_type {EntityType::Document => {@@ -352,7 +352,7 @@ impl AccessRepository for PgAccessRepository {let scope_sources =queries::get_team_scope_source_ids(&self.pool, &bot_principal, &team_id).await- .map_err(|_| AccessError::Internal)?;+ .map_err(anyhow_access_error)?;if !scope_sources.0.contains(&team_id.to_string())|| !scope_sources.0.contains(&bot_principal.to_string())@@ -505,7 +505,7 @@ impl AccessRepository for PgAccessRepository {) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {queries::get_entity_users(&self.pool, entity_id, entity_type).await- .map_err(|_| AccessError::Internal)+ .map_err(anyhow_access_error)}#[tracing::instrument(err, skip(self))]@@ -515,7 +515,7 @@ impl AccessRepository for PgAccessRepository {) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {queries::channel_users::get_channel_users(&self.pool, channel_id).await- .map_err(|_| AccessError::Internal)+ .map_err(AccessError::from)}#[tracing::instrument(err, skip(self))]@@ -551,3 +551,41 @@ impl AccessRepository for PgAccessRepository {Ok(queries::team_access::get_user_team(&self.pool, user_id).await?)}}++/// Classify an anyhow-wrapped query failure by downcasting to the sqlx error+/// when there is one, so genuine database outages surface as `Unavailable`+/// instead of hiding in `Internal`.+fn anyhow_access_error(e: anyhow::Error) -> AccessError {+ match e.downcast::<sqlx::Error>() {+ Ok(sqlx_error) => AccessError::from(sqlx_error),+ Err(other) => AccessError::Internal(rootcause::report!(other).into_dynamic()),+ }+}++// The domain error stays sqlx-free; this adapter owns the classification,+// where the error is still concrete: connection-level failures (and Postgres+// serialization/deadlock aborts, which are safe to retry) are `Unavailable`;+// everything else is a bug or bad data, so retrying won't help. The raw sqlx+// error travels inside the report, so nothing is lost from the logs.+impl From<sqlx::Error> for AccessError {+ fn from(e: sqlx::Error) -> Self {+ let transient = matches!(+ &e,+ sqlx::Error::PoolTimedOut+ | sqlx::Error::PoolClosed+ | sqlx::Error::WorkerCrashed+ | sqlx::Error::Io(_)+ | sqlx::Error::Tls(_)+ ) || matches!(+ &e,+ sqlx::Error::Database(db)+ if matches!(db.code().as_deref(), Some("40001") | Some("40P01"))+ );+ let report = rootcause::report!(e).into_dynamic();+ if transient {+ Self::Unavailable(report)+ } else {+ Self::Internal(report)+ }+ }+}diff --git a/crates/github/src/inbound/github_sync_router/test.rs b/crates/github/src/inbound/github_sync_router/test.rsindex 1f5e4b710a..861ff7c09f 100644--- a/crates/github/src/inbound/github_sync_router/test.rs+++ b/crates/github/src/inbound/github_sync_router/test.rs@@ -73,7 +73,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn generate_bot_entity_access_receipt<T: RequiredPermission>(@@ -83,7 +83,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_access_level(@@ -92,7 +92,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -102,7 +102,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -111,7 +111,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -121,7 +121,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -130,7 +130,7 @@ impl EntityAccessService for TestEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -138,21 +138,21 @@ impl EntityAccessService for TestEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(diff --git a/crates/graphql_email/src/loaders.rs b/crates/graphql_email/src/loaders.rsindex b3e587e6ec..106817624c 100644--- a/crates/graphql_email/src/loaders.rs+++ b/crates/graphql_email/src/loaders.rs@@ -255,8 +255,11 @@ wherefor thread_id in thread_ids {match access_results.remove(&thread_id.to_string())- .unwrap_or(Err(AccessError::Internal))- {+ .unwrap_or_else(|| {+ Err(AccessError::internal(+ "bulk access resolution missing entry",+ ))+ }) {Ok(receipt) => {authorized.push(receipt);authorized_ids.push(thread_id);@@ -331,8 +334,11 @@ wherefor thread_id in thread_ids {match access_results.remove(&thread_id.to_string())- .unwrap_or(Err(AccessError::Internal))- {+ .unwrap_or_else(|| {+ Err(AccessError::internal(+ "bulk access resolution missing entry",+ ))+ }) {Ok(receipt) => {authorized.insert(thread_id, receipt);}diff --git a/crates/graphql_email/src/loaders/test.rs b/crates/graphql_email/src/loaders/test.rsindex 14d2dcf5d0..b289e9050c 100644--- a/crates/graphql_email/src/loaders/test.rs+++ b/crates/graphql_email/src/loaders/test.rs@@ -99,7 +99,7 @@ impl EntityAccessService for TestAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_access_level(@@ -108,7 +108,7 @@ impl EntityAccessService for TestAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -118,7 +118,7 @@ impl EntityAccessService for TestAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -127,7 +127,7 @@ impl EntityAccessService for TestAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -137,7 +137,7 @@ impl EntityAccessService for TestAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -146,7 +146,7 @@ impl EntityAccessService for TestAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -154,28 +154,28 @@ impl EntityAccessService for TestAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(&self,_user_id: &MacroUserId<Lowercase<'_>>,) -> Result<Option<UserTeamInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}}diff --git a/crates/import/Cargo.toml b/crates/import/Cargo.tomlindex d818e85982..99ecb67429 100644--- a/crates/import/Cargo.toml+++ b/crates/import/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+rootcause = { workspace = true }agent = { path = "../agent" }ai_toolset = { path = "../ai_toolset" }ai_usage = { path = "../ai_usage" }diff --git a/crates/import/src/domain/ports.rs b/crates/import/src/domain/ports.rsindex 289345f3ec..e407286578 100644--- a/crates/import/src/domain/ports.rs+++ b/crates/import/src/domain/ports.rs@@ -9,8 +9,8 @@ use uuid::Uuid;#[derive(Debug, Error)]pub enum ImportError {/// Database failure.- #[error(transparent)]- Db(#[from] sqlx::Error),+ #[error("database error: {0}")]+ Db(rootcause::Report),/// Metadata failed to (de)serialize.#[error("invalid import metadata: {0}")]Metadata(#[from] serde_json::Error),diff --git a/crates/import/src/outbound/pg_import_repo.rs b/crates/import/src/outbound/pg_import_repo.rsindex dea265f4c1..5aabf4c13c 100644--- a/crates/import/src/outbound/pg_import_repo.rs+++ b/crates/import/src/outbound/pg_import_repo.rs@@ -744,3 +744,12 @@ impl ImportRepo for PgImportRepo {Ok(result.rows_affected())}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for ImportError {+ fn from(e: sqlx::Error) -> Self {+ Self::Db(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/memory/Cargo.toml b/crates/memory/Cargo.tomlindex 5548989186..fa63adfee1 100644--- a/crates/memory/Cargo.toml+++ b/crates/memory/Cargo.toml@@ -6,6 +6,7 @@ version = "0.1.0"[dependencies]+rootcause = { workspace = true }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }ai_tools = { path = "../ai_tools" }diff --git a/crates/memory/src/domain/ports.rs b/crates/memory/src/domain/ports.rsindex 45f87ef05d..71346c63c1 100644--- a/crates/memory/src/domain/ports.rs+++ b/crates/memory/src/domain/ports.rs@@ -12,8 +12,8 @@ pub enum MemoryError {NoGeneration,#[error("memory rejected by judge: {0}")]Rejected(String),- #[error(transparent)]- Db(#[from] sqlx::Error),+ #[error("database error: {0}")]+ Db(rootcause::Report),#[error(transparent)]Other(#[from] anyhow::Error),}diff --git a/crates/memory/src/domain/service.rs b/crates/memory/src/domain/service.rsindex 73428baa40..7d567ad1f1 100644--- a/crates/memory/src/domain/service.rs+++ b/crates/memory/src/domain/service.rs@@ -78,7 +78,6 @@ struct MemoryJudgement {}pub struct MemoryServiceImpl<Rpo> {- db: sqlx::PgPool,memory_repo: Rpo,tool_context: ToolServiceContext,tools: ToolSetWithPrompt,@@ -86,13 +85,11 @@ pub struct MemoryServiceImpl<Rpo> {impl<Rpo> MemoryServiceImpl<Rpo> {pub fn new(- db: sqlx::PgPool,memory_repo: Rpo,tool_context: ToolServiceContext,tools: ToolSetWithPrompt,) -> Self {Self {- db,memory_repo,tool_context,tools,@@ -105,7 +102,7 @@ const MAX_AGE: std::time::Duration = std::time::Duration::from_hours(24);impl<Rpo> MemoryService for MemoryServiceImpl<Rpo>where- Rpo: MemoryRepo,+ Rpo: MemoryRepo + Clone,{#[tracing::instrument(skip(self), err)]async fn get_or_generate_memory(@@ -125,15 +122,14 @@ wherelet env = Environment::new_or_prod();if needs_generation && !matches!(env, Environment::Local) {let previous_memory = record.as_ref().map(|r| r.memory.clone());- let pool = self.db.clone();+ let repo = self.memory_repo.clone();let tool_context = self.tool_context.clone();let toolset = self.tools.toolset.clone();let prompt: Box<dyn std::fmt::Display + Send + Sync> =Box::new(self.tools.prompt.to_string());tokio::spawn(async move {- let repo = crate::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());let tools = ToolSetWithPrompt { toolset, prompt };- let svc = MemoryServiceImpl::new(pool, repo, tool_context, tools);+ let svc = MemoryServiceImpl::new(repo, tool_context, tools);match svc.generate_memory(user.clone(), previous_memory).await {Ok(_) => tracing::info!(%user, "memory generated"),Err(MemoryError::Rejected(reason)) => {diff --git a/crates/memory/src/main.rs b/crates/memory/src/main.rsindex 992b09a1da..39e646a5f5 100644--- a/crates/memory/src/main.rs+++ b/crates/memory/src/main.rs@@ -30,8 +30,8 @@ async fn main() -> anyhow::Result<()> {let tool_context =build_tool_service_context_from_env(pool.clone(), event_broker_tracker.clone()).await?;let tools = all_tools();- let memory_repo = PgMemoryRepo::new(pool.clone());- let memory_service = MemoryServiceImpl::new(pool, memory_repo, tool_context, tools);+ let memory_repo = PgMemoryRepo::new(pool);+ let memory_service = MemoryServiceImpl::new(memory_repo, tool_context, tools);tracing::info!("Generating memory for {user}...");let memory_result = memory_service.get_or_generate_memory(user).await;diff --git a/crates/memory/src/outbound/pg_memory_repo.rs b/crates/memory/src/outbound/pg_memory_repo.rsindex a110f981b2..fdfbb1abca 100644--- a/crates/memory/src/outbound/pg_memory_repo.rs+++ b/crates/memory/src/outbound/pg_memory_repo.rs@@ -6,6 +6,7 @@ use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use sqlx::PgPool;+#[derive(Clone)]pub struct PgMemoryRepo {inner: PgPool,}@@ -75,3 +76,12 @@ impl MemoryRepo for PgMemoryRepo {Ok(row.memory)}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for crate::domain::MemoryError {+ fn from(e: sqlx::Error) -> Self {+ Self::Db(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/notification/src/domain/models/device.rs b/crates/notification/src/domain/models/device.rsindex 44661f1adc..6a358a94b8 100644--- a/crates/notification/src/domain/models/device.rs+++ b/crates/notification/src/domain/models/device.rs@@ -1,17 +1,12 @@//! Device registration models.use serde::{Deserialize, Serialize};-use sqlx::Type;use strum::{Display, EnumString};/// The device platform type.-#[derive(Debug, Clone, Serialize, Deserialize, Type, EnumString, Display, Eq, PartialEq)]+#[derive(Debug, Clone, Serialize, Deserialize, EnumString, Display, Eq, PartialEq)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[serde(rename_all = "lowercase")]-#[sqlx(- type_name = "notification_device_type_option",- rename_all = "lowercase"-)]#[strum(serialize_all = "lowercase")]pub enum DeviceType {/// iOS (APNS).@@ -20,7 +15,6 @@ pub enum DeviceType {Android,/// iOS VoIP (PushKit / CallKit). Uses the APNS_VOIP SNS platform application.#[serde(rename = "iosvoip")]- #[sqlx(rename = "iosvoip")]#[strum(serialize = "iosvoip")]IosVoip,}diff --git a/crates/notification/src/outbound/device_registration.rs b/crates/notification/src/outbound/device_registration.rsindex 2f2b1ab5e4..a981ae4768 100644--- a/crates/notification/src/outbound/device_registration.rs+++ b/crates/notification/src/outbound/device_registration.rs@@ -1,5 +1,6 @@//! Database adapter for device registration operations.+use super::repository::DbDeviceType;use crate::domain::models::device::DeviceType;use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;@@ -78,7 +79,7 @@ impl DeviceRegistrationDbOps for PgPool {LIMIT 1"#,device_token,- device_type as _,+ DbDeviceType::from(device_type) as _,).map(|row| row.device_endpoint).fetch_optional(self)@@ -106,7 +107,7 @@ impl DeviceRegistrationDbOps for PgPool {user_id_str,device_token,device_endpoint,- device_type as _,+ DbDeviceType::from(device_type) as _,).execute(self).await?;@@ -129,7 +130,7 @@ impl DeviceRegistrationDbOps for PgPool {"#,user_id_str,device_token,- device_type as _,+ DbDeviceType::from(device_type) as _,).map(|row| row.device_endpoint).fetch_all(self)@@ -151,7 +152,7 @@ impl DeviceRegistrationDbOps for PgPool {RETURNING device_endpoint"#,device_token,- device_type as _,+ DbDeviceType::from(device_type) as _,active_endpoint,).map(|row| row.device_endpoint)diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rsindex 345203c28b..4115b263b6 100644--- a/crates/notification/src/outbound/repository.rs+++ b/crates/notification/src/outbound/repository.rs@@ -348,19 +348,30 @@ fn push_cursor_filter(}/// Local representation of the `notification_device_type_option` Postgres enum-/// for compile-time checked sqlx queries.+/// for compile-time checked sqlx queries. The domain `DeviceType` stays+/// sqlx-free; adapters convert at the boundary.#[derive(Debug, sqlx::Type)]#[sqlx(type_name = "notification_device_type_option",rename_all = "lowercase")]-enum DbDeviceType {+pub(crate) enum DbDeviceType {Ios,Android,#[sqlx(rename = "iosvoip")]IosVoip,}+impl From<&DeviceType> for DbDeviceType {+ fn from(value: &DeviceType) -> Self {+ match value {+ DeviceType::Ios => Self::Ios,+ DeviceType::Android => Self::Android,+ DeviceType::IosVoip => Self::IosVoip,+ }+ }+}+/// Database-backed implementation of the notification repository port.////// This adapter handles all database operations for notifications includingdiff --git a/crates/onboarding/Cargo.toml b/crates/onboarding/Cargo.tomlindex 5f002beb9f..531e6cd780 100644--- a/crates/onboarding/Cargo.toml+++ b/crates/onboarding/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+rootcause = { workspace = true }anyhow = { workspace = true }axum = { workspace = true }chrono = { workspace = true }diff --git a/crates/onboarding/src/domain/ports.rs b/crates/onboarding/src/domain/ports.rsindex 4db4026e07..0366a087f4 100644--- a/crates/onboarding/src/domain/ports.rs+++ b/crates/onboarding/src/domain/ports.rs@@ -8,8 +8,8 @@ use thiserror::Error;#[derive(Debug, Error)]pub enum OnboardingError {/// Database failure.- #[error(transparent)]- Db(#[from] sqlx::Error),+ #[error("database error: {0}")]+ Db(rootcause::Report),/// A failure in the import pipeline this flow drives.#[error(transparent)]Import(#[from] import::domain::ports::ImportError),diff --git a/crates/onboarding/src/outbound/pg_onboarding_repo.rs b/crates/onboarding/src/outbound/pg_onboarding_repo.rsindex 7372117a94..6105f86813 100644--- a/crates/onboarding/src/outbound/pg_onboarding_repo.rs+++ b/crates/onboarding/src/outbound/pg_onboarding_repo.rs@@ -106,3 +106,12 @@ impl OnboardingRepo for PgOnboardingRepo {row.try_into()}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for crate::domain::ports::OnboardingError {+ fn from(e: sqlx::Error) -> Self {+ Self::Db(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/projects/src/domain/entity_mutation.rs b/crates/projects/src/domain/entity_mutation.rsindex c3e30d7e60..f4435aed83 100644--- a/crates/projects/src/domain/entity_mutation.rs+++ b/crates/projects/src/domain/entity_mutation.rs@@ -53,7 +53,7 @@ fn access_error(error: AccessError) -> EntityMutationErrorCode {error @ AccessError::BadRequest(_) => {EntityMutationErrorCode::invalid(rootcause::report!(error))}- error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {+ error @ (AccessError::Unavailable(_) | AccessError::Internal(_)) => {EntityMutationErrorCode::internal(rootcause::report!(error))}}diff --git a/crates/reminders/src/inbound/axum_router/test.rs b/crates/reminders/src/inbound/axum_router/test.rsindex 2903f963fa..85dd5e9690 100644--- a/crates/reminders/src/inbound/axum_router/test.rs+++ b/crates/reminders/src/inbound/axum_router/test.rs@@ -145,7 +145,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<EntityAccessReceipt<T>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_access_level(@@ -159,7 +159,7 @@ impl EntityAccessService for FakeEntityAccessService {if entity_type == EntityType::Reminder {return Ok((!self.reminder_not_owned).then_some(AccessLevel::Owner));}- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_access(@@ -169,7 +169,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn check_public_access(@@ -178,7 +178,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_required_level: AccessLevel,) -> Result<AccessLevel, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_entity_permission(@@ -188,7 +188,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_type: EntityType,_user_org_id: Option<i64>,) -> Result<EntityPermission, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_crm_entity_permission_with_team(@@ -197,7 +197,7 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_users_by_entity(@@ -205,28 +205,28 @@ impl EntityAccessService for FakeEntityAccessService {_entity_id: &str,_entity_type: EntityType,) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel(&self,_call_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_call_channel_by_channel_id(&self,_channel_id: &Uuid,) -> Result<Option<CallChannelInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}async fn get_user_team(&self,_user_id: &MacroUserId<Lowercase<'_>>,) -> Result<Option<UserTeamInfo>, AccessError> {- Err(AccessError::Internal)+ Err(AccessError::internal("test access failure"))}}diff --git a/crates/stream/src/domain/types.rs b/crates/stream/src/domain/types.rsindex 87be697734..3f486f242f 100644--- a/crates/stream/src/domain/types.rs+++ b/crates/stream/src/domain/types.rs@@ -57,9 +57,3 @@ impl From<serde_json::error::Error> for StreamServiceError {Self::SerdeError(value)}}--impl From<sqlx::Error> for StreamServiceError {- fn from(value: sqlx::Error) -> Self {- Self::StorageError(value.to_string())- }-}diff --git a/crates/stream/src/outbound/redis_pg/repo.rs b/crates/stream/src/outbound/redis_pg/repo.rsindex 0118d38a50..c6e8ff9715 100644--- a/crates/stream/src/outbound/redis_pg/repo.rs+++ b/crates/stream/src/outbound/redis_pg/repo.rs@@ -296,3 +296,10 @@ impl StreamRepo for RedisPostgresStreamRepo {.subscribe()}}++// The domain error stays sqlx-free; this adapter owns the mapping.+impl From<sqlx::Error> for StreamServiceError {+ fn from(value: sqlx::Error) -> Self {+ Self::StorageError(value.to_string())+ }+}diff --git a/crates/system_properties/Cargo.toml b/crates/system_properties/Cargo.tomlindex 46f757660c..ab20801593 100644--- a/crates/system_properties/Cargo.toml+++ b/crates/system_properties/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+rootcause = { workspace = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }models_properties = { path = "../models_properties" }diff --git a/crates/system_properties/src/domain/model/error.rs b/crates/system_properties/src/domain/model/error.rsindex 5eac1321da..7760f87d8c 100644--- a/crates/system_properties/src/domain/model/error.rs+++ b/crates/system_properties/src/domain/model/error.rs@@ -7,7 +7,7 @@ use thiserror::Error;pub enum SystemPropertyError {/// Database error#[error("Database error: {0}")]- Database(#[from] sqlx::Error),+ Database(rootcause::Report),/// Serialization error#[error("Serialization error: {0}")]diff --git a/crates/system_properties/src/outbound/pgpool/mod.rs b/crates/system_properties/src/outbound/pgpool/mod.rsindex c7bed4d8f4..ec8ce66d41 100644--- a/crates/system_properties/src/outbound/pgpool/mod.rs+++ b/crates/system_properties/src/outbound/pgpool/mod.rs@@ -226,3 +226,12 @@ impl SystemPropertiesRepository for PgSystemPropertiesRepository {Ok(())}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for crate::SystemPropertyError {+ fn from(e: sqlx::Error) -> Self {+ Self::Database(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/task_dedup/Cargo.toml b/crates/task_dedup/Cargo.tomlindex f07cd8145a..3672dc9a49 100644--- a/crates/task_dedup/Cargo.toml+++ b/crates/task_dedup/Cargo.toml@@ -36,6 +36,7 @@ backfill = [default = ["backfill"][dependencies]+rootcause = { workspace = true }agent = { path = "../agent" }ai_usage = { path = "../ai_usage" }anyhow = { workspace = true }diff --git a/crates/task_dedup/src/domain/models.rs b/crates/task_dedup/src/domain/models.rsindex fad72a6bd1..2d9b2295a4 100644--- a/crates/task_dedup/src/domain/models.rs+++ b/crates/task_dedup/src/domain/models.rs@@ -103,8 +103,8 @@ pub enum TaskDedupError {#[error("duplicate match not found")]MatchNotFound,/// Persistence failed.- #[error(transparent)]- Storage(#[from] sqlx::Error),+ #[error("storage error: {0}")]+ Storage(rootcause::Report),/// Pipeline dependency failed.#[error(transparent)]Dependency(#[from] anyhow::Error),diff --git a/crates/task_dedup/src/outbound/postgres.rs b/crates/task_dedup/src/outbound/postgres.rsindex f9579e6c6c..6c83d22f7f 100644--- a/crates/task_dedup/src/outbound/postgres.rs+++ b/crates/task_dedup/src/outbound/postgres.rs@@ -564,3 +564,12 @@ fn search_key_static(key: &str) -> Option<&'static str> {_ => None,}}++// The domain error stays sqlx-free; this adapter owns the mapping so `?`+// works on sqlx results throughout the crate's outbound code. The raw sqlx+// error travels inside the report.+impl From<sqlx::Error> for TaskDedupError {+ fn from(e: sqlx::Error) -> Self {+ Self::Storage(rootcause::report!(e).into_dynamic())+ }+}diff --git a/crates/teams/src/inbound/toolset/list_team_members.rs b/crates/teams/src/inbound/toolset/list_team_members.rsindex 3a1601f298..2fd86e6c99 100644--- a/crates/teams/src/inbound/toolset/list_team_members.rs+++ b/crates/teams/src/inbound/toolset/list_team_members.rs@@ -156,7 +156,9 @@ fn team_access_error(err: AccessError) -> ToolCallError {}AccessError::NotFound(_) => "team not found",AccessError::BadRequest(_) => "invalid team membership",- AccessError::DatabaseError(_) | AccessError::Internal => "failed to verify team membership",+ AccessError::Unavailable(_) | AccessError::Internal(_) => {+ "failed to verify team membership"+ }};ToolCallError {diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rsindex d74598f963..5c8147ad6f 100644--- a/crates/webhook/src/domain/ingestion.rs+++ b/crates/webhook/src/domain/ingestion.rs@@ -62,14 +62,15 @@ pub enum WebhookEventIngestionError {impl WebhookEventIngestionError {/// Whether retrying the same event could plausibly succeed.///- /// Access resolution currently maps some PostgreSQL failures to- /// [`AccessError::Internal`], so that variant remains retryable alongside- /// explicit database, repository, workspace-resolution, and queue errors.- /// Invalid broker contracts are permanent and can be safely skipped.+ /// Access resolution classifies failures at the database boundary:+ /// [`AccessError::Unavailable`] is a connection-level or retryable+ /// Postgres failure, while [`AccessError::Internal`] is a bug or bad+ /// data that retrying cannot fix. Invalid broker contracts are+ /// permanent and can be safely skipped.pub fn is_transient(&self) -> bool {matches!(self,- Self::EntityAccess(AccessError::DatabaseError(_) | AccessError::Internal)+ Self::EntityAccess(AccessError::Unavailable(_))| Self::WorkspaceResolution(_)| Self::Repository(_)| Self::Enqueue(_)diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 10c4fd6a66..9c8e6846d3 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -159,7 +159,7 @@ impl EntityAccessService for MockAccessService {) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {lock(&self.calls).push((entity_id.to_string(), entity_type));match self.failure {- Some(AccessFailure::Internal) => Err(AccessError::Internal),+ Some(AccessFailure::Internal) => Err(AccessError::internal("mock access failure")),None => Ok(self.users.clone()),}}@@ -1266,11 +1266,13 @@ async fn malformed_document_id_is_permanent_and_skips_access_resolution() {#[test]fn classifies_adapter_and_contract_errors() {- let database_error = WebhookEventIngestionError::EntityAccess(AccessError::DatabaseError(- sqlx::Error::PoolTimedOut,- ));- assert!(database_error.is_transient());- assert!(WebhookEventIngestionError::EntityAccess(AccessError::Internal).is_transient());+ let transient_db_error =+ WebhookEventIngestionError::EntityAccess(AccessError::from(sqlx::Error::PoolTimedOut));+ assert!(transient_db_error.is_transient());+ let permanent_db_error =+ WebhookEventIngestionError::EntityAccess(AccessError::from(sqlx::Error::RowNotFound));+ assert!(!permanent_db_error.is_transient());+ assert!(!WebhookEventIngestionError::EntityAccess(AccessError::internal("bug")).is_transient());assert!(!WebhookEventIngestionError::EntityAccess(AccessError::Unauthorized).is_transient());let serialization_error = serde_json::from_str::<Value>("{").expect_err("invalid json");@@ -1281,7 +1283,7 @@ fn classifies_adapter_and_contract_errors() {}#[tokio::test]-async fn entity_access_internal_error_is_transient() {+async fn entity_access_internal_error_is_not_transient() {let access = MockAccessService {users: Vec::new(),failure: Some(AccessFailure::Internal),@@ -1299,9 +1301,9 @@ async fn entity_access_internal_error_is_transient() {assert!(matches!(error,- WebhookEventIngestionError::EntityAccess(AccessError::Internal)+ WebhookEventIngestionError::EntityAccess(AccessError::Internal(_))));- assert!(error.is_transient());+ assert!(!error.is_transient());}fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent>diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex 54fff2c28e..4aadb0d808 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -18,6 +18,7 @@ publish = falseaes-gcm = { version = "0.10", features = ["zeroize"] }ahash = { version = "0.8" }aho-corasick = { version = "1" }+anyhow = { version = "1" }aws-config = { version = "1", features = ["behavior-version-latest"] }aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }aws-runtime = { version = "1", default-features = false, features = ["event-stream", "http-02x", "http-1x", "sigv4a"] }@@ -147,6 +148,7 @@ zeroize = { version = "1", features = ["derive"] }aes-gcm = { version = "0.10", features = ["zeroize"] }ahash = { version = "0.8" }aho-corasick = { version = "1" }+anyhow = { version = "1" }aws-config = { version = "1", features = ["behavior-version-latest"] }aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }aws-runtime = { version = "1", default-features = false, features = ["event-stream", "http-02x", "http-1x", "sigv4a"] }diff --git a/rules/ast-grep/rust-no-sqlx-in-domain.yml b/rules/ast-grep/rust-no-sqlx-in-domain.ymlnew file mode 100644index 0000000000..df3c526f99--- /dev/null+++ b/rules/ast-grep/rust-no-sqlx-in-domain.yml@@ -0,0 +1,31 @@+id: rust-no-sqlx-in-domain+language: rust+severity: error+message: Domain modules must not reference sqlx — database access belongs in outbound adapters behind a port.+note: |-+ Hexagonal architecture: the domain layer depends only on its own models and+ port traits. Move the query into an outbound repo (e.g. outbound/pg_*_repo.rs)+ and expose it through a port. Domain error variants carry causes as+ `rootcause::Report` payloads, never as sqlx types; keep the+ `impl From<sqlx::Error> for <DomainError>` in the outbound module (see+ entity_access's pg_access_repo, which also classifies transient failures+ as `Unavailable` there) so `?` still works in adapter code. DB-backed+ tests (#[sqlx::test]) in domain test.rs files are exempt.+files:+ - crates/**/src/domain/**+ignores:+ - '**/test.rs'+ - '**/tests.rs'+ - '**/test/**'+ - '**/tests/**'+rule:+ any:+ - kind: scoped_identifier+ regex: ^sqlx\b+ not:+ inside:+ kind: scoped_identifier+ - kind: scoped_type_identifier+ regex: ^sqlx\b+ - kind: use_declaration+ regex: ^use sqlx\bdiff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 2e3019d2b8..2d7d62c9cc 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -453,7 +453,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arlet memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(- pool.clone(),memory_repo,tool_service_context.clone(),all_tools,diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 6a47058bff..0797353919 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -618,7 +618,6 @@ async fn main() -> anyhow::Result<()> {// Build memory servicelet memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(db.clone());let memory_service = Arc::new(memory::domain::service::MemoryServiceImpl::new(- db.clone(),memory_repo,tool_service_context.clone(),all_tools,diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rsindex 73a7b8f6df..0421f7f92e 100644--- a/services/document_storage_service/src/service/entity_mutation.rs+++ b/services/document_storage_service/src/service/entity_mutation.rs@@ -108,7 +108,7 @@ fn access_failure(error: AccessError) -> EntityMutationErrorCode {error @ AccessError::BadRequest(_) => {EntityMutationErrorCode::invalid(rootcause::report!(error))}- error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {+ error @ (AccessError::Unavailable(_) | AccessError::Internal(_)) => {EntityMutationErrorCode::internal(rootcause::report!(error))}}diff --git a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rsindex e0fbd2e8ef..8ff1db4bbf 100644--- a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs+++ b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs@@ -66,12 +66,8 @@ async fn fetch_user_memory(toolset: tools.toolset,prompt: tools.prompt,};- let memory_service = MemoryServiceImpl::new(- db.clone(),- PgMemoryRepo::new(db.clone()),- tool_context.clone(),- tools,- );+ let memory_service =+ MemoryServiceImpl::new(PgMemoryRepo::new(db.clone()), tool_context.clone(), tools);match memory_service.get_or_generate_memory(owner.clone()).await {Ok(memory) => memory,Err(e) => {