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
feat(ai): gate usage settlement behind ENABLE_AI_USAGE_BILLING (#7307)
Will Hutchinson376af6e83ef9
diff --git a/Cargo.lock b/Cargo.lockindex d6f601636e..15a8857009 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -713,7 +713,6 @@ dependencies = ["lexical_client","macro_config","macro_entrypoint",- "macro_env","macro_env_var","macro_event_broker","macro_service_urls",@@ -764,7 +763,6 @@ dependencies = ["chrono","macro_authorization","macro_db_migrator",- "macro_env","macro_user_id","macro_uuid","roles_and_permissions",diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.tomlindex a172543393..64f55db307 100644--- a/crates/ai_billing/Cargo.toml+++ b/crates/ai_billing/Cargo.toml@@ -22,7 +22,6 @@ chrono = { workspace = true }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum",] }-macro_env = { path = "../macro_env" }macro_user_id = { path = "../macro_user_id", features = ["schema"] }macro_uuid = { path = "../macro_uuid" }roles_and_permissions = { path = "../roles_and_permissions", default-features = false, features = [diff --git a/crates/ai_billing/src/composition.rs b/crates/ai_billing/src/composition.rsindex d643ac4709..7c5daa99db 100644--- a/crates/ai_billing/src/composition.rs+++ b/crates/ai_billing/src/composition.rs@@ -5,7 +5,6 @@ use crate::{domain::BillingServiceImpl,outbound::{NoOpPaymentGateway, PgBillingRepo, PgUsageReader, RolesTeamsEntitlementSource},};-use macro_env::Environment;use roles_and_permissions::domain::port::UserRolesAndPermissionsService;use sqlx::PgPool;use std::sync::Arc;@@ -19,7 +18,6 @@ mod test;#[cfg(feature = "pg-admission")]pub fn pg_admission_service(pool: PgPool,- environment: Environment,enforcement: AiUsageEnforcement,) -> Arc<dyn AiAdmissionService> {admission_service(@@ -29,20 +27,20 @@ pub fn pg_admission_service(roles_and_permissions::outbound::pgpool::MacroDB::new(pool.clone()),),teams::outbound::team_repo::TeamRepositoryImpl::new(pool),- environment,enforcement,)}/// Compose admission from the host's existing roles service, team repository and/// database pool. Both admission and billing receive the same explicit policy.-/// This service never settles usage, requests collection, or installs financial funding.-/// Hosts already owning a billing instance can wrap it with [`BillingAdmissionService`].+/// This service never settles usage, requests collection, or installs financial+/// funding: its settlement policy stays disabled regardless of the host's+/// `ENABLE_AI_USAGE_BILLING`. Hosts already owning a billing instance can wrap+/// it with [`BillingAdmissionService`].pub fn admission_service<P, T>(pool: PgPool,permissions: P,teams: T,- environment: Environment,enforcement: AiUsageEnforcement,) -> Arc<dyn AiAdmissionService>where@@ -54,7 +52,6 @@ wherePgUsageReader::new(pool.clone()),PgBillingRepo::new(pool),NoOpPaymentGateway,- environment,).with_enforcement(enforcement);Arc::new(BillingAdmissionService::new(Arc::new(billing), enforcement))diff --git a/crates/ai_billing/src/composition/test.rs b/crates/ai_billing/src/composition/test.rsindex 8a4019045b..61e8172cc1 100644--- a/crates/ai_billing/src/composition/test.rs+++ b/crates/ai_billing/src/composition/test.rs@@ -73,28 +73,21 @@ async fn configured_composition_skips_billing_only_for_disabled_or_exempt_work().unwrap();pool.close().await;let user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();- for environment in [- Environment::Local,- Environment::Develop,- Environment::Production,- ] {- let disabled =- pg_admission_service(pool.clone(), environment, AiUsageEnforcement::Disabled);- assert_eq!(disabled.admit(&user, AiFeature::Chat).await, Ok(()));+ let disabled = pg_admission_service(pool.clone(), AiUsageEnforcement::Disabled);+ assert_eq!(disabled.admit(&user, AiFeature::Chat).await, Ok(()));- let enabled = pg_admission_service(pool.clone(), environment, AiUsageEnforcement::Enabled);- for feature in ai_usage::NON_BILLABLE_AI_FEATURES {- assert_eq!(enabled.admit(&user, feature).await, Ok(()));- }- assert_eq!(- enabled- .admit(&ai_usage::SYSTEM_USER_ID, AiFeature::Chat)- .await,- Ok(())- );- assert_eq!(- enabled.admit(&user, AiFeature::Chat).await,- Err(AiAdmissionError::Unavailable)- );+ let enabled = pg_admission_service(pool.clone(), AiUsageEnforcement::Enabled);+ for feature in ai_usage::NON_BILLABLE_AI_FEATURES {+ assert_eq!(enabled.admit(&user, feature).await, Ok(()));}+ assert_eq!(+ enabled+ .admit(&ai_usage::SYSTEM_USER_ID, AiFeature::Chat)+ .await,+ Ok(())+ );+ assert_eq!(+ enabled.admit(&user, AiFeature::Chat).await,+ Err(AiAdmissionError::Unavailable)+ );}diff --git a/crates/ai_billing/src/config.rs b/crates/ai_billing/src/config.rsnew file mode 100644index 0000000000..1639f6a868--- /dev/null+++ b/crates/ai_billing/src/config.rs@@ -0,0 +1,34 @@+//! Startup configuration for AI usage settlement.++use crate::domain::AiUsageBilling;++#[cfg(test)]+mod test;++// Keep configuration deserialization outside the domain policy. MacroConfig+// parses the raw Doppler/environment value as a strict boolean.+impl<'de> serde::Deserialize<'de> for AiUsageBilling {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let enabled = bool::deserialize(deserializer)?;+ Ok(if enabled {+ Self::Enabled+ } else {+ Self::Disabled+ })+ }+}++/// Load `ENABLE_AI_USAGE_BILLING` once at service startup.+///+/// Missing means disabled. Only `true` and `false` are accepted when present;+/// malformed or non-Unicode values return an error that the host must propagate+/// to fail startup. Hosts using MacroConfig must call this loader as well, for+/// the same reasons as [`ai_usage::config::load_ai_usage_enforcement`]. This+/// policy does not enable quota admission or usage counting.+pub fn load_ai_usage_billing() -> Result<AiUsageBilling, rootcause::Report> {+ if ai_usage::config::load_startup_flag("ENABLE_AI_USAGE_BILLING")? {+ Ok(AiUsageBilling::Enabled)+ } else {+ Ok(AiUsageBilling::Disabled)+ }+}diff --git a/crates/ai_billing/src/config/test.rs b/crates/ai_billing/src/config/test.rsnew file mode 100644index 0000000000..83508a3e2b--- /dev/null+++ b/crates/ai_billing/src/config/test.rs@@ -0,0 +1,27 @@+use super::*;++#[test]+fn deserialized_booleans_select_settlement_policy() {+ assert_eq!(+ serde_json::from_value::<AiUsageBilling>(serde_json::json!(true)).unwrap(),+ AiUsageBilling::Enabled+ );+ assert_eq!(+ serde_json::from_value::<AiUsageBilling>(serde_json::json!(false)).unwrap(),+ AiUsageBilling::Disabled+ );+ for value in [+ serde_json::json!("true"),+ serde_json::json!(1),+ serde_json::json!(null),+ ] {+ assert!(serde_json::from_value::<AiUsageBilling>(value).is_err());+ }+}++#[test]+fn default_policy_is_disabled() {+ assert_eq!(AiUsageBilling::default(), AiUsageBilling::Disabled);+ assert!(!AiUsageBilling::Disabled.is_enabled());+ assert!(AiUsageBilling::Enabled.is_enabled());+}diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex 47db47cc6a..8bcfff7c57 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -16,8 +16,8 @@ pub use admission::{};pub use ledger::{SettlementPlan, SettlementPolicy, SettlementState, plan_settlement};pub use models::{- AllowanceDecision, AllowanceStore, BillingError, BillingPeriod, BillingSettings,- CREDIT_PACKS_CENTS, DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS,+ AiUsageBilling, AllowanceDecision, AllowanceStore, BillingError, BillingPeriod,+ BillingSettings, CREDIT_PACKS_CENTS, DenyReason, Entitlement, MIN_STRIPE_CHARGE_CENTS,OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,OpenPeriodStart, OverageChargeStatus, PayerScope, PeriodAllowance, PeriodLedger, PlanTier,Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope, TARGET_GROSS_MARGIN_BPS,diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex fec32118e3..88b26c5441 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -10,6 +10,27 @@ use std::collections::HashSet;use thiserror::Error;use utoipa::ToSchema;+/// Whether usage past a payer's allowance is settled: prepaid credits consumed+/// and overage collected through Stripe. Hosts load it from+/// `ENABLE_AI_USAGE_BILLING` at startup. It is independent of quota admission+/// ([`AiUsageEnforcement`](ai_usage::AiUsageEnforcement)) and of the deployment+/// environment.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub enum AiUsageBilling {+ /// Never consume credits, reserve overage, or collect payment.+ #[default]+ Disabled,+ /// Settle uncovered usage from credits, then collect overage.+ Enabled,+}++impl AiUsageBilling {+ /// Whether settlement is enabled.+ pub const fn is_enabled(self) -> bool {+ matches!(self, Self::Enabled)+ }+}+/// Persisted usage-policy identity, independent of purchase availability or today's roles./// A verified period activation selects this value; legacy records are never repriced.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex 2976f6dd3f..ce64786813 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -6,10 +6,10 @@ mod test;use super::ledger::{SettlementPolicy, build_snapshot, decide};use super::models::{- AllowanceDecision, AllowanceStore, BillingError, BillingPeriod, BillingSettings,- CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS,- OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PlanTier, Result,- SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,+ AiUsageBilling, AllowanceDecision, AllowanceStore, BillingError, BillingPeriod,+ BillingSettings, CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS,+ OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope,+ PeriodAllowance, PlanTier, Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,};use super::period::{PeriodSync, SubscriptionPeriod};use super::ports::{@@ -18,7 +18,6 @@ use super::ports::{};use ai_usage::AiUsageEnforcement;use chrono::{DateTime, Utc};-use macro_env::Environment;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use macro_uuid::Uuid;use std::sync::Arc;@@ -31,32 +30,39 @@ pub struct BillingServiceImpl<E, U, R, P> {usage: U,repo: R,payments: P,- environment: Environment,enforcement: AiUsageEnforcement,+ billing: AiUsageBilling,period_sync: Option<Arc<dyn PeriodSync>>,}impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {- /// Construct with quota enforcement disabled. Settlement remains dev-only.- /// Production composition must explicitly install the configured enforcement policy.- pub fn new(entitlements: E, usage: U, repo: R, payments: P, environment: Environment) -> Self {+ /// Construct with quota enforcement and settlement both disabled. Production+ /// composition must explicitly install each configured policy.+ pub fn new(entitlements: E, usage: U, repo: R, payments: P) -> Self {Self {entitlements,usage,repo,payments,- environment,enforcement: AiUsageEnforcement::Disabled,+ billing: AiUsageBilling::Disabled,period_sync: None,}}- /// Configure quota enforcement independently of the settlement environment guard.+ /// Configure quota enforcement independently of settlement.pub fn with_enforcement(mut self, enforcement: AiUsageEnforcement) -> Self {self.enforcement = enforcement;self}+ /// Configure settlement (credit consumption and overage collection) from+ /// the host's `ENABLE_AI_USAGE_BILLING` policy, independently of admission.+ pub fn with_billing(mut self, billing: AiUsageBilling) -> Self {+ self.billing = billing;+ self+ }+/// Install verified renewal activation at the composition root only after the/// producer and rollout gates pass. Absence never authorizes the new policy.pub fn with_period_sync(mut self, period_sync: Arc<dyn PeriodSync>) -> Self {@@ -508,7 +514,7 @@ where#[tracing::instrument(skip(self), err)]async fn settle(&self, user: &MacroUserIdStr<'_>) -> Result<()> {// Guard every caller: summary reads, settings, purchases, and internal settlement.- if !matches!(self.environment, Environment::Develop) {+ if !self.billing.is_enabled() {return Ok(());}let now = Utc::now();diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex f9f1a0954a..7209e72865 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -570,11 +570,11 @@ async fn period_sync_is_gated_and_never_calls_payments_or_changes_item_anchors()type Service = BillingServiceImpl<FakeEntitlements, FakeUsage, FakeRepo, FakePayments>;fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsage) {- premium_service_in(Environment::Develop, used_cents)+ premium_service_with(AiUsageBilling::Enabled, used_cents)}-fn premium_service_in(- environment: Environment,+fn premium_service_with(+ billing: AiUsageBilling,used_cents: i64,) -> (Service, FakeRepo, FakePayments, FakeUsage) {let payer = user("[email protected]");@@ -588,14 +588,9 @@ fn premium_service_in(let repo = FakeRepo::default();let payments = FakePayments::default();(- BillingServiceImpl::new(- ents,- usage.clone(),- repo.clone(),- payments.clone(),- environment,- )- .with_enforcement(AiUsageEnforcement::Enabled),+ BillingServiceImpl::new(ents, usage.clone(), repo.clone(), payments.clone())+ .with_enforcement(AiUsageEnforcement::Enabled)+ .with_billing(billing),repo,payments,usage,@@ -647,8 +642,8 @@ async fn policy_activation_during_analytics_read_cannot_double_bill() {ActivatingUsage(repo.clone()),repo.clone(),payments.clone(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);svc.settle(&user("[email protected]")).await.unwrap();assert!(repo.state.lock().unwrap().consumed.is_empty());assert!(repo.charges().is_empty());@@ -675,13 +670,9 @@ async fn allows_within_allowance_and_denies_past_it() {}#[tokio::test]-async fn disabled_allows_exhausted_allowances_caps_and_failed_payments_in_every_environment() {- for environment in [- Environment::Local,- Environment::Develop,- Environment::Production,- ] {- let (svc, repo, _, _) = premium_service_in(environment, 1_000_000);+async fn disabled_allows_exhausted_allowances_caps_and_failed_payments_regardless_of_settlement() {+ for billing in [AiUsageBilling::Disabled, AiUsageBilling::Enabled] {+ let (svc, repo, _, _) = premium_service_with(billing, 1_000_000);let svc = svc.with_enforcement(AiUsageEnforcement::Disabled);let payer = user("[email protected]");assert_eq!(@@ -708,13 +699,9 @@ async fn disabled_allows_exhausted_allowances_caps_and_failed_payments_in_every_}#[tokio::test]-async fn enabled_enforces_allowances_in_every_environment_without_settlement() {- for environment in [- Environment::Local,- Environment::Develop,- Environment::Production,- ] {- let (svc, repo, payments, usage) = premium_service_in(environment, 4_000);+async fn enabled_enforces_allowances_under_either_settlement_policy_without_settling() {+ for billing in [AiUsageBilling::Disabled, AiUsageBilling::Enabled] {+ let (svc, repo, payments, usage) = premium_service_with(billing, 4_000);let payer = user("[email protected]");assert_eq!(svc.check_allowance(&payer).await.unwrap(),@@ -743,7 +730,7 @@ async fn enabled_enforces_allowances_in_every_environment_without_settlement() {}#[tokio::test]-async fn default_disabled_gate_and_production_settlement_do_not_read_entitlements() {+async fn default_disabled_gate_and_disabled_settlement_do_not_read_entitlements() {struct PanicEntitlements;impl EntitlementSource for PanicEntitlements {async fn entitlement(&self, _: &MacroUserIdStr<'_>) -> Result<Entitlement> {@@ -756,94 +743,82 @@ async fn default_disabled_gate_and_production_settlement_do_not_read_entitlementpanic!("must not resolve a team payer")}}- for environment in [- Environment::Local,- Environment::Develop,- Environment::Production,- ] {- let svc = BillingServiceImpl::new(- PanicEntitlements,- FakeUsage::default(),- FakeRepo::default(),- FakePayments::default(),- environment,- );- assert_eq!(- svc.check_allowance(&user("[email protected]")).await.unwrap(),- AllowanceDecision::Allow- );- if !matches!(environment, Environment::Develop) {- svc.with_enforcement(AiUsageEnforcement::Enabled)- .settle(&user("[email protected]"))- .await- .unwrap();- }- }+ let svc = BillingServiceImpl::new(+ PanicEntitlements,+ FakeUsage::default(),+ FakeRepo::default(),+ FakePayments::default(),+ );+ assert_eq!(+ svc.check_allowance(&user("[email protected]")).await.unwrap(),+ AllowanceDecision::Allow+ );+ // Quota enforcement alone never turns settlement on.+ svc.with_enforcement(AiUsageEnforcement::Enabled)+ .settle(&user("[email protected]"))+ .await+ .unwrap();}#[tokio::test]-async fn outside_dev_preserves_credits_and_never_reserves_or_collects_overage() {- for environment in [Environment::Production, Environment::Local] {- let (mut svc, repo, payments, usage, _, payer, previous, current) =- anchored_premium(1_000_000);- svc.environment = environment;- svc.sync_period(&payer, current.start, current.end, None)- .await- .unwrap();- usage.add(- &payer,- previous.start + chrono::Duration::days(2),- 1_000_000,- );+async fn disabled_settlement_preserves_credits_and_never_reserves_or_collects_overage() {+ let (mut svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(1_000_000);+ svc.billing = AiUsageBilling::Disabled;+ svc.sync_period(&payer, current.start, current.end, None)+ .await+ .unwrap();+ usage.add(+ &payer,+ previous.start + chrono::Duration::days(2),+ 1_000_000,+ );- svc.update_overage(&payer, true, 10_000).await.unwrap();- svc.apply_credit_purchase(&payer, 2_500, "cs_paused")- .await- .unwrap();- svc.apply_credit_purchase(&payer, 2_500, "cs_paused")- .await- .unwrap();- svc.settle(&payer).await.unwrap();- svc.settle(&payer).await.unwrap();+ svc.update_overage(&payer, true, 10_000).await.unwrap();+ svc.apply_credit_purchase(&payer, 2_500, "cs_paused")+ .await+ .unwrap();+ svc.apply_credit_purchase(&payer, 2_500, "cs_paused")+ .await+ .unwrap();+ svc.settle(&payer).await.unwrap();+ svc.settle(&payer).await.unwrap();- let snapshot = svc.snapshot(&payer).await.unwrap();- assert_eq!(snapshot.used_cents, 1_000_000);- assert_eq!(snapshot.credit_balance_cents, 2_500);- assert_eq!(snapshot.credits_consumed_cents, 0);- assert_eq!(snapshot.overage_charged_cents, 0);- assert!(repo.state.lock().unwrap().consumed.is_empty());- assert!(repo.charges().is_empty());- assert!(payments.opened().is_empty());- assert!(payments.payments().is_empty());- }+ let snapshot = svc.snapshot(&payer).await.unwrap();+ assert_eq!(snapshot.used_cents, 1_000_000);+ assert_eq!(snapshot.credit_balance_cents, 2_500);+ assert_eq!(snapshot.credits_consumed_cents, 0);+ assert_eq!(snapshot.overage_charged_cents, 0);+ assert!(repo.state.lock().unwrap().consumed.is_empty());+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());+ assert!(payments.payments().is_empty());}#[tokio::test]-async fn outside_dev_does_not_retry_pending_or_failed_charges() {- for environment in [Environment::Production, Environment::Local] {- for status in [OverageChargeStatus::Pending, OverageChargeStatus::Failed] {- for invoice in [None, Some("in_existing".to_string())] {- let (svc, repo, payments, _) = premium_service_in(environment, 1_000_000);- let payer = user("[email protected]");- let period = BillingPeriod::current(None, Utc::now());- repo.state.lock().unwrap().charges.push(FakeCharge {- id: macro_uuid::generate_uuid_v7(),- period_start: period.start,- amount_cents: 1_000,- status,- invoice: invoice.clone(),- });-- svc.update_overage(&payer, true, 10_000).await.unwrap();- svc.settle(&payer).await.unwrap();-- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, status);- assert_eq!(charges[0].invoice, invoice);- assert!(payments.opened().is_empty());- assert!(payments.payments().is_empty());- }+async fn disabled_settlement_does_not_retry_pending_or_failed_charges() {+ for status in [OverageChargeStatus::Pending, OverageChargeStatus::Failed] {+ for invoice in [None, Some("in_existing".to_string())] {+ let (svc, repo, payments, _) =+ premium_service_with(AiUsageBilling::Disabled, 1_000_000);+ let payer = user("[email protected]");+ let period = BillingPeriod::current(None, Utc::now());+ repo.state.lock().unwrap().charges.push(FakeCharge {+ id: macro_uuid::generate_uuid_v7(),+ period_start: period.start,+ amount_cents: 1_000,+ status,+ invoice: invoice.clone(),+ });++ svc.update_overage(&payer, true, 10_000).await.unwrap();+ svc.settle(&payer).await.unwrap();++ let charges = repo.charges();+ assert_eq!(charges.len(), 1);+ assert_eq!(charges[0].status, status);+ assert_eq!(charges[0].invoice, invoice);+ assert!(payments.opened().is_empty());+ assert!(payments.payments().is_empty());}}}@@ -1091,8 +1066,8 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {FakeUsage::default(),FakeRepo::default(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);assert!(matches!(svc.update_overage(&member, true, 1_000).await,@@ -1152,14 +1127,10 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {let usage = FakeUsage::default();usage.add(&member, Utc::now(), 5_000);let repo = FakeRepo::default();- let service = BillingServiceImpl::new(- entitlements,- usage,- repo.clone(),- FakePayments::default(),- Environment::Develop,- )- .with_enforcement(AiUsageEnforcement::Enabled);+ let service =+ BillingServiceImpl::new(entitlements, usage, repo.clone(), FakePayments::default())+ .with_billing(AiUsageBilling::Enabled)+ .with_enforcement(AiUsageEnforcement::Enabled);let owner_snapshot = service.snapshot(&owner).await.unwrap();assert_eq!(owner_snapshot.used_cents, 0);@@ -1315,13 +1286,8 @@ fn anchored_premium(};let repo = FakeRepo::default();let payments = FakePayments::default();- let svc = BillingServiceImpl::new(- ents.clone(),- usage.clone(),- repo.clone(),- payments.clone(),- Environment::Develop,- );+ let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone())+ .with_billing(AiUsageBilling::Enabled);let current_start = Utc::now() - chrono::Duration::days(3);let current_end = current_start + chrono::Duration::days(30);let current = BillingPeriod {@@ -1442,13 +1408,8 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {let usage = FakeUsage::default();let repo = FakeRepo::default();let payments = FakePayments::default();- let svc = BillingServiceImpl::new(- ents.clone(),- usage.clone(),- repo.clone(),- payments.clone(),- Environment::Develop,- );+ let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone())+ .with_billing(AiUsageBilling::Enabled);let current_start = Utc::now() - chrono::Duration::days(3);let current_end = current_start + chrono::Duration::days(30);let current = BillingPeriod {@@ -1544,8 +1505,8 @@ async fn release_targets_the_payer_open_period() {FakeUsage::default(),repo.clone(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);svc.release(team_id, &member).await.unwrap();@@ -1579,8 +1540,8 @@ async fn release_missing_team_leaves_allowances_unchanged() {FakeUsage::default(),repo.clone(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);svc.release(Uuid::from_u128(8), &member).await.unwrap();@@ -1617,8 +1578,8 @@ async fn release_refuses_to_remove_the_payer() {FakeUsage::default(),repo.clone(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);svc.release(team_id, &owner).await.unwrap();@@ -1670,8 +1631,8 @@ async fn position_keeps_matching_pairs_in_their_stored_order() {FakeUsage::default(),repo.clone(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);svc.position(&owner, now).await.unwrap();@@ -1733,8 +1694,8 @@ async fn position_does_not_restore_a_member_released_between_entitlement_reads()FakeUsage::default(),repo.clone(),FakePayments::default(),- Environment::Develop,- );+ )+ .with_billing(AiUsageBilling::Enabled);let position = svc.position(&owner, now).await.unwrap();diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rsindex 822780fbc3..f06cd9845c 100644--- a/crates/ai_billing/src/lib.rs+++ b/crates/ai_billing/src/lib.rs@@ -28,6 +28,8 @@//! wrapper that triggers settlement after usage lands.//! - [`inbound`] — the axum router (summary, overage settings, credit//! checkout, internal settle).+//! - [`config`] — the startup loader for `ENABLE_AI_USAGE_BILLING`, the+//! default-off policy that gates settlement in every environment.//!//! The *payer* is the account that owns credits, overage settings, and the//! Stripe customer: the personal subscriber, or the team owner for members@@ -35,13 +37,14 @@//! only its own plan allowance; credits and overage are shared by the payer.pub mod composition;+pub mod config;pub mod domain;pub mod inbound;pub mod outbound;pub use ai_usage::{AiFeature, AiUsageEnforcement};pub use domain::{- AdmissionFuture, AiAdmissionError, AiAdmissionService, AllowanceDecision,+ AdmissionFuture, AiAdmissionError, AiAdmissionService, AiUsageBilling, AllowanceDecision,BillingAdmissionService, BillingError, BillingPeriod, BillingService, BillingSettings,CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement, PayerScope, PlanTier,TARGET_GROSS_MARGIN_BPS, UsageSnapshot, list_rate_cents,diff --git a/crates/ai_billing/src/outbound/settling_recorder.rs b/crates/ai_billing/src/outbound/settling_recorder.rsindex 94a09c9f8a..735f15328a 100644--- a/crates/ai_billing/src/outbound/settling_recorder.rs+++ b/crates/ai_billing/src/outbound/settling_recorder.rs@@ -4,10 +4,9 @@#[cfg(test)]mod test;-use crate::domain::{BillingService, SettlementTrigger};+use crate::domain::{AiUsageBilling, BillingService, SettlementTrigger};use ai_usage::domain::service::UsageServiceImpl;use ai_usage::{UsageEvent, UsageRecorder, UsageRepo};-use macro_env::Environment;use std::sync::Arc;use std::time::Duration;@@ -19,10 +18,11 @@ const RECORD_RETRY_BACKOFF: [Duration; 3] = [Duration::from_secs(5),];-/// Wraps the Postgres usage recorder. After a counted row lands in dev it reads-/// the payer's position and, when there is uncovered usage, triggers settlement-/// (credit consumption and overage collection) in the service that owns-/// Stripe. Recording stays best-effort and never delays the completion.+/// Wraps the Postgres usage recorder. With settlement enabled, after a counted+/// row lands it reads the payer's position and, when there is uncovered usage,+/// triggers settlement (credit consumption and overage collection) in the+/// service that owns Stripe. Recording stays best-effort and never delays the+/// completion.////// A row that cannot be written is billable usage lost, so the write is/// retried with backoff before it is given up on. The retry is bounded and@@ -32,23 +32,24 @@ pub struct SettlingUsageRecorder<Repo, B, T> {inner: Arc<UsageServiceImpl<Repo>>,billing: Arc<B>,trigger: T,- environment: Environment,+ settlement: AiUsageBilling,}impl<Repo, B, T> SettlingUsageRecorder<Repo, B, T> {- /// Build the recorder. Usage is recorded everywhere; only counted usage in- /// dev can request settlement. The inner service owns the counting policy.+ /// Build the recorder. Usage is always recorded; only counted usage can+ /// request settlement, and only when the host's `ENABLE_AI_USAGE_BILLING`+ /// policy is enabled. The inner service owns the counting policy.pub fn new(inner: Arc<UsageServiceImpl<Repo>>,billing: Arc<B>,trigger: T,- environment: Environment,+ settlement: AiUsageBilling,) -> Self {Self {inner,billing,trigger,- environment,+ settlement,}}}@@ -63,8 +64,7 @@ wherelet inner = self.inner.clone();let billing = self.billing.clone();let trigger = self.trigger.clone();- let should_settle =- matches!(self.environment, Environment::Develop) && inner.counts_usage(&event);+ let should_settle = self.settlement.is_enabled() && inner.counts_usage(&event);tokio::spawn(async move {let user = event.user.clone();let mut backoff = RECORD_RETRY_BACKOFF.iter();diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rsindex a7bb834ade..5f62c85f4d 100644--- a/crates/ai_billing/src/outbound/settling_recorder/test.rs+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs@@ -119,7 +119,7 @@ impl SettlementTrigger for FakeTrigger {}async fn record(- environment: Environment,+ settlement: AiUsageBilling,user: MacroUserIdStr<'static>,tier: PlanTier,unlimited: bool,@@ -127,7 +127,7 @@ async fn record(fail_first: bool,) -> (usize, usize, usize) {record_with_policy(- environment,+ settlement,user,tier,unlimited,@@ -139,7 +139,7 @@ async fn record(}async fn record_with_policy(- environment: Environment,+ settlement: AiUsageBilling,user: MacroUserIdStr<'static>,tier: PlanTier,unlimited: bool,@@ -171,13 +171,13 @@ async fn record_with_policy(Arc::new(UsageServiceImpl::new(repo.clone()).with_enforcement(enforcement)),billing.clone(),trigger.clone(),- environment,+ settlement,);let should_count = enforcement.should_count(&user, feature);recorder.record(UsageContext::new(feature, user).into_event("test-model".into(), 10, 10));tokio::time::timeout(Duration::from_secs(2), repo.recorded.notified()).await- .expect("usage must be recorded in every environment, including after a retry");+ .expect("usage must be recorded under either settlement policy, including after a retry");// All fake billing/trigger calls are immediately ready; let the recording task finish.tokio::task::yield_now().await;assert_eq!(repo.counted.load(Ordering::SeqCst), should_count);@@ -193,15 +193,11 @@ fn user() -> MacroUserIdStr<'static> {}#[tokio::test]-async fn records_everywhere_but_only_requests_settlement_in_dev() {- for (environment, expected) in [- (Environment::Develop, 1),- (Environment::Production, 0),- (Environment::Local, 0),- ] {+async fn records_everywhere_but_only_requests_settlement_when_enabled() {+ for (settlement, expected) in [(AiUsageBilling::Enabled, 1), (AiUsageBilling::Disabled, 0)] {for fail_first in [false, true] {let (attempts, snapshots, requests) = record(- environment,+ settlement,user(),PlanTier::Premium,false,@@ -228,7 +224,7 @@ async fn uncounted_usage_never_reads_billing_or_requests_settlement() {for fail_first in [false, true] {assert_eq!(record_with_policy(- Environment::Develop,+ AiUsageBilling::Enabled,user(),PlanTier::Premium,false,@@ -247,7 +243,7 @@ async fn uncounted_usage_never_reads_billing_or_requests_settlement() {async fn system_usage_never_requests_settlement() {assert_eq!(record(- Environment::Develop,+ AiUsageBilling::Enabled,SYSTEM_USER_ID.clone(),PlanTier::Premium,false,@@ -260,7 +256,7 @@ async fn system_usage_never_requests_settlement() {}#[tokio::test]-async fn dev_does_not_settle_free_unlimited_or_covered_usage() {+async fn enabled_settlement_skips_free_unlimited_or_covered_usage() {for (tier, unlimited, chargeable) in [(PlanTier::Free, false, 1_000),(PlanTier::Premium, true, 1_000),@@ -268,7 +264,7 @@ async fn dev_does_not_settle_free_unlimited_or_covered_usage() {] {assert_eq!(record(- Environment::Develop,+ AiUsageBilling::Enabled,user(),tier,unlimited,diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 61e25da130..c8b3052bef 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -489,11 +489,7 @@ pub async fn build_tool_service_context_from_env(skill_tool_context,schedule_tool_context: crate::NoOpScheduleContext,anthropic_tool_context,- admission: ai_billing::composition::pg_admission_service(- pool.clone(),- environment,- enforcement,- ),+ admission: ai_billing::composition::pg_admission_service(pool.clone(), enforcement),recorder: ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement),usage_context: ai_usage::UsageContext::system(ai_usage::AiFeature::Chat),})diff --git a/crates/ai_usage/src/config.rs b/crates/ai_usage/src/config.rsindex 74666a7550..f6c7e78640 100644--- a/crates/ai_usage/src/config.rs+++ b/crates/ai_usage/src/config.rs@@ -24,28 +24,37 @@ impl<'de> serde::Deserialize<'de> for AiUsageEnforcement {////// Missing means disabled. Only `true` and `false` are accepted when present;/// malformed or non-Unicode values return an error that the host must propagate-/// to fail startup. This does not enable financial settlement.+/// to fail startup. This does not enable financial settlement; that is the+/// separately loaded `ENABLE_AI_USAGE_BILLING` policy.+pub fn load_ai_usage_enforcement() -> Result<AiUsageEnforcement, rootcause::Report> {+ if load_startup_flag("ENABLE_AI_USAGE_ENFORCEMENT")? {+ Ok(AiUsageEnforcement::Enabled)+ } else {+ Ok(AiUsageEnforcement::Disabled)+ }+}++/// Load a default-off `true`/`false` policy flag once at service startup.+///+/// Missing means `false`. Only raw `true` and `false` are accepted when present;+/// malformed or non-Unicode values return an error that the host must propagate+/// to fail startup.////// Hosts using MacroConfig must call this loader as well: its defaulted fields/// treat `null` as absent, but a present non-boolean flag must fail startup. The-/// returned policy is authoritative (including process-env fallback when the+/// returned value is authoritative (including process-env fallback when the/// Doppler application configuration omits the key).-pub fn load_ai_usage_enforcement() -> Result<AiUsageEnforcement, rootcause::Report> {+pub fn load_startup_flag(name: &'static str) -> Result<bool, rootcause::Report> {// Unlike maybe_env_var!, this preserves errors for present non-Unicode values.- let value = macro_env_var::optional_read_env_var("ENABLE_AI_USAGE_ENFORCEMENT")- .context("failed to read ENABLE_AI_USAGE_ENFORCEMENT")?;- parse_enforcement(value.as_deref())+ let value =+ macro_env_var::optional_read_env_var(name).context(format!("failed to read {name}"))?;+ parse_startup_flag(name, value.as_deref())}-fn parse_enforcement(value: Option<&str>) -> Result<AiUsageEnforcement, rootcause::Report> {- let enabled = value+fn parse_startup_flag(name: &str, value: Option<&str>) -> Result<bool, rootcause::Report> {+ Ok(value.map(str::parse::<bool>).transpose()- .context("ENABLE_AI_USAGE_ENFORCEMENT must be true or false")?- .unwrap_or(false);- if enabled {- Ok(AiUsageEnforcement::Enabled)- } else {- Ok(AiUsageEnforcement::Disabled)- }+ .context(format!("{name} must be true or false"))?+ .unwrap_or(false))}diff --git a/crates/ai_usage/src/config/test.rs b/crates/ai_usage/src/config/test.rsindex d6af413e8c..ef20683ddd 100644--- a/crates/ai_usage/src/config/test.rs+++ b/crates/ai_usage/src/config/test.rs@@ -1,23 +1,16 @@use super::*;+const FLAG: &str = "ENABLE_AI_USAGE_ENFORCEMENT";+#[test]-fn missing_flag_disables_enforcement() {- assert_eq!(- parse_enforcement(None).unwrap(),- AiUsageEnforcement::Disabled- );+fn missing_flag_is_off() {+ assert!(!parse_startup_flag(FLAG, None).unwrap());}#[test]fn explicit_boolean_values_select_policy() {- assert_eq!(- parse_enforcement(Some("false")).unwrap(),- AiUsageEnforcement::Disabled- );- assert_eq!(- parse_enforcement(Some("true")).unwrap(),- AiUsageEnforcement::Enabled- );+ assert!(!parse_startup_flag(FLAG, Some("false")).unwrap());+ assert!(parse_startup_flag(FLAG, Some("true")).unwrap());}#[test]@@ -25,10 +18,29 @@ fn malformed_present_values_are_errors_not_disabled_defaults() {for value in ["", "TRUE", "False", "1", "0", "yes", " true", "false\n", "garbage", "null",] {- let error = parse_enforcement(Some(value)).unwrap_err();- assert!(- error.to_string().contains("ENABLE_AI_USAGE_ENFORCEMENT"),- "{error}"- );+ let error = parse_startup_flag(FLAG, Some(value)).unwrap_err();+ assert!(error.to_string().contains(FLAG), "{error}");}}++#[test]+fn errors_name_the_flag_being_parsed() {+ let error = parse_startup_flag("ENABLE_AI_USAGE_BILLING", Some("maybe")).unwrap_err();+ assert!(+ error.to_string().contains("ENABLE_AI_USAGE_BILLING"),+ "{error}"+ );+}++#[test]+fn deserialized_booleans_select_enforcement() {+ assert_eq!(+ serde_json::from_value::<AiUsageEnforcement>(serde_json::json!(true)).unwrap(),+ AiUsageEnforcement::Enabled+ );+ assert_eq!(+ serde_json::from_value::<AiUsageEnforcement>(serde_json::json!(false)).unwrap(),+ AiUsageEnforcement::Disabled+ );+ assert!(serde_json::from_value::<AiUsageEnforcement>(serde_json::json!("true")).is_err());+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 36e751dd44..e627a34fc9 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -392,7 +392,9 @@ documents:Quota admission uses the backend's default-off `ENABLE_AI_USAGE_ENFORCEMENT`policy once configured by the host; it is independent of environment. Settlement-still runs only in `Environment::Develop`. With admission enabled, cognition chat+(credit consumption and Stripe overage collection) is gated by the separate+default-off `ENABLE_AI_USAGE_BILLING` policy, also independent of environment.+With admission enabled, cognition chatand structured completion return 402 for exhausted allowance or 503 with`ai_billing_unavailable` when validation is unavailable. Neither starts AI work;chat admission also precedes chat/message creation. Existing model and chat@@ -404,8 +406,8 @@ is unavailable, the successful chat continues with its existing/default title.Usage meters, credit controls, out-of-credit dialogs, and model usage multipliersare hidden outside frontend development mode. Normal paid-model access rulesstill apply everywhere. Backend enforcement does not depend on those frontend-controls, and enabling it does not enable production credit collection. There is-no new upgrade prompt in this rollout.+controls, and enabling it does not enable credit collection; that needs+`ENABLE_AI_USAGE_BILLING`. There is no new upgrade prompt in this rollout.Session creation and spending controls also return 402/503 for admission failures.Waiting prompts are checked again before execution: exhaustion removes rejecteddiff --git a/docs/AI_BILLING_ROLLOUT.md b/docs/AI_BILLING_ROLLOUT.mdindex c6518323e2..a610c586b8 100644--- a/docs/AI_BILLING_ROLLOUT.md+++ b/docs/AI_BILLING_ROLLOUT.md@@ -12,11 +12,12 @@ The separate [legacy quota rollout](AI_QUOTA_ENFORCEMENT.md) adds default-off`ai_usage.count_usage` writes by existing aggregate producers. Billing reads onlypersisted counted rows; historical/default-false rows remain uncounted. This isnot the financial journal's reservation/admission system. Free/unlimited policy,-feature exclusions, and the existing $40 subscription remain unchanged. Production-usage-driven credit consumption and Stripe settlement remain dev-gated even when-legacy quota enforcement is enabled. Follow that document for coordinated Doppler-registration, rollout, rollback, coverage, and limitations; this observation-matrix alone is not an enforcement or collection activation checklist.+feature exclusions, and the existing $40 subscription remain unchanged. Usage-driven+credit consumption and Stripe settlement are gated separately by the default-off+`ENABLE_AI_USAGE_BILLING` policy in every environment, even when legacy quota+enforcement is enabled. Follow that document for coordinated Doppler registration,+rollout, rollback, coverage, and limitations; this observation matrix alone is not+an enforcement or collection activation checklist.`UsageRecorder::tracking()` explicitly bridges the existing analytics injection toan object-safe `UsageTracking` capability. `agent::complete`, history/image and@@ -31,9 +32,10 @@ constructs configured prospective analytics counting alongside the owning-domainobservation service and adapter. The default-disabled `pg_recorder` remains forinternal/evaluation callers. DCS wraps its configured settling recorder with`with_tracking(..., pg_tracking(...))`; only enabled, counted usage can request-legacy settlement, and that path remains dev-only. The observation service accepts-**no funding or rate-authorization capability**. No host selects `FinancialMode::Activated` here;-its strict admission, budget validation, and error propagation remain intact.+legacy settlement, and only when `ENABLE_AI_USAGE_BILLING` is enabled. The+observation service accepts **no funding or rate-authorization capability**. No+host selects `FinancialMode::Activated` here; its strict admission, budget+validation, and error propagation remain intact.### Persistence and failure semanticsdiff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.mdindex 1c331182c4..354f02718b 100644--- a/docs/AI_QUOTA_ENFORCEMENT.md+++ b/docs/AI_QUOTA_ENFORCEMENT.md@@ -6,9 +6,10 @@prospective counting of existing `ai_usage` producers**. It is not a provider-spendcap, a reservation system, or activation of financial admission. It does not select`FinancialMode::Activated`, authorize credit holds, or convert observations into-customer debt. Production usage-driven credit consumption and Stripe settlement-remain disabled by the existing `Environment::Develop` safeguard, even with the-flag true. See [the separate observation/financial rollout](AI_BILLING_ROLLOUT.md).+customer debt. Usage-driven credit consumption and Stripe settlement are gated by+the separate default-off [`ENABLE_AI_USAGE_BILLING`](#settlement-enable_ai_usage_billing)+policy, never by this flag or the deployment environment. See+[the separate observation/financial rollout](AI_BILLING_ROLLOUT.md).The [startup loader](../crates/ai_usage/src/config.rs) accepts only raw `true` or`false`; absent means false. Empty, quoted, `null`, or otherwise malformed present@@ -57,6 +58,38 @@ and [billing-reader tests](../crates/ai_billing/src/outbound/pg_usage_reader/tescover these distinctions. Historical analytics and observations must never bebackfilled into counted usage or financial authorizations.+## Settlement: `ENABLE_AI_USAGE_BILLING`++`ENABLE_AI_USAGE_BILLING` enables **legacy settlement of counted usage past a+payer's allowance**: prepaid credits are consumed and opt-in overage is reserved+and collected through Stripe. The [startup loader](../crates/ai_billing/src/config.rs)+parses it exactly like the enforcement flag (absent means false; only raw `true`+or `false`; malformed present values fail startup) and hosts load it once. It is+independent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:+there is no longer an `Environment::Develop` safeguard, so a true value settles+in production.++Only two hosts participate:++| Host | Gate | When disabled |+| --- | --- | --- |+| Authentication service | [`BillingServiceImpl::settle`](../crates/ai_billing/src/domain/service.rs) guards every caller: summary reads, overage changes, credit-purchase webhooks, and the internal settle endpoint | Returns without reading entitlements, consuming credits, or touching Stripe. Credit purchases are still booked and remain unconsumed |+| Document cognition service | [`SettlingUsageRecorder`](../crates/ai_billing/src/outbound/settling_recorder.rs) requests settlement after counted usage lands | Usage is still recorded and counted; no settlement request is sent |++Every other host composes admission through+[`pg_admission_service`](../crates/ai_billing/src/composition.rs), which never+settles regardless of configuration. The authentication service's policy is+authoritative: a request from document cognition is a no-op there while its flag+is false, and with document cognition false the authentication service still+settles on summary reads, overage changes, and credit purchases. Enable both+together. Settlement without `ENABLE_AI_USAGE_ENFORCEMENT` finds nothing to+settle, because only counted rows are chargeable.++The frontend is not tied to this flag. The usage meter, credit packs,+usage-billing controls, the out-of-credits dialog, and model usage multipliers+keep their existing development-mode gate (`DEV_MODE_ENV`), so they show on+`dev.macro.com` and local dev builds regardless of backend settlement.+## Public failure contractsThe [shared admission port](../crates/ai_billing/src/domain/admission.rs) returns@@ -170,7 +203,7 @@ admission and R. Admission itself never records usage or calls settlement.| Scheduled agent targets / session funding policy | [target runner](../services/scheduled_action/src/domain/target_runner.rs) → session/harness admission | Target runtime's recorder, not duplicate scheduler metering | [delegation and typed errors](../services/scheduled_action/src/domain/target_runner/test.rs), [routine error transport](../crates/agent_session/src/inbound/routine_sessions/test.rs) || Memory, projection, call summary, dictation / exempt | [shared admission policy](../crates/ai_billing/src/domain/admission.rs) skips quota; ordinary permissions still apply | DCS/DSS configured recorders; [memory context](../crates/memory/src/context.rs) uses T; DSS independent call-summary/dictation recorders use R | [all exempt features](../crates/ai_usage/src/domain/counting/test.rs), [no billing I/O](../crates/ai_billing/src/domain/admission/test.rs), [configured recording](../crates/ai_billing/src/composition/test.rs) || Existing system task duplicate judge / Automation | [system attribution](../crates/task_dedup/src/outbound/judge.rs), no user quota gate | DSS main, independent R; system events stay uncounted | [system counting](../crates/ai_usage/src/domain/counting/test.rs), [system recorder behavior](../crates/ai_billing/src/outbound/settling_recorder/test.rs) |-| Billing summary (not execution) | [billing service policy](../crates/ai_billing/src/domain/service.rs) | [authentication main](../services/authentication_service/src/main.rs) configures same flag, no usage producer | [environment/free/unlimited/settlement](../crates/ai_billing/src/domain/service/test.rs), [authentication configuration](../services/authentication_service/src/config/test.rs) |+| Billing summary (not execution) | [billing service policy](../crates/ai_billing/src/domain/service.rs) | [authentication main](../services/authentication_service/src/main.rs) configures the same flag plus `ENABLE_AI_USAGE_BILLING`, no usage producer | [settlement policy/free/unlimited/settlement](../crates/ai_billing/src/domain/service/test.rs), [authentication configuration](../services/authentication_service/src/config/test.rs) |## Limits and operational risks@@ -227,15 +260,17 @@ procedure. Operators must approve and record each release gate.hosted access require operator approval; code defaults are not proof of it.4. **Validate locally, then in an approved staging environment.** Use the checklistbelow and review counts, index plans, failure rates, queue cleanup, and known- metering gaps. Confirm missing/false/true/invalid parsing and that production- settlement is still suppressed. Validate the observation privacy gate too.+ metering gaps. Confirm missing/false/true/invalid parsing and that settlement+ stays suppressed while `ENABLE_AI_USAGE_BILLING` is false. Validate the+ observation privacy gate too.5. **Coordinated, operator-approved enablement only.** Record participating hosts,deployment versions, approved environment/time, monitoring owner, and rollbackdecision. Coordinate configuration and restart/redeploy so traffic does notrely on mixed-policy replicas; drain/pause affected work if needed. Check actualstartup policy, 402/503 behavior, new counted rows, summaries, and backgroundqueues before declaring activation complete. This enables legacy quotas, **not- production credit collection or Stripe settlement**.+ credit collection or Stripe settlement**; those need `ENABLE_AI_USAGE_BILLING`+ registered and enabled for the authentication and document cognition services.### Rollbackdiff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 003c74cce6..58c4bcec76 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -290,7 +290,6 @@ async fn run() -> anyhow::Result<()> {});let admission = ai_billing::composition::pg_admission_service(pool.clone(),- config.environment,config.enable_ai_usage_enforcement,);let recorder =diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.tomlindex 242cb33bfb..f14fdc7000 100644--- a/services/agent_trigger_service/Cargo.toml+++ b/services/agent_trigger_service/Cargo.toml@@ -10,7 +10,6 @@ path = "src/main.rs"[dependencies]ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }-macro_env = { path = "../../crates/macro_env" }roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }initiative = { path = "../../crates/initiative", default-features = false, features = ["postgres"] }diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rsindex 51717d2a82..ebee34388e 100644--- a/services/agent_trigger_service/src/config.rs+++ b/services/agent_trigger_service/src/config.rs@@ -17,9 +17,6 @@ pub struct Config {/// Default-off quota admission and prospective usage counting.#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,- /// Deployment environment; settlement remains disabled in this worker.- #[macro_config_default(macro_env::Environment::new_or_prod())]- pub environment: macro_env::Environment,/// MacroDB connection URL.pub database_url: DatabaseUrl,/// Kafka bootstrap servers.diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rsindex 8daac406bc..42ff5f37bc 100644--- a/services/agent_trigger_service/src/main.rs+++ b/services/agent_trigger_service/src/main.rs@@ -115,7 +115,6 @@ async fn run() -> anyhow::Result<()> {ai_usage::pg_recorder_with_enforcement(pool.clone(), config.enable_ai_usage_enforcement);let admission = ai_billing::composition::pg_admission_service(pool.clone(),- config.environment,config.enable_ai_usage_enforcement,);let task_context = DssTaskAssignmentContext::new(diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rsindex 2fe43ebc5f..11a8923a02 100644--- a/services/authentication_service/src/config.rs+++ b/services/authentication_service/src/config.rs@@ -90,6 +90,11 @@ pub struct Config {/// Default-off quota admission and prospective usage counting.#[macro_config_default(ai_billing::AiUsageEnforcement::Disabled)]pub enable_ai_usage_enforcement: ai_billing::AiUsageEnforcement,+ /// Default-off settlement of usage past allowances: prepaid credit+ /// consumption and Stripe overage collection. This service owns Stripe, so+ /// its policy decides every settlement, however it was requested.+ #[macro_config_default(ai_billing::AiUsageBilling::Disabled)]+ pub enable_ai_usage_billing: ai_billing::AiUsageBilling,#[allow(dead_code)]pub base_url: BaseUrl,/// The connection URL for the Postgres database this application should use.@@ -200,9 +205,12 @@ impl Config {pub fn from_env() -> anyhow::Result<Self> {let enforcement = ai_usage::config::load_ai_usage_enforcement().map_err(|error| anyhow::anyhow!("{error}"))?;+ let billing = ai_billing::config::load_ai_usage_billing()+ .map_err(|error| anyhow::anyhow!("{error}"))?;let mut config = macro_config::ConfigLoader::load::<Config>().context("failed to load authentication service config")?;config.enable_ai_usage_enforcement = enforcement;+ config.enable_ai_usage_billing = billing;Ok(config)}diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rsindex ea7d2707e4..3ce240ac15 100644--- a/services/authentication_service/src/config/test.rs+++ b/services/authentication_service/src/config/test.rs@@ -2,8 +2,7 @@ use authentication_service::service::signup_policy::SignupPolicyDenial;use super::*;-#[test]-fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {+fn config_values() -> serde_json::Value {let mut values = serde_json::json!({ "ENVIRONMENT": "local" });for key in ["BASE_URL",@@ -31,6 +30,12 @@ fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {] {values[key] = serde_json::json!("test");}+ values+}++#[test]+fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {+ let mut values = config_values();let config: Config = serde_json::from_value(values.clone()).unwrap();assert_eq!(config.enable_ai_usage_enforcement,@@ -45,6 +50,25 @@ fn billing_enforcement_config_defaults_off_and_requires_a_boolean() {assert!(serde_json::from_value::<Config>(values).is_err());}+#[test]+fn billing_settlement_config_defaults_off_and_requires_a_boolean() {+ let mut values = config_values();+ let config: Config = serde_json::from_value(values.clone()).unwrap();+ assert_eq!(+ config.enable_ai_usage_billing,+ ai_billing::AiUsageBilling::Disabled+ );+ for enabled in [false, true] {+ values["ENABLE_AI_USAGE_BILLING"] = serde_json::json!(enabled);+ let config: Config = serde_json::from_value(values.clone()).unwrap();+ assert_eq!(config.enable_ai_usage_billing.is_enabled(), enabled);+ // The two policies are independent.+ assert!(!config.enable_ai_usage_enforcement.is_enabled());+ }+ values["ENABLE_AI_USAGE_BILLING"] = serde_json::json!("invalid");+ assert!(serde_json::from_value::<Config>(values).is_err());+}+#[test]fn complete_microsoft_credentials_are_resolved() {let credentials = resolve(diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex 627799e16c..466c420b09 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -508,9 +508,9 @@ async fn main() -> anyhow::Result<()> {ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone()),ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),- config.environment,)- .with_enforcement(config.enable_ai_usage_enforcement),+ .with_enforcement(config.enable_ai_usage_enforcement)+ .with_billing(config.enable_ai_usage_billing),);let teams_service_impl = TeamServiceImpl::new_with_analytics(teams_repo_impl.clone(),diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex fb154f4980..a1a39136a6 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -166,11 +166,7 @@ impl StreamRepo for MockStreamRepo {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 admission = ai_billing::composition::pg_admission_service(- pool.clone(),- config.environment,- enforcement,- );+ let admission = ai_billing::composition::pg_admission_service(pool.clone(), enforcement);let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);use aws_sdk_sqs;use channels::{@@ -626,7 +622,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_billing::outbound::PgUsageReader::new(pool.clone()),ai_billing::outbound::PgBillingRepo::new(pool.clone()),ai_billing::outbound::NoOpPaymentGateway,- config.environment,).with_enforcement(enforcement),),diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rsindex 616e0d796b..493c2c0c7b 100644--- a/services/document_cognition_service/src/config.rs+++ b/services/document_cognition_service/src/config.rs@@ -73,6 +73,11 @@ pub struct Config {/// Default-off quota admission and prospective usage counting.#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,+ /// Default-off settlement of usage past allowances. When enabled, counted+ /// usage recorded here asks the authentication service to settle; that+ /// service's own policy decides whether it does.+ #[macro_config_default(ai_billing::AiUsageBilling::Disabled)]+ pub enable_ai_usage_billing: ai_billing::AiUsageBilling,/// The connection URL for the Postgres database this application should use.pub database_url: DatabaseUrl,/// The port to listen for HTTP requests on.@@ -153,9 +158,12 @@ impl Config {pub fn from_env() -> anyhow::Result<Self> {let enforcement = ai_usage::config::load_ai_usage_enforcement().map_err(|error| anyhow::anyhow!("{error}"))?;+ let billing = ai_billing::config::load_ai_usage_billing()+ .map_err(|error| anyhow::anyhow!("{error}"))?;let mut config =macro_config::ConfigLoader::load::<Config>().context("failed to load config")?;config.enable_ai_usage_enforcement = enforcement;+ config.enable_ai_usage_billing = billing;Ok(config)}@@ -168,6 +176,7 @@ impl Config {pub fn new_empty_for_test() -> Self {Config {enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement::Disabled,+ enable_ai_usage_billing: ai_billing::AiUsageBilling::Disabled,environment: Environment::Local,database_url: DatabaseUrl::Comptime("DATABASE_URL"),port: Default::default(),diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex c9e8f8b2af..67fc4e5f81 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -474,7 +474,8 @@ async fn main() -> anyhow::Result<()> {// The AI billing gate reads allowances, credits, and overage state here;// collection (Stripe) lives in the authentication service, which the- // recorder below asks to settle once a payer runs past their allowance.+ // recorder below asks to settle once a payer runs past their allowance+ // and ENABLE_AI_USAGE_BILLING is enabled. This instance never settles.let ai_billing = Arc::new(ai_billing::domain::BillingServiceImpl::new(ai_billing::outbound::RolesTeamsEntitlementSource::new(@@ -484,7 +485,6 @@ async fn main() -> anyhow::Result<()> {ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone()),ai_billing::outbound::NoOpPaymentGateway,- config.environment,).with_enforcement(config.enable_ai_usage_enforcement),);@@ -507,11 +507,12 @@ async fn main() -> anyhow::Result<()> {),ai_billing.clone(),ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client),- config.environment,+ config.enable_ai_usage_billing,));// Per-attempt observations use a separate journal and never feed the- // legacy settlement trigger, which remains counted-usage-only and dev-only.+ // legacy settlement trigger, which remains counted-usage-only and gated by+ // ENABLE_AI_USAGE_BILLING.let recorder = ai_usage::with_tracking(recorder, ai_usage::pg_tracking(db.clone()));// The import pipeline: staged/imported external items, gather jobs overdiff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex d75d0c0688..06b2b4b2c5 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -444,7 +444,6 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toanthropic_tool_context: ai_tools::build_anthropic_tool_context(),admission: ai_billing::composition::pg_admission_service(db.clone(),- config.environment,config.enable_ai_usage_enforcement,),recorder: ai_usage::pg_recorder_with_enforcement(