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-billing): price in-plan AI at cost with a 5% overage markup (#7491)
Will Hutchinson9e4b0abe2e29
diff --git a/.sqlx/query-0090ad6b952f3c9c0cdd52c5edd45483da9f619a00204ff51ca739693936dc42.json b/.sqlx/query-0090ad6b952f3c9c0cdd52c5edd45483da9f619a00204ff51ca739693936dc42.jsonnew file mode 100644index 0000000000..57037f8302--- /dev/null+++ b/.sqlx/query-0090ad6b952f3c9c0cdd52c5edd45483da9f619a00204ff51ca739693936dc42.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE ai_billing_period_allowance AS allowance\n SET billed_users = excised.users,\n included_cents_by_user = excised.cents,\n included_cost_cents_by_user = CASE\n WHEN cardinality(allowance.included_cost_cents_by_user)\n = cardinality(allowance.billed_users)\n THEN excised.cost_cents\n END,\n updated_at = NOW()\n FROM (\n SELECT\n COALESCE(\n array_agg(seat.billed_user ORDER BY seat.ordinality)\n FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),\n ARRAY[]::text[]\n )::text[] AS users,\n COALESCE(\n array_agg(seat.included_cents ORDER BY seat.ordinality)\n FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),\n ARRAY[]::bigint[]\n )::bigint[] AS cents,\n COALESCE(\n array_agg(seat.cost_cents ORDER BY seat.ordinality)\n FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),\n ARRAY[]::bigint[]\n )::bigint[] AS cost_cents\n FROM ai_billing_period_allowance AS src\n CROSS JOIN LATERAL unnest(\n src.billed_users, src.included_cents_by_user, src.included_cost_cents_by_user\n ) WITH ORDINALITY AS seat(billed_user, included_cents, cost_cents, ordinality)\n WHERE src.user_id = $1\n AND src.period_start = $2\n ) AS excised\n WHERE allowance.user_id = $1\n AND allowance.period_start = $2\n AND $3 = ANY (allowance.billed_users)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "0090ad6b952f3c9c0cdd52c5edd45483da9f619a00204ff51ca739693936dc42"+}diff --git a/.sqlx/query-f11189d3026d8bfde974a03893017752ca96ee3a2074b59ec7b4d02e2c76ec66.json b/.sqlx/query-097d81df581fceedb035d0b862ba2b46e9c701aa52d0cd285164bdc4d9b65a83.jsonsimilarity index 63%rename from .sqlx/query-f11189d3026d8bfde974a03893017752ca96ee3a2074b59ec7b4d02e2c76ec66.jsonrename to .sqlx/query-097d81df581fceedb035d0b862ba2b46e9c701aa52d0cd285164bdc4d9b65a83.jsonindex d7a8119e32..dae2641b7d 100644--- a/.sqlx/query-f11189d3026d8bfde974a03893017752ca96ee3a2074b59ec7b4d02e2c76ec66.json+++ b/.sqlx/query-097d81df581fceedb035d0b862ba2b46e9c701aa52d0cd285164bdc4d9b65a83.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT billed_users AS \"billed_users!\",\n included_cents_by_user AS \"included_cents_by_user!\",\n updated_at\n FROM ai_billing_period_allowance\n WHERE user_id = $1 AND period_start = $2\n ",+ "query": "\n SELECT billed_users AS \"billed_users!\",\n included_cents_by_user AS \"included_cents_by_user!\",\n included_cost_cents_by_user,\n updated_at\n FROM ai_billing_period_allowance\n WHERE user_id = $1 AND period_start = $2\n ","describe": {"columns": [{@@ -15,6 +15,11 @@},{"ordinal": 2,+ "name": "included_cost_cents_by_user",+ "type_info": "Int8Array"+ },+ {+ "ordinal": 3,"name": "updated_at","type_info": "Timestamptz"}@@ -28,8 +33,9 @@"nullable": [false,false,+ true,false]},- "hash": "f11189d3026d8bfde974a03893017752ca96ee3a2074b59ec7b4d02e2c76ec66"+ "hash": "097d81df581fceedb035d0b862ba2b46e9c701aa52d0cd285164bdc4d9b65a83"}diff --git a/.sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.json b/.sqlx/query-120fc08df13374b604765e4a21b3c04484ff22733e84ca385f7cef7d78b91a09.jsonsimilarity index 57%rename from .sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.jsonrename to .sqlx/query-120fc08df13374b604765e4a21b3c04484ff22733e84ca385f7cef7d78b91a09.jsonindex e2a7eace02..3ef5768308 100644--- a/.sqlx/query-a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e.json+++ b/.sqlx/query-120fc08df13374b604765e4a21b3c04484ff22733e84ca385f7cef7d78b91a09.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT billed_users as \"billed_users!\",\n included_cents_by_user as \"included_cents_by_user!\"\n FROM ai_billing_period_allowance\n WHERE user_id = $1 AND period_start = $2\n ",+ "query": "\n SELECT billed_users as \"billed_users!\",\n included_cost_cents_by_user\n FROM ai_billing_period_allowance\n WHERE user_id = $1 AND period_start = $2\n ","describe": {"columns": [{@@ -10,7 +10,7 @@},{"ordinal": 1,- "name": "included_cents_by_user!",+ "name": "included_cost_cents_by_user","type_info": "Int8Array"}],@@ -22,8 +22,8 @@},"nullable": [false,- false+ true]},- "hash": "a8160cf5bd4bae1a84bc08ab598dc54483806c8ff49c41c30ddba7d11d78901e"+ "hash": "120fc08df13374b604765e4a21b3c04484ff22733e84ca385f7cef7d78b91a09"}diff --git a/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.json b/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.jsondeleted file mode 100644index d45007a2ec..0000000000--- a/.sqlx/query-3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8.json+++ /dev/null@@ -1,17 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user\n )\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (user_id, period_start) DO UPDATE\n SET billed_users = EXCLUDED.billed_users,\n included_cents_by_user = EXCLUDED.included_cents_by_user,\n updated_at = NOW()\n WHERE ai_billing_period_allowance.billed_users\n IS DISTINCT FROM EXCLUDED.billed_users\n OR ai_billing_period_allowance.included_cents_by_user\n IS DISTINCT FROM EXCLUDED.included_cents_by_user\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Timestamptz",- "TextArray",- "Int8Array"- ]- },- "nullable": []- },- "hash": "3077674eb0e7b318b5a42e67bf5a745504707103aee8c55454b90a3b5d18fdc8"-}diff --git a/.sqlx/query-736a15378e19dcaacae0b77359f63b9c5a157f04c7c828a1f109733b2d4c9eb9.json b/.sqlx/query-736a15378e19dcaacae0b77359f63b9c5a157f04c7c828a1f109733b2d4c9eb9.jsonnew file mode 100644index 0000000000..d8d678a5a4--- /dev/null+++ b/.sqlx/query-736a15378e19dcaacae0b77359f63b9c5a157f04c7c828a1f109733b2d4c9eb9.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user,\n included_cost_cents_by_user\n )\n VALUES ($1, $2, $3, $4, $5)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "TextArray",+ "Int8Array",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "736a15378e19dcaacae0b77359f63b9c5a157f04c7c828a1f109733b2d4c9eb9"+}diff --git a/.sqlx/query-740675ec64e23b476db7b1a0e7df4f13a18ed6ebaf40f20be915d9a4d867ed04.json b/.sqlx/query-740675ec64e23b476db7b1a0e7df4f13a18ed6ebaf40f20be915d9a4d867ed04.jsonnew file mode 100644index 0000000000..c2e8ea95fa--- /dev/null+++ b/.sqlx/query-740675ec64e23b476db7b1a0e7df4f13a18ed6ebaf40f20be915d9a4d867ed04.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user,\n included_cost_cents_by_user\n )\n VALUES ($1, $2, $3, $4, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "TextArray",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "740675ec64e23b476db7b1a0e7df4f13a18ed6ebaf40f20be915d9a4d867ed04"+}diff --git a/.sqlx/query-7a3f5bf0c81ca88a00746a60bc2b709c41fa2e7c60e9269f182d354282074035.json b/.sqlx/query-7a3f5bf0c81ca88a00746a60bc2b709c41fa2e7c60e9269f182d354282074035.jsonnew file mode 100644index 0000000000..bced5a2573--- /dev/null+++ b/.sqlx/query-7a3f5bf0c81ca88a00746a60bc2b709c41fa2e7c60e9269f182d354282074035.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user,\n included_cost_cents_by_user\n )\n VALUES ($1, $2, $3, $4, $4)\n ON CONFLICT (user_id, period_start) DO UPDATE\n SET billed_users = EXCLUDED.billed_users,\n included_cents_by_user = EXCLUDED.included_cents_by_user,\n included_cost_cents_by_user = EXCLUDED.included_cost_cents_by_user,\n updated_at = NOW()\n WHERE ai_billing_period_allowance.billed_users\n IS DISTINCT FROM EXCLUDED.billed_users\n OR ai_billing_period_allowance.included_cost_cents_by_user\n IS DISTINCT FROM EXCLUDED.included_cost_cents_by_user\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "TextArray",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "7a3f5bf0c81ca88a00746a60bc2b709c41fa2e7c60e9269f182d354282074035"+}diff --git a/.sqlx/query-8a5b5e8e1e4992958968606d363bd491c714225964e44dec89aef85ab1b581bb.json b/.sqlx/query-8a5b5e8e1e4992958968606d363bd491c714225964e44dec89aef85ab1b581bb.jsonnew file mode 100644index 0000000000..a5e5129305--- /dev/null+++ b/.sqlx/query-8a5b5e8e1e4992958968606d363bd491c714225964e44dec89aef85ab1b581bb.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO ai_billing_period_allowance (\n user_id, period_start, billed_users, included_cents_by_user, updated_at,\n included_cost_cents_by_user\n )\n VALUES ($1, $2, $3, $4, $5, $4)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Timestamptz",+ "TextArray",+ "Int8Array",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "8a5b5e8e1e4992958968606d363bd491c714225964e44dec89aef85ab1b581bb"+}diff --git a/.sqlx/query-9fc573bd641f7b73375801ae9a45b64d212f871c4af2192a74f57bab83b4ceb5.json b/.sqlx/query-9fc573bd641f7b73375801ae9a45b64d212f871c4af2192a74f57bab83b4ceb5.jsondeleted file mode 100644index 4327b956af..0000000000--- a/.sqlx/query-9fc573bd641f7b73375801ae9a45b64d212f871c4af2192a74f57bab83b4ceb5.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE ai_billing_period_allowance AS allowance\n SET billed_users = excised.users,\n included_cents_by_user = excised.cents,\n updated_at = NOW()\n FROM (\n SELECT\n COALESCE(\n array_agg(seat.billed_user ORDER BY seat.ordinality)\n FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),\n ARRAY[]::text[]\n )::text[] AS users,\n COALESCE(\n array_agg(seat.included_cents ORDER BY seat.ordinality)\n FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),\n ARRAY[]::bigint[]\n )::bigint[] AS cents\n FROM ai_billing_period_allowance AS src\n CROSS JOIN LATERAL unnest(src.billed_users, src.included_cents_by_user)\n WITH ORDINALITY AS seat(billed_user, included_cents, ordinality)\n WHERE src.user_id = $1\n AND src.period_start = $2\n ) AS excised\n WHERE allowance.user_id = $1\n AND allowance.period_start = $2\n AND $3 = ANY (allowance.billed_users)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Timestamptz",- "Text"- ]- },- "nullable": []- },- "hash": "9fc573bd641f7b73375801ae9a45b64d212f871c4af2192a74f57bab83b4ceb5"-}diff --git a/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsxindex 4952d88344..150b29b37e 100644--- a/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx+++ b/apps/web/src/features/gtm-invite/InviteOfferPanel.tsx@@ -5,6 +5,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableAiUsageBilling } from '@core/constant/featureFlags';import ArrowRight from '@phosphor/arrow-right.svg';import Check from '@phosphor/check.svg';+import { useIncludedAiCentsByTier } from '@queries/auth';import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';import { Button } from '@ui';import { Index, onMount } from 'solid-js';@@ -25,6 +26,7 @@ export function InviteOfferPanel(props: {}) {const analytics = useAnalytics();const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);+ const includedAi = useIncludedAiCentsByTier();onMount(() => {analytics.track('gtm_invite_offer_viewed', {@@ -58,7 +60,7 @@ export function InviteOfferPanel(props: {</span></div><ul class="flex flex-col gap-2">- <Index each={planFeatures(aiUsageBilling().enabled)}>+ <Index each={planFeatures(aiUsageBilling().enabled, includedAi())}>{(feature) => (<li class="flex items-center justify-between gap-2 text-xs"><span class="flex items-center gap-1.5 text-ink-muted">diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsxindex 6839569f5c..9e0da181f3 100644--- a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx@@ -56,7 +56,7 @@ export function AiUsageLimitDialog() {<div class="flex flex-col gap-1"><h2 class="text-xl font-semibold text-ink">{title()}</h2><p class="text-sm text-ink-extra-muted">- Your plan includes AI each month at Macro's usage rates. Add+ Your plan includes AI each month, measured at provider cost. Addcredits or turn on usage billing to keep going.</p></div>diff --git a/apps/web/src/features/paywall/plans.test.ts b/apps/web/src/features/paywall/plans.test.tsindex b568bfd493..1e81fad8bd 100644--- a/apps/web/src/features/paywall/plans.test.ts+++ b/apps/web/src/features/paywall/plans.test.ts@@ -12,7 +12,6 @@ describe('plan catalogs', () => {name: 'Max',price: 200,highlighted: false,- aiIncluded: 200,});});});diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.tsindex 0ca889b6cf..8bc2a10849 100644--- a/apps/web/src/features/paywall/plans.ts+++ b/apps/web/src/features/paywall/plans.ts@@ -4,12 +4,29 @@ export type Plan = {name: string;price: number;highlighted: boolean;- /**- * AI usage included each month, in dollars at Macro's list rate. Equal to the- * plan price: the plan's AI allowance is worth what the plan costs.- */- aiIncluded: number;};++/**+ * Included AI per seat per period in cents at provider cost, by tier. The+ * backend owns these numbers; read them from the plan catalog with+ * `useIncludedAiCentsByTier` (`@queries/auth`) rather than hard-coding them.+ * Empty until the catalog has loaded.+ */+export type IncludedAiCentsByTier = Partial<Record<PlanTier, number>>;++/** "$20" for whole dollars, "$12.50" otherwise; undefined while unknown. */+export function formatIncludedAi(+ cents: number | undefined+): string | undefined {+ if (cents === undefined) return undefined;+ const dollars = cents / 100;+ return Number.isInteger(dollars)+ ? `$${dollars.toLocaleString()}`+ : `$${dollars.toLocaleString(undefined, {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}`;+}/** Tiers that correspond to real Stripe products. Excludes 'free'. */export type PaidPlanTier = Exclude<PlanTier, 'free'>;@@ -18,7 +35,6 @@ const FREE_PLAN = {name: 'Free',price: 0,highlighted: false,- aiIncluded: 0,} as const satisfies Plan;const PREMIUM_PLAN = {@@ -26,7 +42,6 @@ const PREMIUM_PLAN = {name: 'Premium',price: 40,highlighted: true,- aiIncluded: 40,} as const satisfies Plan;const MAX_PLAN = {@@ -34,7 +49,6 @@ const MAX_PLAN = {name: 'Max',price: 200,highlighted: false,- aiIncluded: 200,} as const satisfies Plan;export const PLANS = [@@ -56,16 +70,24 @@ interface PlanFeature {aiUsageBilling?: boolean;}-const PLAN_FEATURE_ROWS: PlanFeature[] = [- {+/** The allowance row; amounts come from the plan catalog, "—" until it loads. */+function includedAiRow(includedAi: IncludedAiCentsByTier): PlanFeature {+ const perMonth = (tier: PlanTier) => {+ const amount = formatIncludedAi(includedAi[tier]);+ return amount ? `${amount} / mo at cost` : '—';+ };+ return {label: 'AI usage included',aiUsageBilling: true,values: {free: 'Limited',- premium: '$40 / mo',- max: '$200 / mo',+ premium: perMonth('premium'),+ max: perMonth('max'),},- },+ };+}++const PLAN_FEATURE_ROWS: PlanFeature[] = [{label: 'AI Agent',values: {@@ -96,10 +118,15 @@ const PLAN_FEATURE_ROWS: PlanFeature[] = [/*** The plan comparison rows. The AI usage rows (included allowance and what* covers usage beyond it) appear only while AI usage billing is on; callers- * read `enableAiUsageBilling` and pass its value.+ * read `enableAiUsageBilling` and pass its value, and pass the catalog's+ * allowances from `useIncludedAiCentsByTier` so the amounts are never+ * hard-coded here.*/-export function planFeatures(aiUsageBilling: boolean) {- return PLAN_FEATURE_ROWS.filter(+export function planFeatures(+ aiUsageBilling: boolean,+ includedAi: IncludedAiCentsByTier = {}+) {+ return [includedAiRow(includedAi), ...PLAN_FEATURE_ROWS].filter((feature) => !feature.aiUsageBilling || aiUsageBilling);}diff --git a/apps/web/src/features/settings/AiUsage.test.tsx b/apps/web/src/features/settings/AiUsage.test.tsxindex 787e0ffaad..d14f5dfde7 100644--- a/apps/web/src/features/settings/AiUsage.test.tsx+++ b/apps/web/src/features/settings/AiUsage.test.tsx@@ -17,7 +17,7 @@ const snapshot = (seats: number): AiUsageSnapshot => ({seats,period_start: '2026-09-01T00:00:00Z',period_end: '2026-10-01T00:00:00Z',- included_cents: 4_000,+ included_cents: 2_000,used_cents: 1_000,credits_consumed_cents: 0,credit_balance_cents: 2_500,@@ -36,7 +36,7 @@ describe('AiUsageMeter', () => {render(() => <AiUsageMeter snapshot={snapshot(5)} />);expect(screen.getAllByText('$10')).toHaveLength(2);- expect(screen.getByText(/of \$40 included/)).toBeTruthy();+ expect(screen.getByText(/of \$20 included/)).toBeTruthy();expect(screen.queryByText(/across 5 seats/)).toBeNull();expect(screen.getByText(/Team credits:/)).toBeTruthy();expect(screen.getByText(/Team usage billing this period/)).toBeTruthy();diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsxindex 6fc2203fd7..f4384f29a1 100644--- a/apps/web/src/features/settings/Billing.test.tsx+++ b/apps/web/src/features/settings/Billing.test.tsx@@ -64,7 +64,7 @@ vi.mock('@queries/auth', () => ({can_manage_billing: true,unlimited: state.unlimited,used_cents: 1_000_000,- included_cents: 4_000,+ included_cents: 2_000,credit_balance_cents: 0,blocked_reason: 'ai_allowance_exhausted',};@@ -75,6 +75,11 @@ vi.mock('@queries/auth', () => ({mutateAsync: state.changePlan,}),useCreateCheckoutSessionMutation: () => ({ mutateAsync: vi.fn() }),+ useIncludedAiCentsByTier: () => () => ({+ free: 0,+ premium: 2_000,+ max: 2_000,+ }),}));vi.mock('@service-stripe/client', () => ({stripeServiceClient: { createPortalSession: vi.fn() },diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsxindex 12ab07b3b3..bf9e56cd2f 100644--- a/apps/web/src/features/settings/Billing.tsx+++ b/apps/web/src/features/settings/Billing.tsx@@ -1,4 +1,8 @@-import { PLAN_BY_TIER, type PlanTier } from '@app/features/paywall/plans';+import {+ formatIncludedAi,+ PLAN_BY_TIER,+ type PlanTier,+} from '@app/features/paywall/plans';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { ShowFeatureFlag, useFeatureFlag } from '@app/lib/analytics/posthog';import { useHasPaidAccess } from '@core/auth';@@ -13,6 +17,7 @@ import {useAiBillingSummaryQuery,useChangePlanMutation,useCreateCheckoutSessionMutation,+ useIncludedAiCentsByTier,} from '@queries/auth';import { useCurrentTeamQuery } from '@queries/team/teams';import type { PaidPlan } from '@service-auth/ai-billing-types';@@ -23,16 +28,19 @@ import { createMemo, For, Match, Show, Switch } from 'solid-js';import { AiUsageControls, AiUsageMeter } from './AiUsage';import { SettingsCard, SettingsPage, SettingsSection } from './primitives';-/** Plan bullet points; the "$N of AI usage" line only with AI usage billing on. */+/**+ * Plan bullet points. The allowance line appears only with AI usage billing on+ * and once the plan catalog has supplied the amount.+ */const BILLING_PLAN_FEATURES: Record<PlanTier,- (aiUsageBilling: boolean) => string[]+ (includedAi: string | undefined) => string[]> = {free: () => ['Access to Haiku', 'MCP access', '5 GB storage'],- premium: (aiUsageBilling) => [+ premium: (includedAi) => ['All agents','All models',- ...(aiUsageBilling ? ['$40 of AI usage each month'] : []),+ ...(includedAi ? [`${includedAi} of AI usage at cost each month`] : []),'No watermark','AI projections','Multiple email inboxes',@@ -40,17 +48,22 @@ const BILLING_PLAN_FEATURES: Record<'Teams','1 TB storage',],- max: (aiUsageBilling) => [+ max: (includedAi) => ['Everything in Premium',- ...(aiUsageBilling ? ['$200 of AI usage each month'] : []),+ ...(includedAi ? [`${includedAi} of AI usage at cost each month`] : []),'Priority support',],};const PlanFeatures = (props: { tier: PlanTier }) => {const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);+ const includedAi = useIncludedAiCentsByTier();+ const allowance = () =>+ aiUsageBilling().enabled+ ? formatIncludedAi(includedAi()[props.tier])+ : undefined;return (- <For each={BILLING_PLAN_FEATURES[props.tier](aiUsageBilling().enabled)}>+ <For each={BILLING_PLAN_FEATURES[props.tier](allowance())}>{(label) => (<li class="flex items-center gap-2"><CheckIcon class="size-3 text-success" />@@ -77,20 +90,27 @@ function describeSeatPlans(members: TeamMember[]): string {return parts.join(', ');}-const PlanPrice = (props: { tier: PaidPlan }) => (- <p class="text-ink-extra-muted text-xs">- ${PLAN_BY_TIER[props.tier].price} per seat / month- <ShowFeatureFlag flag={enableAiUsageBilling}>- {' '}- · includes ${PLAN_BY_TIER[props.tier].aiIncluded} of AI usage- </ShowFeatureFlag>- </p>-);+const PlanPrice = (props: { tier: PaidPlan }) => {+ const includedAi = useIncludedAiCentsByTier();+ const allowance = () => formatIncludedAi(includedAi()[props.tier]);+ return (+ <p class="text-ink-extra-muted text-xs">+ ${PLAN_BY_TIER[props.tier].price} per seat / month+ <ShowFeatureFlag flag={enableAiUsageBilling}>+ <Show when={allowance()}>+ {(amount) => <> · includes {amount()} of AI usage at cost</>}+ </Show>+ </ShowFeatureFlag>+ </p>+ );+};export const Billing = () => {const permissions = usePermissions();const analytics = useAnalytics();const hasPaid = useHasPaidAccess();+ const includedAi = useIncludedAiCentsByTier();+ const premiumAllowance = () => formatIncludedAi(includedAi().premium);const userId = useUserId();const team = useCurrentTeamQuery();const summary = useAiBillingSummaryQuery();@@ -273,7 +293,7 @@ export const Billing = () => {{(snapshot) => (<SettingsSectiontitle="AI usage"- description="Your plan includes AI each month at Macro's usage rates. Beyond that, prepaid credits and usage billing keep you going."+ description="Your plan includes AI each month, measured at provider cost. Beyond that, prepaid credits and usage billing keep you going."><SettingsCard><section class="flex flex-col gap-5 p-4">@@ -401,8 +421,9 @@ export const Billing = () => {</button>{' '}($40 per seat / month<ShowFeatureFlag flag={enableAiUsageBilling}>- {' '}- with $40 of AI usage+ <Show when={premiumAllowance()}>+ {(amount) => <> with {amount()} of AI usage at cost</>}+ </Show></ShowFeatureFlag>).</p>diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 7f14365343..e065141aa9 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -1,5 +1,13 @@-import { PLAN_BY_TIER, PLANS } from '@app/features/paywall/plans';+import {+ formatIncludedAi,+ type IncludedAiCentsByTier,+ PLAN_BY_TIER,+ PLANS,+ type Plan,+ type PlanTier,+} from '@app/features/paywall/plans';import { SlackImport } from '@app/features/slack-import/slack-import';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { toast } from '@core/component/Toast/Toast';import {getLinkShareScope,@@ -8,6 +16,7 @@ import {NO_LINK_SHARE,} from '@core/component/TopBar/linkShare';import { UserIcon } from '@core/component/UserIcon';+import { enableAiUsageBilling } from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';import { useUserId } from '@core/context/user';import { getDisplayName, macroIdToEmail, tryMacroId } from '@core/user';@@ -33,6 +42,7 @@ import XIcon from '@phosphor/x.svg';import {useAiBillingSummaryQuery,useGithubLinkStatusQuery,+ useIncludedAiCentsByTier,} from '@queries/auth';import {useJoinTeamMutation,@@ -165,30 +175,30 @@ function RoleSelect(props: {type PlanOption = { value: PaidPlan; label: string; description: string };-const maxPlan = PLAN_BY_TIER.max;-const MAX_PLAN_OPTION: PlanOption = {- value: 'max',- label: maxPlan.name,- description: `$${maxPlan.price} · $${maxPlan.aiIncluded} of AI`,-};-const purchasablePlanOptions: PlanOption[] = [- ...PLANS.flatMap((plan) =>- plan.tier === 'free'- ? []- : [- {- value: plan.tier,- label: plan.name,- description: `$${plan.price} · $${plan.aiIncluded} of AI`,- },- ]- ),-];+/** "$40 · $20 of AI" once the catalog has the allowance, otherwise "$40". */+function planOption(plan: Plan, includedAi: string | undefined): PlanOption {+ return {+ value: plan.tier as PaidPlan,+ label: plan.name,+ description: includedAi+ ? `$${plan.price} · ${includedAi} of AI`+ : `$${plan.price}`,+ };+}-function planOptionsFor(currentPlan: PaidPlan): PlanOption[] {+function planOptionsFor(+ currentPlan: PaidPlan,+ includedAi: IncludedAiCentsByTier,+ aiUsageBilling: boolean+): PlanOption[] {+ const allowance = (tier: PlanTier) =>+ aiUsageBilling ? formatIncludedAi(includedAi[tier]) : undefined;+ const purchasable = PLANS.flatMap((plan) =>+ plan.tier === 'free' ? [] : [planOption(plan, allowance(plan.tier))]+ );return currentPlan === 'max'- ? [...purchasablePlanOptions, MAX_PLAN_OPTION]- : purchasablePlanOptions;+ ? [...purchasable, planOption(PLAN_BY_TIER.max, allowance('max'))]+ : purchasable;}/**@@ -205,7 +215,10 @@ function PlanSelect(props: {onChange: (plan: PaidPlan) => void;disabled?: boolean;}) {- const options = () => planOptionsFor(props.value);+ const includedAi = useIncludedAiCentsByTier();+ const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);+ const options = () =>+ planOptionsFor(props.value, includedAi(), aiUsageBilling().enabled);const selectedOption = () =>options().find((option) => option.value === props.value) ?? options()[0];diff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsxindex 9dc3808b5f..f9a8e0bc47 100644--- a/apps/web/src/features/setup/flow/PlanStep.tsx+++ b/apps/web/src/features/setup/flow/PlanStep.tsx@@ -11,6 +11,7 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableAiUsageBilling } from '@core/constant/featureFlags';import ArrowRight from '@phosphor/arrow-right.svg';import Check from '@phosphor/check.svg';+import { useIncludedAiCentsByTier } from '@queries/auth';import { useUserInfoQuery } from '@queries/auth/user-info';import type { GtmInviteOffer } from '@service-auth/generated/schemas/gtmInviteOffer';import { useSearchParams } from '@solidjs/router';@@ -149,6 +150,7 @@ function PlanPicker(props: {}) {const selected = () => props.selected;const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);+ const includedAi = useIncludedAiCentsByTier();return (<div class="flex flex-col gap-6"><div class="grid grid-cols-1 sm:grid-cols-2 gap-3">@@ -190,7 +192,9 @@ function PlanPicker(props: {</span></div><ul class="flex flex-col gap-2">- <Index each={planFeatures(aiUsageBilling().enabled)}>+ <Index+ each={planFeatures(aiUsageBilling().enabled, includedAi())}+ >{(feature) => (<li class="flex items-center justify-between gap-2 text-xs"><span class="text-ink-muted">{feature().label}</span>diff --git a/apps/web/src/lib/queries/auth/ai-billing.ts b/apps/web/src/lib/queries/auth/ai-billing.tsindex 355c01a55d..3cbee62862 100644--- a/apps/web/src/lib/queries/auth/ai-billing.ts+++ b/apps/web/src/lib/queries/auth/ai-billing.ts@@ -1,5 +1,5 @@import { throwOnErr } from '@core/util/result';-import type { PaidPlan } from '@service-auth/ai-billing-types';+import type { AiPlanTier, PaidPlan } from '@service-auth/ai-billing-types';import { authServiceClient } from '@service-auth/client';import { useMutation, useQuery } from '@tanstack/solid-query';import { queryClient } from '../client';@@ -52,6 +52,24 @@ export function useAiBillingPlansQuery() {}));}+/**+ * Included AI per seat per period from the plan catalog, in cents at provider+ * cost, keyed by tier. The backend owns the amount; this is the only place the+ * frontend should get it from. Empty until the catalog has loaded.+ */+export function useIncludedAiCentsByTier(): () => Partial<+ Record<AiPlanTier, number>+> {+ const plans = useAiBillingPlansQuery();+ return () =>+ Object.fromEntries(+ (plans.data?.plans ?? []).map((plan) => [+ plan.tier,+ plan.included_ai_cents_per_seat,+ ])+ );+}+export function invalidateAiBillingSummary() {return queryClient.invalidateQueries({queryKey: authKeys.aiBillingSummary.queryKey,diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.tsindex b676db7391..5207c3825a 100644--- a/apps/web/src/lib/queries/auth/index.ts+++ b/apps/web/src/lib/queries/auth/index.ts@@ -10,6 +10,7 @@ export {useAiBillingSummaryQuery,useChangePlanMutation,useCreateAiCreditCheckoutMutation,+ useIncludedAiCentsByTier,useUpdateAiOverageMutation,} from './ai-billing';export {diff --git a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.tsindex b7080c776f..dc10521798 100644--- a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts+++ b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts@@ -3,7 +3,9 @@* (`crates/ai_billing`). Replace with the orval-generated schemas on the next* client regeneration (`bun run gen-api auth-service`).*- * Every money field is in cents at Macro's list rate.+ * Allowance and usage fields (`included_cents`, `used_cents`,+ * `remaining_cents`) are cents at provider cost. Credits, overage charges,+ * caps, packs and `uncovered_cents` are customer cents.*/export type AiPlanTier = 'free' | 'premium' | 'max';@@ -44,6 +46,7 @@ export interface AiPlanCatalogEntry {tier: AiPlanTier;monthly_price_cents: number;included_ai_cents_per_seat: number;+ purchasable: boolean;}export interface AiPlanCatalog {diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.tsindex 0b5d98553e..7bd36e9734 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts@@ -10,10 +10,12 @@ import type { PlanTier } from './planTier';* One plan in the catalog.*/export interface PlanCatalogEntry {- /** Included AI per seat per period, list-rate cents. */+ /** Included AI per seat per period, in cents at provider cost. */included_ai_cents_per_seat: number;- /** Monthly list price per seat, cents. */+ /** Monthly subscription price per seat, cents. */monthly_price_cents: number;+ /** Whether a new purchase or plan move may pick this plan today. */+ purchasable: boolean;/** The tier. */tier: PlanTier;}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.tsindex 57cee420b9..37c3c0fffd 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogResponse.ts@@ -16,6 +16,7 @@ export interface PlanCatalogResponse {overage_limit_max_cents: number;/** Smallest allowed overage cap, cents. */overage_limit_min_cents: number;- /** Free and every purchasable paid plan, cheapest first. */+ /** Every plan, cheapest first. Clients read allowances from here rather+than hard-coding them; `purchasable` marks the plans a user can buy. */plans: PlanCatalogEntry[];}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.tsindex a225f33e92..45f267d940 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/usageSnapshot.ts@@ -16,17 +16,17 @@ export interface UsageSnapshot {blocked_reason?: UsageSnapshotBlockedReason;/** Whether the requesting user is the payer. */can_manage_billing: boolean;- /** Shared prepaid credit balance. */+ /** Shared prepaid credit balance, in customer cents. */credit_balance_cents: number;- /** Shared payer credits already applied to this period. */+ /** Shared payer credits already applied to this period, in customer cents. */credits_consumed_cents: number;- /** Included AI for this user's seat this period, in list-rate cents. */+ /** Included AI for this user's seat this period, in cents at provider cost. */included_cents: number;- /** Shared overage charged so far this period. */+ /** Shared overage charged so far this period, in customer cents. */overage_charged_cents: number;/** Whether overage billing is on. */overage_enabled: boolean;- /** Per-period overage cap. */+ /** Per-period overage cap, in customer cents. */overage_limit_cents: number;/** Whether overage is paused after a failed charge. */overage_suspended: boolean;@@ -36,8 +36,9 @@ export interface UsageSnapshot {period_end: string;/** Period start. */period_start: string;- /** This seat's remaining allowance plus shared credit/overage headroom; 0-when blocked. */+ /** Cost cents of usage this seat may still consume: its remaining allowance+plus whatever shared credit and overage headroom pays for at the markup.+0 when blocked. */remaining_cents: number;/*** Seats billed to the payer.@@ -46,11 +47,12 @@ when blocked. */seats: number;/** The plan. */tier: PlanTier;- /** Team-wide usage beyond per-seat allowances that is not yet covered by-shared credits or charges (awaiting settlement). */+ /** Team-wide usage beyond per-seat allowances, at the overage markup, that+is not yet covered by shared credits or charges (awaiting settlement).+Customer cents. */uncovered_cents: number;/** Enterprise: never metered. */unlimited: boolean;- /** AI used by this user this period, in list-rate cents. */+ /** AI used by this user this period, in cents at provider cost. */used_cents: number;}diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 236ff61c0c..96272ca8e4 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -6145,18 +6145,23 @@"required": ["tier","monthly_price_cents",- "included_ai_cents_per_seat"+ "included_ai_cents_per_seat",+ "purchasable"],"properties": {"included_ai_cents_per_seat": {"type": "integer","format": "int64",- "description": "Included AI per seat per period, list-rate cents."+ "description": "Included AI per seat per period, in cents at provider cost."},"monthly_price_cents": {"type": "integer","format": "int64",- "description": "Monthly list price per seat, cents."+ "description": "Monthly subscription price per seat, cents."+ },+ "purchasable": {+ "type": "boolean",+ "description": "Whether a new purchase or plan move may pick this plan today."},"tier": {"$ref": "#/components/schemas/PlanTier",@@ -6197,7 +6202,7 @@"items": {"$ref": "#/components/schemas/PlanCatalogEntry"},- "description": "Free and every purchasable paid plan, cheapest first."+ "description": "Every plan, cheapest first. Clients read allowances from here rather\nthan hard-coding them; `purchasable` marks the plans a user can buy."}}},@@ -6618,22 +6623,22 @@"credit_balance_cents": {"type": "integer","format": "int64",- "description": "Shared prepaid credit balance."+ "description": "Shared prepaid credit balance, in customer cents."},"credits_consumed_cents": {"type": "integer","format": "int64",- "description": "Shared payer credits already applied to this period."+ "description": "Shared payer credits already applied to this period, in customer cents."},"included_cents": {"type": "integer","format": "int64",- "description": "Included AI for this user's seat this period, in list-rate cents."+ "description": "Included AI for this user's seat this period, in cents at provider cost."},"overage_charged_cents": {"type": "integer","format": "int64",- "description": "Shared overage charged so far this period."+ "description": "Shared overage charged so far this period, in customer cents."},"overage_enabled": {"type": "boolean",@@ -6642,7 +6647,7 @@"overage_limit_cents": {"type": "integer","format": "int64",- "description": "Per-period overage cap."+ "description": "Per-period overage cap, in customer cents."},"overage_suspended": {"type": "boolean",@@ -6665,7 +6670,7 @@"remaining_cents": {"type": "integer","format": "int64",- "description": "This seat's remaining allowance plus shared credit/overage headroom; 0\nwhen blocked."+ "description": "Cost cents of usage this seat may still consume: its remaining allowance\nplus whatever shared credit and overage headroom pays for at the markup.\n0 when blocked."},"seats": {"type": "integer",@@ -6680,7 +6685,7 @@"uncovered_cents": {"type": "integer","format": "int64",- "description": "Team-wide usage beyond per-seat allowances that is not yet covered by\nshared credits or charges (awaiting settlement)."+ "description": "Team-wide usage beyond per-seat allowances, at the overage markup, that\nis not yet covered by shared credits or charges (awaiting settlement).\nCustomer cents."},"unlimited": {"type": "boolean",@@ -6689,7 +6694,7 @@"used_cents": {"type": "integer","format": "int64",- "description": "AI used by this user this period, in list-rate cents."+ "description": "AI used by this user this period, in cents at provider cost."}}},diff --git a/crates/ai_billing/src/composition/test.rs b/crates/ai_billing/src/composition/test.rsindex 61e8172cc1..2d176c7d24 100644--- a/crates/ai_billing/src/composition/test.rs+++ b/crates/ai_billing/src/composition/test.rs@@ -6,7 +6,7 @@ use macro_user_id::user_id::MacroUserIdStr;async fn configured_recorders_preserve_analytics_and_count_only_enabled_billable_usage(pool: PgPool,) {- use crate::domain::{BillingPeriod, UsageReader, list_rate_cents};+ use crate::domain::{BillingPeriod, UsageReader, cost_cents};use ai_usage::{UsageApiParams, UsageContext, UsageRepo};use std::time::Duration;@@ -53,7 +53,7 @@ async fn configured_recorders_preserve_analytics_and_count_only_enabled_billable.expect("all analytics writes must finish, including uncounted usage");let usage = PgUsageReader::new(pool)- .list_rate_usage_cents_by_user(+ .usage_cost_cents_by_user(&[user.clone(), ai_usage::SYSTEM_USER_ID.clone()],BillingPeriod::current(None, chrono::Utc::now()),)@@ -61,7 +61,7 @@ async fn configured_recorders_preserve_analytics_and_count_only_enabled_billable.unwrap();assert_eq!(usage.len(), 1);assert_eq!(usage[0].user, user);- assert_eq!(usage[0].used_cents, list_rate_cents(5.0));+ assert_eq!(usage[0].used_cents, cost_cents(5.0));}#[tokio::test]diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rsindex 8bcfff7c57..8b3f6f18a0 100644--- a/crates/ai_billing/src/domain.rs+++ b/crates/ai_billing/src/domain.rs@@ -1,5 +1,5 @@-//! Domain layer: plans and margin math, the settlement ledger, ports, and the-//! billing service.+//! Domain layer: plans and pricing constants, the settlement ledger, ports, and+//! the billing service.pub mod admission;pub mod financial;@@ -8,6 +8,7 @@ pub mod models;pub mod period;pub mod policy;pub mod ports;+pub mod pricing;pub mod service;pub use admission::{@@ -20,11 +21,15 @@ pub use models::{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,- UsagePolicy, UsageSnapshot, list_rate_cents,+ Result, SeatAllowance, SeatGeneration, SeatUsage, SubscriptionScope, UsagePolicy,+ UsageSnapshot,};pub use ports::{BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,PaymentGateway, PendingCharge, SettlementOutcome, SettlementTrigger, UsageReader,};+pub use pricing::{+ INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT, cost_cents, cost_cents_covered_by,+ extra_customer_cents,+};pub use service::BillingServiceImpl;diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rsindex a453059587..b12187ea69 100644--- a/crates/ai_billing/src/domain/ledger.rs+++ b/crates/ai_billing/src/domain/ledger.rs@@ -2,20 +2,25 @@//! its row lock and the service can run it for snapshots.//!//! For a payer and period, each seat first consumes only its own included-//! allowance. The remaining usage is chargeable to the payer's shared credits-//! and overage:+//! allowance, both measured in cost cents. The remaining usage is chargeable to+//! the payer's shared credits and overage at the markup, in customer cents://!//! ```text-//! chargeable = sum(max(0, seat_used - seat_included))-//! covered = credits_consumed + overage_charged-//! uncovered = max(0, chargeable - covered)-//! headroom = (covered - chargeable) + credit_balance + overage_room+//! chargeable_cost = sum(max(0, seat_used_cost - seat_included_cost))+//! chargeable = extra_customer_cents(chargeable_cost)+//! covered = credits_consumed + overage_charged+//! uncovered = max(0, chargeable - covered)+//! headroom = (covered - chargeable) + credit_balance + overage_room+//! remaining = seat_remaining_cost + cost_cents_covered_by(headroom)//! ```//!-//! Settlement moves `uncovered` into `credits_consumed` (from the balance) and-//! then into `overage_charged` (when overage is on, within the cap, and the-//! chunk is worth charging). Between settlements `uncovered` is simply usage-//! that has not been booked yet; the gate accounts for it through `headroom`.+//! The markup is applied to the period's cumulative chargeable cost, never to+//! an increment, so settling in several chunks books exactly the same money as+//! settling once. Settlement moves `uncovered` into `credits_consumed` (from+//! the balance) and then into `overage_charged` (when overage is on, within the+//! cap, and the chunk is worth charging). Between settlements `uncovered` is+//! simply usage that has not been booked yet; the gate accounts for it through+//! `headroom`.#[cfg(test)]mod test;@@ -24,6 +29,7 @@ use super::models::{AllowanceDecision, BillingPeriod, BillingSettings, DenyReason, Entitlement,MIN_STRIPE_CHARGE_CENTS, PeriodLedger, PlanTier, UsageSnapshot,};+use super::pricing::cost_cents_covered_by;use macro_user_id::user_id::MacroUserIdStr;/// The overage policy in force for one settlement.@@ -42,20 +48,23 @@ pub struct SettlementPolicy {/// The ledger position a settlement plans against.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SettlementState {- /// Sum of each seat's usage beyond its own allowance this period.- pub chargeable_cents: i64,- /// Credits already applied this period.+ /// The period's cumulative usage beyond each seat's own allowance, already+ /// converted to customer cents at the overage markup.+ pub chargeable_customer_cents: i64,+ /// Credits already applied this period, customer cents.pub credits_consumed_cents: i64,- /// Overage already charged this period (pending or paid).+ /// Overage already charged this period (pending or paid), customer cents.pub overage_charged_cents: i64,- /// Current credit balance.+ /// Current credit balance, customer cents.pub credit_balance_cents: i64,}impl SettlementState {- /// Chargeable usage not yet covered by credits or charges.+ /// Chargeable money not yet covered by credits or charges.pub fn uncovered_cents(&self) -> i64 {- (self.chargeable_cents - (self.credits_consumed_cents + self.overage_charged_cents)).max(0)+ (self.chargeable_customer_cents+ - (self.credits_consumed_cents + self.overage_charged_cents))+ .max(0)}}@@ -95,7 +104,9 @@ pub fn plan_settlement(state: SettlementState, policy: SettlementPolicy) -> Sett}}-/// Assemble the API-facing snapshot from the resolved inputs.+/// Assemble the API-facing snapshot from the resolved inputs. `used_cost_cents`+/// is this seat's usage at cost; `shared_chargeable_customer_cents` is the+/// payer's cumulative usage beyond all seat allowances, already marked up.#[expect(clippy::too_many_arguments,reason = "snapshot assembly keeps its resolved billing inputs explicit"@@ -105,14 +116,14 @@ pub fn build_snapshot(entitlement: &Entitlement,settings: &BillingSettings,period: BillingPeriod,- used_cents: i64,- shared_chargeable_cents: i64,+ used_cost_cents: i64,+ shared_chargeable_customer_cents: i64,ledger: PeriodLedger,credit_balance_cents: i64,) -> UsageSnapshot {let included_cents = entitlement.included_ai_cents();let shared_covered = ledger.credits_consumed_cents + ledger.overage_charged_cents;- let uncovered_cents = (shared_chargeable_cents - shared_covered).max(0);+ let uncovered_cents = (shared_chargeable_customer_cents - shared_covered).max(0);let overage_room = if settings.overage_active() {(settings.overage_limit_cents - ledger.overage_charged_cents).max(0)} else {@@ -121,12 +132,12 @@ pub fn build_snapshot(let remaining_cents = if entitlement.unlimited {i64::MAX} else {- let seat_remaining = (included_cents - used_cents).max(0);- let shared_headroom = ((shared_covered - shared_chargeable_cents)+ let seat_remaining = (included_cents - used_cost_cents).max(0);+ let shared_headroom = ((shared_covered - shared_chargeable_customer_cents)+ credit_balance_cents.max(0)+ overage_room).max(0);- seat_remaining.saturating_add(shared_headroom)+ seat_remaining.saturating_add(cost_cents_covered_by(shared_headroom))};let mut snapshot = UsageSnapshot {@@ -138,7 +149,7 @@ pub fn build_snapshot(period_start: period.start,period_end: period.end,included_cents,- used_cents,+ used_cents: used_cost_cents,credits_consumed_cents: ledger.credits_consumed_cents,credit_balance_cents,overage_enabled: settings.overage_enabled,diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rsindex cddb089c7b..a3d35a8425 100644--- a/crates/ai_billing/src/domain/ledger/test.rs+++ b/crates/ai_billing/src/domain/ledger/test.rs@@ -1,5 +1,6 @@use super::*;-use crate::domain::models::{OVERAGE_CHARGE_THRESHOLD_CENTS, PayerScope, list_rate_cents};+use crate::domain::models::{OVERAGE_CHARGE_THRESHOLD_CENTS, PayerScope};+use crate::domain::pricing::extra_customer_cents;use chrono::{TimeZone, Utc};fn user(email: &str) -> MacroUserIdStr<'static> {@@ -15,9 +16,10 @@ fn policy(active: bool, limit: i64, ended: bool) -> SettlementPolicy {}}+/// `used` and `included` are cost cents; the rest is customer money.fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) -> SettlementState {SettlementState {- chargeable_cents: (used - included).max(0),+ chargeable_customer_cents: extra_customer_cents((used - included).max(0)),credits_consumed_cents: consumed,overage_charged_cents: charged,credit_balance_cents: balance,@@ -25,21 +27,9 @@ fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) ->}#[test]-fn list_rate_marks_provider_cost_up_to_the_target_margin() {- // $16 of provider cost is exactly the Premium allowance at 60% margin.- assert_eq!(list_rate_cents(16.0), 4_000);- assert_eq!(list_rate_cents(80.0), 20_000);- // Fractions of a cent round up.- assert_eq!(list_rate_cents(0.001), 1);- assert_eq!(list_rate_cents(0.0), 0);- assert_eq!(list_rate_cents(-3.0), 0);- assert_eq!(list_rate_cents(f64::NAN), 0);-}--#[test]-fn included_allowance_equals_plan_price_per_seat() {- assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), 4_000);- assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 20_000);+fn included_allowance_is_the_same_at_cost_for_every_paid_seat() {+ assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), 2_000);+ assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 2_000);assert_eq!(PlanTier::Free.included_ai_cents_per_seat(), 0);let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);@@ -51,18 +41,18 @@ fn included_allowance_equals_plan_price_per_seat() {team_id: macro_uuid::generate_uuid_v7(),};assert_eq!(team.seats(), 3);- assert_eq!(team.included_ai_cents(), 4_000);+ assert_eq!(team.included_ai_cents(), 2_000);assert_eq!(team.seat_allowances().into_iter().map(|seat| seat.included_cents).collect::<Vec<_>>(),- vec![4_000, 4_000, 4_000]+ vec![2_000, 2_000, 2_000]);}#[test]-fn mixed_seat_plans_keep_each_seats_allowance_separate() {+fn mixed_seat_plans_keep_one_allowance_per_seat() {let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);team.billed_users.push(user("[email protected]"));team.seat_tiers.push(PlanTier::Max);@@ -72,35 +62,45 @@ fn mixed_seat_plans_keep_each_seats_allowance_separate() {team_id: macro_uuid::generate_uuid_v7(),};assert_eq!(team.seats(), 3);- assert_eq!(team.included_ai_cents(), 4_000);+ assert_eq!(team.included_ai_cents(), 2_000);+ let allowances = team.seat_allowances();assert_eq!(- team.seat_allowances()+ allowances+ .iter()+ .map(|seat| seat.user.as_ref())+ .collect::<Vec<_>>(),+ );+ // Max has no allowance of its own yet: every paid seat gets the same at-cost amount.+ assert_eq!(+ allowances.into_iter().map(|seat| seat.included_cents).collect::<Vec<_>>(),- vec![4_000, 20_000, 4_000]+ vec![2_000, 2_000, 2_000]);assert_eq!(team.tier, PlanTier::Premium);}#[test]fn nothing_to_settle_under_allowance() {- let plan = plan_settlement(state(3_000, 4_000, 0, 0, 5_000), policy(true, 5_000, false));+ let plan = plan_settlement(state(1_500, 2_000, 0, 0, 5_000), policy(true, 5_000, false));assert_eq!(plan, SettlementPlan::default());}#[test]-fn credits_cover_overflow_before_overage() {- let plan = plan_settlement(state(4_700, 4_000, 0, 0, 5_000), policy(true, 5_000, false));- assert_eq!(plan.consume_credits_cents, 700);+fn credits_cover_overflow_before_overage_at_the_markup() {+ // 700 cost cents over the allowance cost the customer 735.+ let plan = plan_settlement(state(2_700, 2_000, 0, 0, 5_000), policy(true, 5_000, false));+ assert_eq!(plan.consume_credits_cents, 735);assert_eq!(plan.charge_overage_cents, 0);}#[test]fn already_consumed_credits_are_not_double_counted() {- // 700 over, 700 already consumed: settled.+ // 735 owed, 735 already consumed: settled.let plan = plan_settlement(- state(4_700, 4_000, 700, 0, 4_300),+ state(2_700, 2_000, 735, 0, 4_265),policy(true, 5_000, false),);assert_eq!(plan, SettlementPlan::default());@@ -108,44 +108,61 @@ fn already_consumed_credits_are_not_double_counted() {#[test]fn overage_waits_for_the_charge_threshold() {- // 900 uncovered, no credits: below the $10 chunk, nothing charged yet.- let plan = plan_settlement(state(4_900, 4_000, 0, 0, 0), policy(true, 5_000, false));+ // 900 cost over is 945 owed, no credits: below the $10 chunk, nothing charged yet.+ let plan = plan_settlement(state(2_900, 2_000, 0, 0, 0), policy(true, 5_000, false));assert_eq!(plan.charge_overage_cents, 0);- // 1_000 uncovered: charged.- let plan = plan_settlement(state(5_000, 4_000, 0, 0, 0), policy(true, 5_000, false));- assert_eq!(plan.charge_overage_cents, 1_000);+ // 960 cost over is 1_008 owed: charged.+ let plan = plan_settlement(state(2_960, 2_000, 0, 0, 0), policy(true, 5_000, false));+ assert_eq!(plan.charge_overage_cents, 1_008);}#[test]fn period_end_flushes_small_remainders_above_the_stripe_minimum() {- let plan = plan_settlement(state(4_300, 4_000, 0, 0, 0), policy(true, 5_000, true));- assert_eq!(plan.charge_overage_cents, 300);+ let plan = plan_settlement(state(2_300, 2_000, 0, 0, 0), policy(true, 5_000, true));+ assert_eq!(plan.charge_overage_cents, 315);// Below Stripe's $0.50 floor the remainder is forgiven.- let plan = plan_settlement(state(4_030, 4_000, 0, 0, 0), policy(true, 5_000, true));+ let plan = plan_settlement(state(2_030, 2_000, 0, 0, 0), policy(true, 5_000, true));assert_eq!(plan.charge_overage_cents, 0);}#[test]fn overage_respects_the_cap_and_prior_charges() {- // 6_000 uncovered, cap 5_000 with 4_500 already charged: only 500 room,- // and 500 is below the threshold mid-period.+ // 10_500 cost over is 11_025 owed; cap 5_000 with 4_500 already charged:+ // only 500 room, and 500 is below the threshold mid-period.let plan = plan_settlement(- state(14_500, 4_000, 0, 4_500, 0),+ state(12_500, 2_000, 0, 4_500, 0),policy(true, 5_000, false),);assert_eq!(plan.charge_overage_cents, 0);// At period end the 500 is flushed.- let plan = plan_settlement(state(14_500, 4_000, 0, 4_500, 0), policy(true, 5_000, true));+ let plan = plan_settlement(state(12_500, 2_000, 0, 4_500, 0), policy(true, 5_000, true));assert_eq!(plan.charge_overage_cents, 500);}#[test]fn overage_off_only_consumes_credits() {- let plan = plan_settlement(state(9_000, 4_000, 0, 0, 2_000), policy(false, 0, false));+ let plan = plan_settlement(state(7_000, 2_000, 0, 0, 2_000), policy(false, 0, false));assert_eq!(plan.consume_credits_cents, 2_000);assert_eq!(plan.charge_overage_cents, 0);}+#[test]+fn settling_in_chunks_books_the_same_money_as_settling_once() {+ // First settlement at 1_000 cost over: 1_050 consumed.+ let first = plan_settlement(state(3_000, 2_000, 0, 0, 10_000), policy(false, 0, false));+ assert_eq!(first.consume_credits_cents, 1_050);+ // Later at 1_500 cost over: only the 525 difference, not extra(500) = 525 plus rounding.+ let second = plan_settlement(+ state(3_500, 2_000, 1_050, 0, 8_950),+ policy(false, 0, false),+ );+ assert_eq!(second.consume_credits_cents, 525);+ assert_eq!(+ first.consume_credits_cents + second.consume_credits_cents,+ extra_customer_cents(1_500)+ );+}+fn snapshot_for(tier: PlanTier,settings: BillingSettings,@@ -156,7 +173,7 @@ fn snapshot_for(let u = user("[email protected]");let ent = Entitlement::personal(u.clone(), tier);let period = BillingPeriod::calendar_month(Utc::now());- let chargeable = (used - ent.included_ai_cents()).max(0);+ let chargeable = extra_customer_cents((used - ent.included_ai_cents()).max(0));build_snapshot(&u, &ent, &settings, period, used, chargeable, ledger, balance,)@@ -167,7 +184,7 @@ fn gate_allows_within_allowance_and_blocks_after() {let s = snapshot_for(PlanTier::Premium,BillingSettings::default(),- 3_999,+ 1_999,PeriodLedger::default(),0,);@@ -177,7 +194,7 @@ fn gate_allows_within_allowance_and_blocks_after() {let s = snapshot_for(PlanTier::Premium,BillingSettings::default(),- 4_000,+ 2_000,PeriodLedger::default(),0,);@@ -191,34 +208,34 @@ fn gate_allows_within_allowance_and_blocks_after() {#[test]fn gate_counts_unsettled_usage_against_credits() {- // 500 over allowance, not yet settled, 300 of credit: 300 - 500 < 0.+ // 500 cost over allowance is 525 owed, not yet settled, 300 of credit: 300 - 525 < 0.let s = snapshot_for(PlanTier::Premium,BillingSettings::default(),- 4_500,+ 2_500,PeriodLedger::default(),300,);- assert_eq!(s.uncovered_cents, 500);+ assert_eq!(s.uncovered_cents, 525);assert_eq!(s.remaining_cents, 0);assert_eq!(decide(&s),AllowanceDecision::Deny(DenyReason::AllowanceExhausted));- // Once settled (500 consumed), the balance is what remains.+ // Once settled (525 consumed), the 800 balance pays for 761 cost cents more.let s = snapshot_for(PlanTier::Premium,BillingSettings::default(),- 4_500,+ 2_500,PeriodLedger {- credits_consumed_cents: 500,+ credits_consumed_cents: 525,overage_charged_cents: 0,},800,);assert_eq!(s.uncovered_cents, 0);- assert_eq!(s.remaining_cents, 800);+ assert_eq!(s.remaining_cents, 761);assert_eq!(decide(&s), AllowanceDecision::Allow);}@@ -232,18 +249,19 @@ fn gate_uses_overage_room_and_reports_the_cap() {let s = snapshot_for(PlanTier::Premium,settings.clone(),- 5_500,+ 3_500,PeriodLedger::default(),0,);- // 1_500 uncovered against 2_000 of room.- assert_eq!(s.remaining_cents, 500);+ // 1_500 cost over is 1_575 owed against 2_000 of room: 425 left pays for 404 cost cents.+ assert_eq!(s.uncovered_cents, 1_575);+ assert_eq!(s.remaining_cents, 404);assert_eq!(decide(&s), AllowanceDecision::Allow);let s = snapshot_for(PlanTier::Premium,settings,- 6_000,+ 4_000,PeriodLedger {credits_consumed_cents: 0,overage_charged_cents: 2_000,@@ -257,6 +275,21 @@ fn gate_uses_overage_room_and_reports_the_cap() {);}+#[test]+fn a_single_cent_of_headroom_does_not_pay_for_marked_up_usage() {+ // 1 customer cent covers 0 cost cents at the markup; 2 cover 1.+ for (balance, remaining) in [(1, 0), (2, 1)] {+ let s = snapshot_for(+ PlanTier::Premium,+ BillingSettings::default(),+ 2_000,+ PeriodLedger::default(),+ balance,+ );+ assert_eq!(s.remaining_cents, remaining);+ }+}+#[test]fn gate_reports_failed_payment_when_suspended() {let settings = BillingSettings {@@ -268,7 +301,7 @@ fn gate_reports_failed_payment_when_suspended() {let s = snapshot_for(PlanTier::Premium,settings,- 4_500,+ 2_500,PeriodLedger::default(),0,);@@ -298,7 +331,7 @@ fn free_and_unlimited_are_never_blocked() {&BillingSettings::default(),BillingPeriod::calendar_month(Utc::now()),99_999,- 95_999,+ extra_customer_cents(97_999),PeriodLedger::default(),0,);@@ -332,7 +365,7 @@ fn team_member_is_not_the_payer() {);assert!(!s.can_manage_billing);assert_eq!(s.seats, 2);- assert_eq!(s.included_cents, 20_000);+ assert_eq!(s.included_cents, 2_000);}#[test]diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rsindex 88b26c5441..f4c35a1a52 100644--- a/crates/ai_billing/src/domain/models.rs+++ b/crates/ai_billing/src/domain/models.rs@@ -1,5 +1,6 @@-//! Plans, the margin math, billing periods, and the API-facing snapshot.+//! Plans, billing periods, settings, and the API-facing snapshot.+use super::pricing::INCLUDED_ALLOWANCE_CENTS;pub use ai_usage::NON_BILLABLE_AI_FEATURES;use chrono::{DateTime, Datelike, Months, TimeZone, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -36,29 +37,15 @@ impl AiUsageBilling {#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum UsagePolicy {- /// Original 2.5x list-rate arithmetic and plan allowances.+ /// Aggregate per-period settlement in [`super::ledger`]: the at-cost+ /// allowance, then credits and overage at the markup.Legacy,- /// Existing $40 offer: $20 public usage per seat, then public usage times 1.05.+ /// Per-attempt exact-money policy in [`super::policy`]: the same allowance+ /// at public price, then public usage at the same markup.PublicAllowanceV1,}-/// Legacy target gross margin on AI, in basis points. The list rate is provider cost-/// divided by `(1 - margin)`; at 60% that is a 2.5x markup.-pub const TARGET_GROSS_MARGIN_BPS: i64 = 6_000;--const BPS_PER_UNIT: i64 = 10_000;--/// Legacy only: convert a provider cost in USD to Macro's list rate in whole cents,-/// rounding up so fractional cents never accrue in the customer's favour.-pub fn list_rate_cents(provider_cost_usd: f64) -> i64 {- if !provider_cost_usd.is_finite() || provider_cost_usd <= 0.0 {- return 0;- }- let markup = BPS_PER_UNIT as f64 / (BPS_PER_UNIT - TARGET_GROSS_MARGIN_BPS) as f64;- (provider_cost_usd * 100.0 * markup).ceil() as i64-}--/// One-off credit packs a payer may buy, in list-rate cents.+/// One-off credit packs a payer may buy, in customer cents.pub const CREDIT_PACKS_CENTS: [i64; 4] = [1_000, 2_500, 5_000, 10_000];/// Smallest per-period overage cap a payer may set.@@ -96,12 +83,13 @@ pub enum PlanTier {Free,/// The $40/seat/month plan (recorded as the legacy `sub_opus` role).Premium,- /// The $200/seat/month plan with a 5x AI allowance.+ /// The $200/seat/month plan. Its AI allowance equals Premium's until GTM+ /// defines a Max allowance.Max,}impl PlanTier {- /// Monthly list price per seat, in cents.+ /// Monthly subscription price per seat, in cents.pub const fn monthly_price_cents(self) -> i64 {match self {PlanTier::Free => 0,@@ -110,11 +98,14 @@ impl PlanTier {}}- /// Legacy AI usage included per seat per period, in list-rate cents. Equal to the- /// plan price by construction: spending it all costs Macro- /// `price x (1 - margin)`, which is exactly the target margin.+ /// AI usage included per seat per period, in cents at provider cost+ /// ([`INCLUDED_ALLOWANCE_CENTS`] for every paid plan, nothing for Free).pub const fn included_ai_cents_per_seat(self) -> i64 {- self.monthly_price_cents()+ if self.is_paid() {+ INCLUDED_ALLOWANCE_CENTS+ } else {+ 0+ }}/// Whether this tier pays for AI at all (credits and overage need a plan).@@ -314,7 +305,7 @@ pub enum PayerScope {pub struct SeatAllowance {/// The user occupying the seat.pub user: MacroUserIdStr<'static>,- /// Included AI for this seat, in list-rate cents.+ /// Included AI for this seat, in cents at provider cost.pub included_cents: i64,}@@ -323,7 +314,7 @@ pub struct SeatAllowance {pub struct SeatUsage {/// The user occupying the seat.pub user: MacroUserIdStr<'static>,- /// Usage at Macro's list rate, in cents.+ /// Usage in cents at provider cost.pub used_cents: i64,}@@ -365,7 +356,7 @@ impl Entitlement {self.billed_users.len().max(1) as u32}- /// Included AI for this user's seat, in list-rate cents.+ /// Included AI for this user's seat, in cents at provider cost.pub fn included_ai_cents(&self) -> i64 {self.tier.included_ai_cents_per_seat()}@@ -397,7 +388,7 @@ impl Entitlement {pub struct BillingSettings {/// Whether usage past allowance and credits is billed as overage.pub overage_enabled: bool,- /// Per-period cap on overage, in list-rate cents.+ /// Per-period cap on overage, in customer cents.pub overage_limit_cents: i64,/// Set when an overage charge failed to collect.pub overage_suspended_at: Option<DateTime<Utc>>,@@ -518,27 +509,29 @@ pub struct UsageSnapshot {pub period_start: DateTime<Utc>,/// Period end (exclusive).pub period_end: DateTime<Utc>,- /// Included AI for this user's seat this period, in list-rate cents.+ /// Included AI for this user's seat this period, in cents at provider cost.pub included_cents: i64,- /// AI used by this user this period, in list-rate cents.+ /// AI used by this user this period, in cents at provider cost.pub used_cents: i64,- /// Shared payer credits already applied to this period.+ /// Shared payer credits already applied to this period, in customer cents.pub credits_consumed_cents: i64,- /// Shared prepaid credit balance.+ /// Shared prepaid credit balance, in customer cents.pub credit_balance_cents: i64,/// Whether overage billing is on.pub overage_enabled: bool,- /// Per-period overage cap.+ /// Per-period overage cap, in customer cents.pub overage_limit_cents: i64,- /// Shared overage charged so far this period.+ /// Shared overage charged so far this period, in customer cents.pub overage_charged_cents: i64,/// Whether overage is paused after a failed charge.pub overage_suspended: bool,- /// Team-wide usage beyond per-seat allowances that is not yet covered by- /// shared credits or charges (awaiting settlement).+ /// Team-wide usage beyond per-seat allowances, at the overage markup, that+ /// is not yet covered by shared credits or charges (awaiting settlement).+ /// Customer cents.pub uncovered_cents: i64,- /// This seat's remaining allowance plus shared credit/overage headroom; 0- /// when blocked.+ /// Cost cents of usage this seat may still consume: its remaining allowance+ /// plus whatever shared credit and overage headroom pays for at the markup.+ /// 0 when blocked.pub remaining_cents: i64,/// Why requests are refused right now, if they are.#[serde(skip_serializing_if = "Option::is_none")]diff --git a/crates/ai_billing/src/domain/policy.rs b/crates/ai_billing/src/domain/policy.rsindex cc322e3f4d..4146ccc3a2 100644--- a/crates/ai_billing/src/domain/policy.rs+++ b/crates/ai_billing/src/domain/policy.rs@@ -26,6 +26,7 @@ use super::models::{BillingPeriod, BillingSettings, Entitlement, MIN_STRIPE_CHARGE_CENTS, NON_BILLABLE_AI_FEATURES,OVERAGE_CHARGE_THRESHOLD_CENTS, PlanTier, UsagePolicy,};+use super::pricing::{INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT};#[cfg(test)]mod test;@@ -33,12 +34,15 @@ mod test;const ZERO_PUBLIC: PublicUsage = PublicUsage::from_units(0);const ZERO_MONEY: CustomerMoney = CustomerMoney::from_units(0);const PUBLIC_UNITS_PER_CENT: u64 = CustomerMoney::UNITS_PER_CENT / 100;-const EXTRA_RATE_NUMERATOR: u64 = 105;+// Both figures come from `pricing`, so this policy and the ledger never disagree.+// A whole-percent markup over 100 prices every public unit exactly.+const EXTRA_RATE_NUMERATOR: u64 = 100 + OVERAGE_MARKUP_PERCENT as u64;const EXTRA_RATE_DENOMINATOR: u64 = 100;-/// Non-rolling $20 public-provider-price allowance for each activated seat and period.+/// Non-rolling public-provider-price allowance for each activated seat and+/// period: [`INCLUDED_ALLOWANCE_CENTS`] of public usage.pub const INCLUDED_PUBLIC_USAGE: PublicUsage =- PublicUsage::from_units(2_000 * PUBLIC_UNITS_PER_CENT);+ PublicUsage::from_units(INCLUDED_ALLOWANCE_CENTS as u64 * PUBLIC_UNITS_PER_CENT);/// Accounting path after a trusted caller resolves the recorded policy and entitlement./// This is not eligibility detection: a Premium role alone must never activate V1.@@ -75,9 +79,10 @@ pub fn accounting_route(/// Pricing is independent of which source funds the usage.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PricingCategory {- /// First $20 public usage: zero additional customer money, no markup.+ /// Public usage within the allowance: zero additional customer money, no markup.Included,- /// Beyond $20: public usage multiplied by exactly 1.05 (not divided by 0.95).+ /// Beyond the allowance: public usage multiplied by exactly+ /// `(100 + OVERAGE_MARKUP_PERCENT) / 100` (never divided by the complement).Extra,}diff --git a/crates/ai_billing/src/domain/policy/test.rs b/crates/ai_billing/src/domain/policy/test.rsindex b117e60e61..f9a6bdf5a6 100644--- a/crates/ai_billing/src/domain/policy/test.rs+++ b/crates/ai_billing/src/domain/policy/test.rs@@ -556,8 +556,11 @@ fn legacy_free_enterprise_and_exempt_features_keep_their_paths() {AccountingRoute::Unmetered);assert_eq!(PlanTier::Premium.monthly_price_cents(), 4_000);- assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), 20_000);- assert_eq!(super::super::models::list_rate_cents(1.0), 250);+ // Both accounting paths read the same allowance constant.+ let allowance = super::super::pricing::INCLUDED_ALLOWANCE_CENTS;+ assert_eq!(PlanTier::Premium.included_ai_cents_per_seat(), allowance);+ assert_eq!(PlanTier::Max.included_ai_cents_per_seat(), allowance);+ assert_eq!(INCLUDED_PUBLIC_USAGE, public_cents(allowance as u64));let mut auth = authorization(true);auth.policy = UsagePolicy::Legacy;assert!(matches!(diff --git a/crates/ai_billing/src/domain/ports.rs b/crates/ai_billing/src/domain/ports.rsindex 5622aa0a83..05bce8bf67 100644--- a/crates/ai_billing/src/domain/ports.rs+++ b/crates/ai_billing/src/domain/ports.rs@@ -71,15 +71,15 @@ pub trait EntitlementSource: Send + Sync + 'static {) -> impl Future<Output = Result<Option<MacroUserIdStr<'static>>>> + Send;}-/// Reads recorded, metered AI usage at Macro's list rate.+/// Reads recorded, metered AI usage at provider cost.pub trait UsageReader: Send + Sync + 'static {- /// List-rate usage for each of `users` within `period`.+ /// Usage in cost cents for each of `users` within `period`.////// Only rows with the persisted `count_usage = TRUE` decision consume a user's/// allowance, credits, or overage. Historical and uncounted rows remain available/// for cost tracking. The period is inclusive at the start and exclusive at the end;/// users with no counted rows are omitted, and an empty user list returns no rows.- fn list_rate_usage_cents_by_user(+ fn usage_cost_cents_by_user(&self,users: &[MacroUserIdStr<'static>],period: BillingPeriod,@@ -91,7 +91,7 @@ pub trait UsageReader: Send + Sync + 'static {pub struct PendingCharge {/// The `ai_overage_charge` row.pub id: Uuid,- /// Amount to collect, list-rate cents.+ /// Amount to collect, customer cents.pub amount_cents: i64,/// The Stripe invoice an earlier attempt opened for this charge, if any./// A retry pays that invoice instead of opening a second one.@@ -154,7 +154,7 @@ pub trait BillingRepo: Send + Sync + 'static {payer: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<()>> + Send;- /// Current prepaid balance, list-rate cents.+ /// Current prepaid balance, customer cents.fn credit_balance_cents(&self,payer: &MacroUserIdStr<'_>,@@ -212,9 +212,12 @@ pub trait BillingRepo: Send + Sync + 'static {/// Atomically settle a period: under the payer's row lock, re-read the/// ledger, run [`plan_settlement`](super::ledger::plan_settlement) with the/// stored overage settings, book credit consumption, and reserve a- /// pending overage charge. `chargeable_cents` is the sum of each seat's- /// usage beyond its own allowance. The overage policy is read inside the lock, with- /// `charge_threshold_cents` and `period_ended` taken from `policy`.+ /// pending overage charge. `chargeable_customer_cents` is the period's+ /// cumulative usage beyond each seat's own allowance, already converted to+ /// customer cents at the overage markup+ /// ([`extra_customer_cents`](super::pricing::extra_customer_cents)). The+ /// overage policy is read inside the lock, with `charge_threshold_cents` and+ /// `period_ended` taken from `policy`.////// A charge that was reserved earlier but never collected is handed back/// before anything new is reserved, so retries reuse its id (and so its@@ -233,7 +236,7 @@ pub trait BillingRepo: Send + Sync + 'static {&self,payer: &MacroUserIdStr<'_>,period_start: DateTime<Utc>,- chargeable_cents: i64,+ chargeable_customer_cents: i64,policy: SettlementPolicy,) -> impl Future<Output = Result<SettlementOutcome>> + Send;@@ -271,7 +274,7 @@ pub struct CreditCheckoutRequest {pub customer_id: String,/// The payer, stamped on the session so the webhook can book it.pub payer: MacroUserIdStr<'static>,- /// Pack size, list-rate cents.+ /// Pack size, customer cents.pub amount_cents: i64,/// Where Stripe returns the user after paying.pub success_url: String,@@ -287,7 +290,7 @@ pub struct OverageChargeRequest {/// The reserved charge; doubles as the idempotency key, so opening the/// same charge twice yields the same invoice.pub charge_id: Uuid,- /// Amount, list-rate cents.+ /// Amount, customer cents.pub amount_cents: i64,/// Line description shown on the invoice.pub description: String,@@ -364,9 +367,9 @@ pub trait BillingService: Send + Sync + 'static {/// Admission is a read of the position at this instant; usage is/// metered after the completion, so requests that are in flight together/// can each be admitted against the same headroom. The overshoot is- /// bounded by one completion per concurrent request, is billed at list- /// rate like everything else, and can only exceed the payer's overage cap- /// by that much. Reserving capacity per request would need a second+ /// bounded by one completion per concurrent request, is priced at the+ /// same markup as everything else, and can only exceed the payer's overage+ /// cap by that much. Reserving capacity per request would need a second/// ledger write on every completion; the gate deliberately does not.fn check_allowance(&self,diff --git a/crates/ai_billing/src/domain/pricing.rs b/crates/ai_billing/src/domain/pricing.rsnew file mode 100644index 0000000000..1f5a71243d--- /dev/null+++ b/crates/ai_billing/src/domain/pricing.rs@@ -0,0 +1,65 @@+//! The two numbers GTM owns, and the conversions between provider cost and+//! customer money that every billing path shares.+//!+//! Usage and the in-plan allowance are measured in **cost cents**: the+//! provider's public price for what was consumed, in whole cents. Credits,+//! overage charges, caps and credit packs are **customer cents**: what the+//! customer actually pays. The two meet only where usage runs past the+//! allowance, which is marked up by [`OVERAGE_MARKUP_PERCENT`].+//!+//! Change a constant and redeploy to change pricing. The exact-money+//! public-allowance policy in [`super::policy`] derives its figures from the+//! same two constants, so the ledger and that policy can never disagree.++#[cfg(test)]+mod test;++/// In-plan AI allowance per paid seat per billing period, in cents at+/// provider cost. The same for every paid plan until GTM defines otherwise.+pub const INCLUDED_ALLOWANCE_CENTS: i64 = 2_000;++/// Markup on usage beyond the allowance, as a whole percent of provider cost.+///+/// Whole percents only: the exact-money path prices public usage over a+/// denominator of 100 (`CustomerMoney::from_public_ratio`) and rejects finer+/// rates at runtime.+pub const OVERAGE_MARKUP_PERCENT: i64 = 5;++const _: () = assert!(INCLUDED_ALLOWANCE_CENTS >= 0);+const _: () = assert!(OVERAGE_MARKUP_PERCENT >= 0 && OVERAGE_MARKUP_PERCENT < 100);++const PERCENT: i64 = 100;++/// Provider cost in USD to whole cents at cost, rounded up so fractions of a+/// cent never accrue in the customer's favour. Non-finite and non-positive+/// amounts are zero.+///+/// The product is first rounded to a millionth of a cent: provider totals are+/// summed as binary floating point, and `0.07 * 100.0` is `7.000000000000001`,+/// which a bare `ceil` would charge as 8.+pub fn cost_cents(provider_cost_usd: f64) -> i64 {+ if !provider_cost_usd.is_finite() || provider_cost_usd <= 0.0 {+ return 0;+ }+ let micro_cents = (provider_cost_usd * 100.0 * 1_000_000.0).round();+ (micro_cents / 1_000_000.0).ceil() as i64+}++/// Customer cents owed for `cost_cents` of usage beyond the allowance.+///+/// Apply this to a period's *cumulative* chargeable cost and book the+/// difference from what was already covered, never to each increment:+/// `extra(1) + extra(1)` is 4 but `extra(2)` is 3.+pub fn extra_customer_cents(cost_cents: i64) -> i64 {+ let marked_up = cost_cents+ .max(0)+ .saturating_mul(PERCENT + OVERAGE_MARKUP_PERCENT);+ // Ceiling division; `i64::div_ceil` is not stable.+ marked_up.saturating_add(PERCENT - 1) / PERCENT+}++/// The most cost cents of usage that `customer_cents` pays for at the markup:+/// the largest `cost` with `extra_customer_cents(cost) <= customer_cents`.+pub fn cost_cents_covered_by(customer_cents: i64) -> i64 {+ customer_cents.max(0).saturating_mul(PERCENT) / (PERCENT + OVERAGE_MARKUP_PERCENT)+}diff --git a/crates/ai_billing/src/domain/pricing/test.rs b/crates/ai_billing/src/domain/pricing/test.rsnew file mode 100644index 0000000000..80d5f0bc99--- /dev/null+++ b/crates/ai_billing/src/domain/pricing/test.rs@@ -0,0 +1,72 @@+use super::*;++#[test]+fn cost_cents_rounds_fractions_up_and_ignores_junk() {+ assert_eq!(cost_cents(16.0), 1_600);+ assert_eq!(cost_cents(0.001), 1);+ // 0.07 * 100.0 is 7.000000000000001 in binary floating point.+ assert_eq!(cost_cents(0.07), 7);+ assert_eq!(cost_cents(0.29), 29);+ assert_eq!(cost_cents(0.0), 0);+ assert_eq!(cost_cents(-3.0), 0);+ assert_eq!(cost_cents(f64::NAN), 0);+ assert_eq!(cost_cents(f64::INFINITY), 0);+}++#[test]+fn markup_rounds_up_on_the_cumulative_total() {+ assert_eq!(extra_customer_cents(0), 0);+ assert_eq!(extra_customer_cents(1), 2);+ assert_eq!(extra_customer_cents(19), 20);+ assert_eq!(extra_customer_cents(20), 21);+ assert_eq!(extra_customer_cents(1_000), 1_050);+ assert_eq!(extra_customer_cents(1_500), 1_575);+ assert_eq!(extra_customer_cents(-5), 0);+}++#[test]+fn cumulative_conversion_books_exact_increments() {+ // Settle at cost 1_000, then again at 1_500: the increments sum to extra(1_500).+ let first = extra_customer_cents(1_000);+ let second = extra_customer_cents(1_500) - first;+ assert_eq!((first, second), (1_050, 525));+ assert_eq!(first + second, extra_customer_cents(1_500));+ // Converting each increment on its own would overcharge.+ assert_eq!(extra_customer_cents(1) + extra_customer_cents(1), 4);+ assert_eq!(extra_customer_cents(2), 3);+}++#[test]+fn covered_cost_is_the_exact_inverse_of_the_markup() {+ assert_eq!(cost_cents_covered_by(0), 0);+ assert_eq!(cost_cents_covered_by(1), 0);+ assert_eq!(cost_cents_covered_by(2), 1);+ assert_eq!(cost_cents_covered_by(104), 99);+ assert_eq!(cost_cents_covered_by(105), 100);+ assert_eq!(cost_cents_covered_by(-1), 0);+ for cost in 0..10_000 {+ assert_eq!(cost_cents_covered_by(extra_customer_cents(cost)), cost);+ }+ for customer in 0..10_000 {+ let covered = cost_cents_covered_by(customer);+ assert!(extra_customer_cents(covered) <= customer);+ assert!(customer < extra_customer_cents(covered + 1));+ }+}++#[test]+fn constants_feed_the_exact_money_policy() {+ use crate::domain::policy::INCLUDED_PUBLIC_USAGE;+ use ai_usage::domain::financial::{CustomerMoney, PublicUsage};++ let public_units_per_cent = CustomerMoney::UNITS_PER_CENT / 100;+ assert_eq!(+ INCLUDED_PUBLIC_USAGE.units(),+ INCLUDED_ALLOWANCE_CENTS as u64 * public_units_per_cent+ );+ // A whole-percent markup over a denominator of 100 prices every public unit exactly.+ let numerator = (PERCENT + OVERAGE_MARKUP_PERCENT) as u64;+ let money =+ CustomerMoney::from_public_ratio(PublicUsage::from_units(1), numerator, 100).unwrap();+ assert_eq!(money.units(), numerator);+}diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex ce64786813..dcca3f2708 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -16,6 +16,7 @@ use super::ports::{BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,PaymentGateway, PendingCharge, UsageReader,};+use super::pricing::extra_customer_cents;use ai_usage::AiUsageEnforcement;use chrono::{DateTime, Utc};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};@@ -86,7 +87,8 @@ fn usage_for(user: &MacroUserIdStr<'_>, usage: &[SeatUsage]) -> i64 {.unwrap_or(0)}-fn chargeable_usage_cents(seats: &[SeatAllowance], usage: &[SeatUsage]) -> i64 {+/// Cost cents of usage beyond each seat's own allowance, summed for the payer.+fn chargeable_cost_cents(seats: &[SeatAllowance], usage: &[SeatUsage]) -> i64 {seats.iter().map(|seat| (usage_for(&seat.user, usage) - seat.included_cents).max(0))@@ -203,14 +205,11 @@ wheresettings,period,} = position;- let (used_cents, chargeable_cents, ledger, credit_balance_cents) =+ let (used_cents, chargeable_customer_cents, ledger, credit_balance_cents) =if entitlement.tier.is_paid() {let seats = entitlement.seat_allowances();let users: Vec<_> = seats.iter().map(|seat| seat.user.clone()).collect();- let usage = self- .usage- .list_rate_usage_cents_by_user(&users, *period)- .await?;+ let usage = self.usage.usage_cost_cents_by_user(&users, *period).await?;let seats = self.repo.legacy_seats(&entitlement.payer, *period, seats)@@ -220,7 +219,7 @@ where} else {0};- let chargeable = chargeable_usage_cents(&seats, &usage);+ let chargeable = extra_customer_cents(chargeable_cost_cents(&seats, &usage));let ledger = self.repo.period_ledger(&entitlement.payer, period.start)@@ -237,7 +236,7 @@ wheresettings,*period,used_cents,- chargeable_cents,+ chargeable_customer_cents,ledger,credit_balance_cents,))@@ -283,10 +282,7 @@ where) -> Result<()> {let seats = self.allowance_for_period(entitlement, period, now).await?;let users: Vec<_> = seats.iter().map(|seat| seat.user.clone()).collect();- let usage = self- .usage- .list_rate_usage_cents_by_user(&users, period)- .await?;+ let usage = self.usage.usage_cost_cents_by_user(&users, period).await?;// Read policy AFTER analytics. V1 execution requires a committed binding,// so any V1 analytics just observed must now be excluded. Filtering before// the usage read would race renewal activation and could double bill.@@ -294,17 +290,20 @@ where.repo.legacy_seats(&entitlement.payer, period, seats).await?;- let chargeable_cents = chargeable_usage_cents(&seats, &usage);- if chargeable_cents == 0 {+ let chargeable_cost = chargeable_cost_cents(&seats, &usage);+ if chargeable_cost == 0 {return Ok(());}+ // Mark up the cumulative total, never an increment: the repository+ // books the difference from what earlier settlements already covered.+ let chargeable_customer_cents = extra_customer_cents(chargeable_cost);let outcome = self.repo.apply_settlement(&entitlement.payer,period.start,- chargeable_cents,+ chargeable_customer_cents,SettlementPolicy {// The repo reads the live overage settings under its lock;// these two are the caller's contribution.diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 7209e72865..ef8a75fe22 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -102,7 +102,7 @@ impl FakeUsage {impl UsageReader for FakeUsage {/// `cents` is treated as current usage for the first requested user./// `entries` are summed when their timestamp falls in the requested period.- async fn list_rate_usage_cents_by_user(+ async fn usage_cost_cents_by_user(&self,users: &[MacroUserIdStr<'static>],period: BillingPeriod,@@ -343,7 +343,7 @@ impl BillingRepo for FakeRepo {&self,_payer: &MacroUserIdStr<'_>,period_start: DateTime<Utc>,- chargeable_cents: i64,+ chargeable_customer_cents: i64,policy: SettlementPolicy,) -> Result<SettlementOutcome> {let mut s = self.state.lock().unwrap();@@ -352,7 +352,7 @@ impl BillingRepo for FakeRepo {s.settings.overage_enabled && !s.suspended && s.settings.overage_limit_cents > 0;let plan = plan_settlement(crate::domain::ledger::SettlementState {- chargeable_cents,+ chargeable_customer_cents,credits_consumed_cents: ledger.credits_consumed_cents,overage_charged_cents: ledger.overage_charged_cents,credit_balance_cents: s.balance,@@ -619,7 +619,7 @@ async fn recorded_new_policy_never_enters_legacy_analytics_settlement() {async fn policy_activation_during_analytics_read_cannot_double_bill() {struct ActivatingUsage(FakeRepo);impl UsageReader for ActivatingUsage {- async fn list_rate_usage_cents_by_user(+ async fn usage_cost_cents_by_user(&self,users: &[MacroUserIdStr<'static>],_period: BillingPeriod,@@ -652,13 +652,13 @@ async fn policy_activation_during_analytics_read_cannot_double_bill() {#[tokio::test]async fn allows_within_allowance_and_denies_past_it() {- let (svc, _, _, usage) = premium_service(3_000);+ let (svc, _, _, usage) = premium_service(1_500);let payer = user("[email protected]");assert_eq!(svc.check_allowance(&payer).await.unwrap(),AllowanceDecision::Allow);- *usage.cents.lock().unwrap() = 4_000;+ *usage.cents.lock().unwrap() = 2_000;assert_eq!(svc.check_allowance(&payer).await.unwrap(),AllowanceDecision::Deny(DenyReason::AllowanceExhausted)@@ -838,7 +838,7 @@ async fn free_users_are_not_gated() {#[tokio::test]async fn credits_unblock_and_settlement_consumes_them() {- let (svc, repo, ..) = premium_service(4_600);+ let (svc, repo, ..) = premium_service(2_600);let payer = user("[email protected]");assert!(matches!(svc.check_allowance(&payer).await.unwrap(),@@ -848,12 +848,13 @@ async fn credits_unblock_and_settlement_consumes_them() {svc.apply_credit_purchase(&payer, 2_500, "cs_1").await.unwrap();- // The purchase settles: 600 consumed, 1_900 left.+ // The purchase settles: 600 cost over is 630 consumed, 1_870 left, which+ // pays for 1_780 more cost cents at the markup.let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.credits_consumed_cents, 600);- assert_eq!(snap.credit_balance_cents, 1_900);+ assert_eq!(snap.credits_consumed_cents, 630);+ assert_eq!(snap.credit_balance_cents, 1_870);assert_eq!(snap.uncovered_cents, 0);- assert_eq!(snap.remaining_cents, 1_900);+ assert_eq!(snap.remaining_cents, 1_780);assert_eq!(svc.check_allowance(&payer).await.unwrap(),AllowanceDecision::Allow@@ -863,25 +864,26 @@ async fn credits_unblock_and_settlement_consumes_them() {svc.apply_credit_purchase(&payer, 2_500, "cs_1").await.unwrap();- assert_eq!(repo.state.lock().unwrap().balance, 1_900);+ assert_eq!(repo.state.lock().unwrap().balance, 1_870);}#[tokio::test]async fn overage_is_charged_in_chunks_and_respects_the_cap() {- let (svc, repo, payments, usage) = premium_service(4_500);+ let (svc, repo, payments, usage) = premium_service(2_500);let payer = user("[email protected]");let snap = svc.update_overage(&payer, true, 2_000).await.unwrap();assert!(snap.overage_enabled);- // 500 over: under the $10 chunk, nothing charged yet but plenty of room.+ // 500 cost over is 525 owed: under the $10 chunk, nothing charged yet, and+ // the 1_475 of room left pays for 1_404 more cost cents.assert_eq!(snap.overage_charged_cents, 0);- assert_eq!(snap.remaining_cents, 1_500);+ assert_eq!(snap.remaining_cents, 1_404);- *usage.cents.lock().unwrap() = 5_200;+ *usage.cents.lock().unwrap() = 3_200;svc.settle(&payer).await.unwrap();let opened = payments.opened();assert_eq!(opened.len(), 1);- assert_eq!(opened[0].amount_cents, 1_200);+ assert_eq!(opened[0].amount_cents, 1_260);assert_eq!(opened[0].customer_id, "cus_123");assert_eq!(opened[0].scope, SubscriptionScope::Personal);let charges = repo.charges();@@ -892,19 +894,19 @@ async fn overage_is_charged_in_chunks_and_respects_the_cap() {Some(format!("in_{}", charge.id).as_str()));- // Past the cap: the last 800 of room is under the charge chunk, so it+ // Past the cap: the last 740 of room is under the charge chunk, so it// waits for period end, and the payer is blocked with the right reason.- *usage.cents.lock().unwrap() = 7_000;+ *usage.cents.lock().unwrap() = 5_000;svc.settle(&payer).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.overage_charged_cents, 1_200);+ assert_eq!(snap.overage_charged_cents, 1_260);assert_eq!(snap.remaining_cents, 0);assert_eq!(snap.blocked_reason, Some(DenyReason::OverageLimitReached));}#[tokio::test]async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated() {- let (svc, repo, payments, _) = premium_service(5_500);+ let (svc, repo, payments, _) = premium_service(3_500);let payer = user("[email protected]");payments.set_pay(PayOutcome::Error);@@ -927,7 +929,7 @@ async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated()payments.set_pay(PayOutcome::Paid);let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_500);+ assert_eq!(snap.overage_charged_cents, 1_575);let charges = repo.charges();assert_eq!(charges.len(), 1);assert_eq!(charges[0].status, OverageChargeStatus::Paid);@@ -942,7 +944,7 @@ async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated()#[tokio::test]async fn opening_the_invoice_failing_marks_the_charge_failed() {- let (svc, repo, payments, _) = premium_service(5_500);+ let (svc, repo, payments, _) = premium_service(3_500);let payer = user("[email protected]");*payments.fail_open.lock().unwrap() = true;@@ -965,20 +967,20 @@ async fn opening_the_invoice_failing_marks_the_charge_failed() {#[tokio::test]async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried() {- let (svc, repo, payments, _) = premium_service(5_800);+ let (svc, repo, payments, _) = premium_service(3_800);let payer = user("[email protected]");*payments.fail_open.lock().unwrap() = true;svc.update_overage(&payer, true, 10_000).await.unwrap();assert_eq!(repo.charges()[0].status, OverageChargeStatus::Failed);assert!(repo.charges()[0].invoice.is_none());- // Credits arrive and cover the 1_800 that was never invoiced.+ // Credits arrive and cover the 1_890 (1_800 cost, marked up) that was never invoiced.*payments.fail_open.lock().unwrap() = false;svc.apply_credit_purchase(&payer, 2_500, "cs_1").await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.credits_consumed_cents, 1_800);+ assert_eq!(snap.credits_consumed_cents, 1_890);assert_eq!(snap.uncovered_cents, 0);// Re-enabling overage must not collect that stale charge.@@ -993,13 +995,13 @@ async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried()#[tokio::test]async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {- let (svc, repo, payments, _) = premium_service(7_000);+ let (svc, repo, payments, _) = premium_service(5_000);let payer = user("[email protected]");payments.set_pay(PayOutcome::Error);svc.update_overage(&payer, true, 10_000).await.unwrap();let first = repo.charges().into_iter().next().unwrap();- assert_eq!(first.amount_cents, 3_000);+ assert_eq!(first.amount_cents, 3_150);assert_eq!(first.status, OverageChargeStatus::Failed);assert!(first.invoice.is_some());@@ -1010,14 +1012,14 @@ async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {let snap = svc.snapshot(&payer).await.unwrap();assert_eq!(snap.credits_consumed_cents, 0);assert_eq!(snap.credit_balance_cents, 1_000);- assert_eq!(snap.overage_charged_cents, 3_000);+ assert_eq!(snap.overage_charged_cents, 3_150);svc.update_overage(&payer, true, 10_000).await.unwrap();let charges = repo.charges();assert_eq!(charges.len(), 1);assert_eq!(charges[0].id, first.id);assert_eq!(charges[0].status, OverageChargeStatus::Pending);- assert_eq!(charges[0].amount_cents, 3_000);+ assert_eq!(charges[0].amount_cents, 3_150);assert_eq!(charges[0].invoice, first.invoice);assert_eq!(payments.opened().len(), 1);assert_eq!(payments.payments().len(), 2);@@ -1025,14 +1027,14 @@ async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {#[tokio::test]async fn a_declined_card_leaves_the_invoice_open_for_the_webhook() {- let (svc, repo, payments, _) = premium_service(5_500);+ let (svc, repo, payments, _) = premium_service(3_500);let payer = user("[email protected]");payments.set_pay(PayOutcome::Declined);let snap = svc.update_overage(&payer, true, 5_000).await.unwrap();// Not suspended yet: Stripe retries, the webhook decides.assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_500);+ assert_eq!(snap.overage_charged_cents, 1_575);let charges = repo.charges();assert_eq!(charges[0].status, OverageChargeStatus::Pending);let invoice = charges[0].invoice.clone().unwrap();@@ -1041,7 +1043,7 @@ async fn a_declined_card_leaves_the_invoice_open_for_the_webhook() {let snap = svc.snapshot(&payer).await.unwrap();assert!(snap.overage_suspended);// Stripe may still retry the open invoice, so it remains coverage.- assert_eq!(snap.overage_charged_cents, 1_500);+ assert_eq!(snap.overage_charged_cents, 1_575);}#[tokio::test]@@ -1104,7 +1106,7 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {let snap = svc.snapshot(&member).await.unwrap();assert!(!snap.can_manage_billing);assert_eq!(snap.seats, 2);- assert_eq!(snap.included_cents, 4_000);+ assert_eq!(snap.included_cents, 2_000);}#[tokio::test]@@ -1125,7 +1127,7 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {.with(team).with_customer(&owner, "cus_owner");let usage = FakeUsage::default();- usage.add(&member, Utc::now(), 5_000);+ usage.add(&member, Utc::now(), 3_000);let repo = FakeRepo::default();let service =BillingServiceImpl::new(entitlements, usage, repo.clone(), FakePayments::default())@@ -1134,10 +1136,10 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {let owner_snapshot = service.snapshot(&owner).await.unwrap();assert_eq!(owner_snapshot.used_cents, 0);- assert_eq!(owner_snapshot.included_cents, 4_000);+ assert_eq!(owner_snapshot.included_cents, 2_000);let member_snapshot = service.snapshot(&member).await.unwrap();- assert_eq!(member_snapshot.used_cents, 5_000);- assert_eq!(member_snapshot.included_cents, 4_000);+ assert_eq!(member_snapshot.used_cents, 3_000);+ assert_eq!(member_snapshot.included_cents, 2_000);assert_eq!(member_snapshot.blocked_reason,Some(DenyReason::AllowanceExhausted)@@ -1147,16 +1149,17 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {.apply_credit_purchase(&owner, 2_500, "cs_team").await.unwrap();+ // 1_000 cost over the member's allowance is 1_050 of the shared credits.let member_snapshot = service.snapshot(&member).await.unwrap();- assert_eq!(member_snapshot.credits_consumed_cents, 1_000);- assert_eq!(member_snapshot.credit_balance_cents, 1_500);+ assert_eq!(member_snapshot.credits_consumed_cents, 1_050);+ assert_eq!(member_snapshot.credit_balance_cents, 1_450);assert_eq!(member_snapshot.blocked_reason, None);- assert_eq!(repo.state.lock().unwrap().balance, 1_500);+ assert_eq!(repo.state.lock().unwrap().balance, 1_450);}#[tokio::test]async fn overage_invoice_webhooks_update_suspension() {- let (svc, repo, payments, _) = premium_service(5_500);+ let (svc, repo, payments, _) = premium_service(3_500);let payer = user("[email protected]");payments.set_pay(PayOutcome::Declined);svc.update_overage(&payer, true, 5_000).await.unwrap();@@ -1169,13 +1172,13 @@ async fn overage_invoice_webhooks_update_suspension() {svc.mark_overage_invoice(&invoice, true).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_500);+ assert_eq!(snap.overage_charged_cents, 1_575);// Paid is terminal: a late or duplicate failure changes nothing.svc.mark_overage_invoice(&invoice, false).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 1_500);+ assert_eq!(snap.overage_charged_cents, 1_575);assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);// Unknown invoices are ignored.@@ -1185,13 +1188,13 @@ async fn overage_invoice_webhooks_update_suspension() {#[tokio::test]async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {- let (svc, repo, payments, usage) = premium_service(6_000);+ let (svc, repo, payments, usage) = premium_service(4_000);let payer = user("[email protected]");payments.set_pay(PayOutcome::Declined);- // Charge A: 2_000 over, declined, awaiting Stripe.+ // Charge A: 2_000 cost over, 2_100 owed, declined, awaiting Stripe.svc.update_overage(&payer, true, 10_000).await.unwrap();- // Charge B: another 1_500, also declined.- *usage.cents.lock().unwrap() = 7_500;+ // Charge B: another 1_500 cost, 1_575 owed, also declined.+ *usage.cents.lock().unwrap() = 5_500;svc.settle(&payer).await.unwrap();let charges = repo.charges();assert_eq!(charges.len(), 2);@@ -1207,19 +1210,19 @@ async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {svc.mark_overage_invoice(&a, true).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();assert!(snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 3_500);+ assert_eq!(snap.overage_charged_cents, 3_675);// B eventually collects: cleared, everything covered.svc.mark_overage_invoice(&b, true).await.unwrap();let snap = svc.snapshot(&payer).await.unwrap();assert!(!snap.overage_suspended);- assert_eq!(snap.overage_charged_cents, 3_500);+ assert_eq!(snap.overage_charged_cents, 3_675);// The mirror image: a late failure for an older invoice after the newest// charge went through does not re-suspend.- let (svc, repo, payments, usage) = premium_service(6_000);+ let (svc, repo, payments, usage) = premium_service(4_000);payments.set_pay(PayOutcome::Declined);svc.update_overage(&payer, true, 10_000).await.unwrap();- *usage.cents.lock().unwrap() = 7_500;+ *usage.cents.lock().unwrap() = 5_500;svc.settle(&payer).await.unwrap();let charges = repo.charges();let (a, b) = (@@ -1232,7 +1235,7 @@ async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {assert!(!snap.overage_suspended);// A remains coverage because its invoice can still collect. Settlement// retries that same invoice rather than replacing it.- assert_eq!(snap.overage_charged_cents, 3_500);+ assert_eq!(snap.overage_charged_cents, 3_675);assert_eq!(repo.charges()[0].status, OverageChargeStatus::Failed);}@@ -1310,74 +1313,98 @@ async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {frozen.seats,vec![SeatAllowance {user: payer.clone(),- included_cents: 4_000,+ included_cents: 2_000,}]);- ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));+ // A roster change while the period is open refreshes the freeze.+ let member = user("[email protected]");+ ents.set(Entitlement {+ tier: PlanTier::Premium,+ seat_tiers: vec![PlanTier::Premium, PlanTier::Premium],+ unlimited: false,+ payer: payer.clone(),+ billed_users: vec![payer.clone(), member.clone()],+ scope: PayerScope::TeamOwner {+ team_id: macro_uuid::generate_uuid_v7(),+ },+ });svc.snapshot(&payer).await.unwrap();let frozen = repo.allowance(current.start).expect("open period refreshed");- assert_eq!(frozen.seats[0].included_cents, 20_000);+ assert_eq!(+ frozen.seats,+ vec![+ SeatAllowance {+ user: payer.clone(),+ included_cents: 2_000,+ },+ SeatAllowance {+ user: member,+ included_cents: 2_000,+ },+ ]+ );}#[tokio::test]-async fn previous_period_overage_survives_an_upgrade() {- let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);+async fn previous_period_overage_uses_the_frozen_allowance_not_the_live_one() {+ let (svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(0);svc.sync_period(&payer, current.start, current.end, None).await.unwrap();+ // A smaller allowance was in force while the previous period was open.repo.freeze(previous.start,PeriodAllowance {seats: vec![SeatAllowance {user: payer.clone(),- included_cents: 4_000,+ included_cents: 1_000,}],},);svc.update_overage(&payer, true, 10_000).await.unwrap();- usage.add(&payer, previous.start + chrono::Duration::days(2), 5_500);+ usage.add(&payer, previous.start + chrono::Duration::days(2), 2_500);- ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));svc.settle(&payer).await.unwrap();let opened = payments.opened();assert_eq!(opened.len(), 1);- // 5_500 used against the frozen Premium 4_000, not Max's 20_000.- assert_eq!(opened[0].amount_cents, 1_500);+ // 2_500 cost against the frozen 1_000, not the live 2_000: 1_500 over, 1_575 owed.+ assert_eq!(opened[0].amount_cents, 1_575);assert_eq!(repo.charges()[0].status, OverageChargeStatus::Paid);- // The open period freeze now reflects Max; the closed one does not.+ // The closed period keeps its freeze; the open one reflects the live allowance.assert_eq!(repo.allowance(previous.start).unwrap().seats[0].included_cents,- 4_000+ 1_000);assert_eq!(repo.allowance(current.start).unwrap().seats[0].included_cents,- 20_000+ 2_000);}#[tokio::test]-async fn previous_period_does_not_charge_included_usage_after_a_downgrade() {- let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);+async fn previous_period_does_not_charge_usage_its_frozen_allowance_included() {+ let (svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(0);svc.sync_period(&payer, current.start, current.end, None).await.unwrap();+ // A larger allowance was in force while the previous period was open.repo.freeze(previous.start,PeriodAllowance {seats: vec![SeatAllowance {user: payer.clone(),- included_cents: 20_000,+ included_cents: 5_000,}],},);svc.update_overage(&payer, true, 10_000).await.unwrap();- usage.add(&payer, previous.start + chrono::Duration::days(2), 10_000);+ // Over the live 2_000, but inside the frozen 5_000.+ usage.add(&payer, previous.start + chrono::Duration::days(2), 4_000);- ents.set(Entitlement::personal(payer.clone(), PlanTier::Premium));svc.settle(&payer).await.unwrap();assert!(payments.opened().is_empty());@@ -1426,16 +1453,16 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {seats: vec![SeatAllowance {user: owner.clone(),- included_cents: 4_000,+ included_cents: 2_000,},SeatAllowance {user: member_a.clone(),- included_cents: 4_000,+ included_cents: 2_000,},],},);- usage.add(&member_a, previous.start + chrono::Duration::days(2), 9_200);+ usage.add(&member_a, previous.start + chrono::Duration::days(2), 7_200);usage.add(&member_b,previous.start + chrono::Duration::days(2),@@ -1447,38 +1474,44 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {let opened = payments.opened();assert_eq!(opened.len(), 1);- // Member A gets only their own $40 allowance, so 5_200 is chargeable.- // The owner's unused allowance does not offset it. Member B's usage is- // ignored because they were not a billed user in that period.- assert_eq!(opened[0].amount_cents, 5_200);+ // Member A gets only their own $20 at-cost allowance, so 5_200 cost is+ // chargeable: 5_460 at the markup. The owner's unused allowance does not+ // offset it. Member B's usage is ignored because they were not a billed+ // user in that period.+ assert_eq!(opened[0].amount_cents, 5_460);assert_eq!(opened[0].scope, SubscriptionScope::Team { team_id });}#[tokio::test]-async fn current_period_uses_the_live_allowance_after_an_upgrade() {- let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);+async fn current_period_uses_the_live_allowance_not_a_stale_freeze() {+ let (svc, repo, payments, usage, _, payer, _, current) = anchored_premium(0);svc.sync_period(&payer, current.start, current.end, None).await.unwrap();+ // A stale freeze of the open period with a smaller allowance.repo.freeze(- previous.start,+ current.start,PeriodAllowance {seats: vec![SeatAllowance {user: payer.clone(),- included_cents: 4_000,+ included_cents: 1_000,}],},);svc.update_overage(&payer, true, 10_000).await.unwrap();- // Current-period usage that exceeds Premium but sits inside Max.- *usage.cents.lock().unwrap() = 10_000;- ents.set(Entitlement::personal(payer.clone(), PlanTier::Max));+ // Current-period usage over the stale 1_000 but inside the live 2_000.+ *usage.cents.lock().unwrap() = 1_500;svc.settle(&payer).await.unwrap();assert!(payments.opened().is_empty());let snap = svc.snapshot(&payer).await.unwrap();- assert_eq!(snap.included_cents, 20_000);- assert_eq!(snap.used_cents, 10_000);+ assert_eq!(snap.included_cents, 2_000);+ assert_eq!(snap.used_cents, 1_500);assert_eq!(snap.uncovered_cents, 0);+ // The open period was re-frozen from the live entitlement.+ assert_eq!(+ repo.allowance(current.start).unwrap().seats[0].included_cents,+ 2_000+ );}fn open_anchor(now: DateTime<Utc>) -> (DateTime<Utc>, DateTime<Utc>, OpenPeriodStart) {@@ -1531,7 +1564,7 @@ async fn release_missing_team_leaves_allowances_unchanged() {PeriodAllowance {seats: vec![SeatAllowance {user: member.clone(),- included_cents: 4_000,+ included_cents: 2_000,}],},);@@ -1550,7 +1583,7 @@ async fn release_missing_team_leaves_allowances_unchanged() {repo.allowance(period_start).unwrap().seats,vec![SeatAllowance {user: member,- included_cents: 4_000,+ included_cents: 2_000,}]);}@@ -1568,7 +1601,7 @@ async fn release_refuses_to_remove_the_payer() {PeriodAllowance {seats: vec![SeatAllowance {user: owner.clone(),- included_cents: 4_000,+ included_cents: 2_000,}],},);@@ -1588,7 +1621,7 @@ async fn release_refuses_to_remove_the_payer() {repo.allowance(open.start()).unwrap().seats,vec![SeatAllowance {user: owner,- included_cents: 4_000,+ included_cents: 2_000,}]);}@@ -1608,14 +1641,15 @@ async fn position_keeps_matching_pairs_in_their_stored_order() {billed_users: vec![owner.clone(), member.clone()],scope: PayerScope::TeamOwner { team_id },};+ // The same seat/allowance pairs as the live entitlement, in another order.let stored = vec![SeatAllowance {user: member.clone(),- included_cents: 20_000,+ included_cents: 2_000,},SeatAllowance {user: owner.clone(),- included_cents: 4_000,+ included_cents: 2_000,},];let repo = FakeRepo::default();diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rsindex af20100258..278636231f 100644--- a/crates/ai_billing/src/inbound/axum_router.rs+++ b/crates/ai_billing/src/inbound/axum_router.rs@@ -34,16 +34,19 @@ pub struct AiBillingErrorBody {pub struct PlanCatalogEntry {/// The tier.pub tier: PlanTier,- /// Monthly list price per seat, cents.+ /// Monthly subscription price per seat, cents.pub monthly_price_cents: i64,- /// Included AI per seat per period, list-rate cents.+ /// Included AI per seat per period, in cents at provider cost.pub included_ai_cents_per_seat: i64,+ /// Whether a new purchase or plan move may pick this plan today.+ pub purchasable: bool,}/// The plan catalog and the knobs the billing UI offers.#[derive(Debug, Clone, Serialize, ToSchema)]pub struct PlanCatalogResponse {- /// Free and every purchasable paid plan, cheapest first.+ /// Every plan, cheapest first. Clients read allowances from here rather+ /// than hard-coding them; `purchasable` marks the plans a user can buy.pub plans: Vec<PlanCatalogEntry>,/// Credit packs a payer may buy, cents.pub credit_packs_cents: Vec<i64>,@@ -282,12 +285,15 @@ pub async fn get_summary_handler<B: BillingService, Auth: MacroAuthorizationServ)]pub async fn get_plans_handler() -> Json<PlanCatalogResponse> {Json(PlanCatalogResponse {- plans: std::iter::once(PlanTier::Free)- .chain(SeatPlan::PURCHASABLE.into_iter().map(PlanTier::from))+ plans: [PlanTier::Free, PlanTier::Premium, PlanTier::Max]+ .into_iter().map(|tier| PlanCatalogEntry {tier,monthly_price_cents: tier.monthly_price_cents(),included_ai_cents_per_seat: tier.included_ai_cents_per_seat(),+ purchasable: SeatPlan::PURCHASABLE+ .into_iter()+ .any(|plan| PlanTier::from(plan) == tier),}).collect(),credit_packs_cents: CREDIT_PACKS_CENTS.to_vec(),diff --git a/crates/ai_billing/src/inbound/axum_router/test.rs b/crates/ai_billing/src/inbound/axum_router/test.rsindex f71dac8656..0e7a7fc165 100644--- a/crates/ai_billing/src/inbound/axum_router/test.rs+++ b/crates/ai_billing/src/inbound/axum_router/test.rs@@ -1,5 +1,5 @@use super::{ReturnUrlError, get_plans_handler, validate_return_url};-use crate::domain::PlanTier;+use crate::domain::{INCLUDED_ALLOWANCE_CENTS, PlanTier};#[test]fn return_urls_must_be_https_on_the_calling_origin() {@@ -48,14 +48,20 @@ fn return_urls_must_be_https_on_the_calling_origin() {}#[tokio::test]-async fn plan_catalog_contains_only_free_and_purchasable_paid_plans() {- let tiers = get_plans_handler()- .await- .0- .plans- .into_iter()- .map(|plan| plan.tier)+async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {+ let plans = get_plans_handler().await.0.plans;+ let summary = plans+ .iter()+ .map(|plan| (plan.tier, plan.purchasable, plan.included_ai_cents_per_seat)).collect::<Vec<_>>();- assert_eq!(tiers, vec![PlanTier::Free, PlanTier::Premium]);+ // The frontend reads allowances from here, so every tier it can display is listed.+ assert_eq!(+ summary,+ vec![+ (PlanTier::Free, false, 0),+ (PlanTier::Premium, true, INCLUDED_ALLOWANCE_CENTS),+ (PlanTier::Max, false, INCLUDED_ALLOWANCE_CENTS),+ ]+ );}diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rsindex f06cd9845c..2bb581af6c 100644--- a/crates/ai_billing/src/lib.rs+++ b/crates/ai_billing/src/lib.rs@@ -2,26 +2,27 @@//! AI billing — plan allowances, prepaid credits, and post-paid overage.//!-//! # The margin model+//! # The pricing model//!-//! Every paid plan includes a monthly AI allowance equal to its list price,-//! measured at Macro's **list rate**. The list rate is provider cost marked up-//! so that a fully consumed allowance yields the target gross margin:+//! Every paid seat includes a monthly AI allowance measured **at cost**: the+//! provider's public price for what was consumed. Usage past the allowance is+//! covered, in order, by prepaid credits (bought in one-off Stripe Checkout+//! payments) and then by opt-in overage, billed to the payer's Stripe customer+//! in chunks. Both are priced at cost plus a small markup://!//! ```text-//! list = cost / (1 - margin) margin = 60% => list = 2.5 x cost-//! Premium: $40/mo includes $40 of AI at list ( = $16 of provider cost)-//! Max: $200/mo includes $200 of AI at list ( = $80 of provider cost)+//! allowance = INCLUDED_ALLOWANCE_CENTS ($20 of provider cost per seat per period)+//! extra = cost x (100 + OVERAGE_MARKUP_PERCENT) / 100 (5% over cost)//! ```//!-//! Usage past the allowance is covered, in order, by prepaid credits (bought-//! in one-off Stripe Checkout payments) and then by opt-in overage, billed to-//! the payer's Stripe customer in chunks at the same list rate. Both keep the-//! same margin as the plan itself.+//! Both numbers live in [`domain::pricing`]; change a constant and redeploy.+//! Usage and allowance are **cost cents**; credits, charges, caps and packs are+//! **customer cents**. The conversions in that module are the only place the+//! two units meet.//!//! # Layout//!-//! - [`domain`] — plan catalog, the margin math, the settlement ledger (pure),+//! - [`domain`] — plan catalog, pricing constants, the settlement ledger (pure),//! ports, and the service.//! - [`outbound`] — Postgres repos over `ai_usage` and the billing tables, the//! Stripe gateway, the roles + teams entitlement resolver, and the recorder@@ -46,6 +47,7 @@ pub use ai_usage::{AiFeature, AiUsageEnforcement};pub use domain::{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,+ CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement,+ INCLUDED_ALLOWANCE_CENTS, OVERAGE_MARKUP_PERCENT, PayerScope, PlanTier, UsageSnapshot,+ cost_cents, cost_cents_covered_by, extra_customer_cents,};diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rsindex 57556c708e..abea815068 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs@@ -1,5 +1,12 @@//! Postgres adapter for the billing tables (`ai_billing_account`,//! `ai_credit_ledger`, `ai_overage_charge`, `ai_billing_period_allowance`).+//!+//! Frozen allowances live in `ai_billing_period_allowance.included_cost_cents_by_user`+//! (cost cents). The legacy `included_cents_by_user` column predates the at-cost+//! model and is still written, with the same values, so a pre-cutover binary keeps+//! working during a deploy; it is never read here. A row whose cost column is+//! missing or does not match its roster was frozen by that older binary, and+//! every seat in it is priced at the current allowance.#[cfg(test)]mod test;@@ -7,9 +14,10 @@ mod test;use super::pg_funding_repo::{credit_commitments, lock_payer, postpaid_commitments};use crate::domain::financial::legacy_cap_remaining;use crate::domain::{- AllowanceStore, BillingError, BillingRepo, BillingSettings, OpenPeriodStart,- OverageChargeStatus, PendingCharge, PeriodAllowance, PeriodLedger, Result, SeatAllowance,- SeatGeneration, SettlementOutcome, SettlementPolicy, SettlementState, plan_settlement,+ AllowanceStore, BillingError, BillingRepo, BillingSettings, INCLUDED_ALLOWANCE_CENTS,+ OpenPeriodStart, OverageChargeStatus, PendingCharge, PeriodAllowance, PeriodLedger, Result,+ SeatAllowance, SeatGeneration, SettlementOutcome, SettlementPolicy, SettlementState,+ plan_settlement,};use chrono::{DateTime, Utc};use macro_user_id::user_id::MacroUserIdStr;@@ -210,7 +218,7 @@ impl BillingRepo for PgBillingRepo {let row = sqlx::query!(r#"SELECT billed_users as "billed_users!",- included_cents_by_user as "included_cents_by_user!"+ included_cost_cents_by_userFROM ai_billing_period_allowanceWHERE user_id = $1 AND period_start = $2"#,@@ -222,7 +230,7 @@ impl BillingRepo for PgBillingRepo {.map_err(storage)?;row.map(|r| {Ok(PeriodAllowance {- seats: parse_seat_allowances(r.billed_users, r.included_cents_by_user)?,+ seats: parse_seat_allowances(r.billed_users, r.included_cost_cents_by_user)?,})}).transpose()@@ -273,20 +281,24 @@ impl BillingRepo for PgBillingRepo {return Ok(AllowanceStore::Conflict);}+ // The legacy column receives the same values so an older binary can+ // still read the row during a deploy; see the module docs.sqlx::query!(r#"INSERT INTO ai_billing_period_allowance (- user_id, period_start, billed_users, included_cents_by_user+ user_id, period_start, billed_users, included_cents_by_user,+ included_cost_cents_by_user)- VALUES ($1, $2, $3, $4)+ VALUES ($1, $2, $3, $4, $4)ON CONFLICT (user_id, period_start) DO UPDATESET billed_users = EXCLUDED.billed_users,included_cents_by_user = EXCLUDED.included_cents_by_user,+ included_cost_cents_by_user = EXCLUDED.included_cost_cents_by_user,updated_at = NOW()WHERE ai_billing_period_allowance.billed_usersIS DISTINCT FROM EXCLUDED.billed_users- OR ai_billing_period_allowance.included_cents_by_user- IS DISTINCT FROM EXCLUDED.included_cents_by_user+ OR ai_billing_period_allowance.included_cost_cents_by_user+ IS DISTINCT FROM EXCLUDED.included_cost_cents_by_user"#,payer,period.start(),@@ -324,11 +336,18 @@ impl BillingRepo for PgBillingRepo {.await.map_err(storage)?;+ // A cost array that is missing or out of step with the roster (an older+ // binary refreshed the row) is dropped rather than excised positionally.sqlx::query!(r#"UPDATE ai_billing_period_allowance AS allowanceSET billed_users = excised.users,included_cents_by_user = excised.cents,+ included_cost_cents_by_user = CASE+ WHEN cardinality(allowance.included_cost_cents_by_user)+ = cardinality(allowance.billed_users)+ THEN excised.cost_cents+ END,updated_at = NOW()FROM (SELECT@@ -341,10 +360,16 @@ impl BillingRepo for PgBillingRepo {array_agg(seat.included_cents ORDER BY seat.ordinality)FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),ARRAY[]::bigint[]- )::bigint[] AS cents+ )::bigint[] AS cents,+ COALESCE(+ array_agg(seat.cost_cents ORDER BY seat.ordinality)+ FILTER (WHERE seat.billed_user IS DISTINCT FROM $3),+ ARRAY[]::bigint[]+ )::bigint[] AS cost_centsFROM ai_billing_period_allowance AS src- CROSS JOIN LATERAL unnest(src.billed_users, src.included_cents_by_user)- WITH ORDINALITY AS seat(billed_user, included_cents, ordinality)+ CROSS JOIN LATERAL unnest(+ src.billed_users, src.included_cents_by_user, src.included_cost_cents_by_user+ ) WITH ORDINALITY AS seat(billed_user, included_cents, cost_cents, ordinality)WHERE src.user_id = $1AND src.period_start = $2) AS excised@@ -396,7 +421,7 @@ impl BillingRepo for PgBillingRepo {&self,payer: &MacroUserIdStr<'_>,period_start: DateTime<Utc>,- chargeable_cents: i64,+ chargeable_customer_cents: i64,policy: SettlementPolicy,) -> Result<SettlementOutcome> {let payer = payer.as_ref();@@ -454,7 +479,7 @@ impl BillingRepo for PgBillingRepo {let plan = plan_settlement(SettlementState {- chargeable_cents,+ chargeable_customer_cents,credits_consumed_cents: ledger.credits_consumed_cents,overage_charged_cents: ledger.overage_charged_cents,credit_balance_cents: balance,@@ -700,15 +725,17 @@ async fn read_period_ledger(})}+/// Pair a frozen roster with its cost-cent allowances. A missing or mismatched+/// cost array means an older binary wrote the row; every seat then gets the+/// current allowance, which is what that binary's seats are entitled to now.fn parse_seat_allowances(billed_users: Vec<String>,- included_cents_by_user: Vec<i64>,+ included_cost_cents_by_user: Option<Vec<i64>>,) -> Result<Vec<SeatAllowance>> {- if billed_users.len() != included_cents_by_user.len() {- return Err(BillingError::Storage(anyhow::anyhow!(- "billed users and per-user allowances have different lengths"- )));- }+ let included_cents_by_user = match included_cost_cents_by_user {+ Some(cents) if cents.len() == billed_users.len() => cents,+ _ => vec![INCLUDED_ALLOWANCE_CENTS; billed_users.len()],+ };billed_users.into_iter().zip(included_cents_by_user)diff --git a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs b/crates/ai_billing/src/outbound/pg_billing_repo/test.rsindex ba735dcc26..cd0c8025e0 100644--- a/crates/ai_billing/src/outbound/pg_billing_repo/test.rs+++ b/crates/ai_billing/src/outbound/pg_billing_repo/test.rs@@ -485,11 +485,11 @@ async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {let seats = vec![SeatAllowance {user: payer.clone(),- included_cents: 4_000,+ included_cents: 2_000,},SeatAllowance {user: member.clone(),- included_cents: 20_000,+ included_cents: 1_000,},];@@ -512,11 +512,17 @@ async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {.unwrap().unwrap();assert_eq!(frozen.seats, seats);+ // Both columns carry the cost amounts; the legacy one keeps a pre-cutover binary working.+ let raw = raw_allowance(&pool, payer.as_ref(), open.start())+ .await+ .unwrap();+ assert_eq!(raw.included_cents_by_user, vec![2_000, 1_000]);+ assert_eq!(raw.included_cost_cents_by_user, Some(vec![2_000, 1_000]));// A later observation of the same open period refreshes.let max_payer = vec![SeatAllowance {user: payer.clone(),- included_cents: 20_000,+ included_cents: 2_500,}];assert_eq!(repo.store_open_allowance(&payer, open, &max_payer, SeatGeneration::from_raw(0))@@ -534,14 +540,15 @@ async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {sqlx::query!(r#"INSERT INTO ai_billing_period_allowance (- user_id, period_start, billed_users, included_cents_by_user+ user_id, period_start, billed_users, included_cents_by_user,+ included_cost_cents_by_user)- VALUES ($1, $2, $3, $4)+ VALUES ($1, $2, $3, $4, $4)"#,payer.as_ref(),earlier,&vec![payer.as_ref().to_string(), member.as_ref().to_string()],- &vec![4_000_i64, 20_000_i64],+ &vec![2_000_i64, 1_000_i64],).execute(&pool).await@@ -567,6 +574,7 @@ async fn period_allowance_roundtrips_and_upserts_per_period(pool: PgPool) {struct RawAllowance {billed_users: Vec<String>,included_cents_by_user: Vec<i64>,+ included_cost_cents_by_user: Option<Vec<i64>>,updated_at: chrono::DateTime<Utc>,}@@ -579,6 +587,7 @@ async fn raw_allowance(r#"SELECT billed_users AS "billed_users!",included_cents_by_user AS "included_cents_by_user!",+ included_cost_cents_by_user,updated_atFROM ai_billing_period_allowanceWHERE user_id = $1 AND period_start = $2@@ -592,6 +601,7 @@ async fn raw_allowance(.map(|row| RawAllowance {billed_users: row.billed_users,included_cents_by_user: row.included_cents_by_user,+ included_cost_cents_by_user: row.included_cost_cents_by_user,updated_at: row.updated_at,})}@@ -629,14 +639,17 @@ async fn release_open_seat_removes_the_middle_pair_and_leaves_the_closed_row(poobob.as_ref().to_string(),];let open_cents = vec![100_i64, 100, 300];- let closed_cents = vec![4_000_i64, 20_000, 4_000];+ let closed_cents = vec![2_000_i64, 1_000, 2_000];let seeded_at = open_start - chrono::Duration::days(2);+ // The open row was frozen by this binary (cost column present); the closed+ // row below predates the cost column.sqlx::query!(r#"INSERT INTO ai_billing_period_allowance (- user_id, period_start, billed_users, included_cents_by_user, updated_at+ user_id, period_start, billed_users, included_cents_by_user, updated_at,+ included_cost_cents_by_user)- VALUES ($1, $2, $3, $4, $5)+ VALUES ($1, $2, $3, $4, $5, $4)"#,payer.as_ref(),open.start(),@@ -674,12 +687,14 @@ async fn release_open_seat_removes_the_middle_pair_and_leaves_the_closed_row(poovec![payer.as_ref().to_string(), bob.as_ref().to_string()]);assert_eq!(open_row.included_cents_by_user, vec![100, 300]);+ assert_eq!(open_row.included_cost_cents_by_user, Some(vec![100, 300]));assert_ne!(open_row.updated_at, seeded_at);let closed_row = raw_allowance(&pool, payer.as_ref(), closed_start).await.unwrap();assert_eq!(closed_row.billed_users, users);assert_eq!(closed_row.included_cents_by_user, closed_cents);+ assert_eq!(closed_row.included_cost_cents_by_user, None);assert_eq!(closed_row.updated_at, seeded_at);assert_eq!(seat_generation(&pool, payer.as_ref()).await, Some(1));@@ -828,7 +843,7 @@ async fn release_open_seat_without_an_allowance_row_bumps_generation(pool: PgPooopen,&[SeatAllowance {user: member.clone(),- included_cents: 4_000,+ included_cents: 2_000,}],SeatGeneration::from_raw(0),)@@ -843,3 +858,85 @@ async fn release_open_seat_without_an_allowance_row_bumps_generation(pool: PgPoo.is_none());}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rows_frozen_before_the_cost_column_read_as_the_current_allowance(pool: PgPool) {+ let repo = PgBillingRepo::new(pool.clone());+ let payer = payer();+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();+ let users = vec![payer.as_ref().to_string(), member.as_ref().to_string()];+ let legacy_start = Utc::now() - chrono::Duration::days(40);+ let stale_start = legacy_start - chrono::Duration::days(30);+ // A pre-cutover binary wrote list-rate amounts and no cost column.+ sqlx::query!(+ r#"+ INSERT INTO ai_billing_period_allowance (+ user_id, period_start, billed_users, included_cents_by_user+ )+ VALUES ($1, $2, $3, $4)+ "#,+ payer.as_ref(),+ legacy_start,+ &users,+ &vec![4_000_i64, 20_000],+ )+ .execute(&pool)+ .await+ .unwrap();+ // An older binary refreshed the roster, leaving the cost column out of step.+ sqlx::query!(+ r#"+ INSERT INTO ai_billing_period_allowance (+ user_id, period_start, billed_users, included_cents_by_user,+ included_cost_cents_by_user+ )+ VALUES ($1, $2, $3, $4, $5)+ "#,+ payer.as_ref(),+ stale_start,+ &users,+ &vec![4_000_i64, 4_000],+ &vec![2_000_i64],+ )+ .execute(&pool)+ .await+ .unwrap();++ for start in [legacy_start, stale_start] {+ let seats = repo+ .period_allowance(&payer, start)+ .await+ .unwrap()+ .unwrap()+ .seats;+ assert_eq!(+ seats,+ vec![+ SeatAllowance {+ user: payer.clone(),+ included_cents: INCLUDED_ALLOWANCE_CENTS,+ },+ SeatAllowance {+ user: member.clone(),+ included_cents: INCLUDED_ALLOWANCE_CENTS,+ },+ ]+ );+ }++ // Releasing a seat from a pre-cutover row keeps the cost column empty rather+ // than excising a stale array positionally.+ let open = BillingPeriod {+ start: legacy_start,+ end: Utc::now() + chrono::Duration::days(20),+ }+ .open_start(Utc::now())+ .unwrap();+ repo.release_open_seat(&payer, open, &member).await.unwrap();+ let raw = raw_allowance(&pool, payer.as_ref(), legacy_start)+ .await+ .unwrap();+ assert_eq!(raw.billed_users, vec![payer.as_ref().to_string()]);+ assert_eq!(raw.included_cents_by_user, vec![4_000]);+ assert_eq!(raw.included_cost_cents_by_user, None);+}diff --git a/crates/ai_billing/src/outbound/pg_usage_reader.rs b/crates/ai_billing/src/outbound/pg_usage_reader.rsindex e2cfcba52a..3baf15c993 100644--- a/crates/ai_billing/src/outbound/pg_usage_reader.rs+++ b/crates/ai_billing/src/outbound/pg_usage_reader.rs@@ -1,9 +1,9 @@-//! Reads prospectively counted AI usage from `ai_usage` at Macro's list rate.+//! Reads prospectively counted AI usage from `ai_usage` at provider cost.#[cfg(test)]mod test;-use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, list_rate_cents};+use crate::domain::{BillingError, BillingPeriod, Result, SeatUsage, UsageReader, cost_cents};use macro_user_id::user_id::MacroUserIdStr;use sqlx::PgPool;@@ -31,7 +31,7 @@ impl PgUsageReader {}impl UsageReader for PgUsageReader {- async fn list_rate_usage_cents_by_user(+ async fn usage_cost_cents_by_user(&self,users: &[MacroUserIdStr<'static>],period: BillingPeriod,@@ -71,7 +71,7 @@ impl UsageReader for PgUsageReader {.map_err(|error| BillingError::Storage(error.into()))?;Ok(SeatUsage {user,- used_cents: list_rate_cents(row.usd),+ used_cents: cost_cents(row.usd),})}).collect()diff --git a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs b/crates/ai_billing/src/outbound/pg_usage_reader/test.rsindex d0604166fb..772e47b01e 100644--- a/crates/ai_billing/src/outbound/pg_usage_reader/test.rs+++ b/crates/ai_billing/src/outbound/pg_usage_reader/test.rs@@ -97,7 +97,7 @@ async fn aggregates_only_persisted_counted_rows_for_requested_seats(pool: PgPoollet reader = PgUsageReader::new(pool);let mut usage = reader- .list_rate_usage_cents_by_user(&[first.clone(), second.clone(), empty], current_period())+ .usage_cost_cents_by_user(&[first.clone(), second.clone(), empty], current_period()).await.unwrap();usage.sort_by(|a, b| a.user.as_ref().cmp(b.user.as_ref()));@@ -106,29 +106,29 @@ async fn aggregates_only_persisted_counted_rows_for_requested_seats(pool: PgPoolvec![SeatUsage {user: first.clone(),- used_cents: 1_000+ used_cents: 400},SeatUsage {user: second,- used_cents: 8_250+ used_cents: 3_300},]);assert!(reader- .list_rate_usage_cents_by_user(&[], current_period())+ .usage_cost_cents_by_user(&[], current_period()).await.unwrap().is_empty());assert_eq!(reader- .list_rate_usage_cents_by_user(std::slice::from_ref(&first), current_period())+ .usage_cost_cents_by_user(std::slice::from_ref(&first), current_period()).await.unwrap(),vec![SeatUsage {user: first,- used_cents: 1_000+ used_cents: 400}]);}@@ -160,14 +160,14 @@ async fn billing_period_includes_start_and_excludes_end(pool: PgPool) {.unwrap();}let usage = PgUsageReader::new(pool)- .list_rate_usage_cents_by_user(std::slice::from_ref(&user), BillingPeriod { start, end })+ .usage_cost_cents_by_user(std::slice::from_ref(&user), BillingPeriod { start, end }).await.unwrap();assert_eq!(usage,vec![SeatUsage {user,- used_cents: 500+ used_cents: 200}]);}@@ -222,7 +222,7 @@ async fn free_features_are_recorded_but_only_chat_and_editing_are_metered(pool:assert_eq!(stored_features, expected_features);let usage = PgUsageReader::new(pool)- .list_rate_usage_cents_by_user(std::slice::from_ref(&user), current_period())+ .usage_cost_cents_by_user(std::slice::from_ref(&user), current_period()).await.unwrap();@@ -230,7 +230,7 @@ async fn free_features_are_recorded_but_only_chat_and_editing_are_metered(pool:usage,vec![SeatUsage {user,- used_cents: 1_500,+ used_cents: 600,}]);}@@ -244,7 +244,7 @@ async fn free_features_alone_do_not_produce_billable_usage(pool: PgPool) {}let usage = PgUsageReader::new(pool)- .list_rate_usage_cents_by_user(&[user], current_period())+ .usage_cost_cents_by_user(&[user], current_period()).await.unwrap();assert!(usage.is_empty());@@ -267,17 +267,17 @@ async fn unpriced_free_features_are_excluded_from_fallback_billing(pool: PgPool)}let usage = PgUsageReader::new(pool)- .list_rate_usage_cents_by_user(std::slice::from_ref(&user), current_period())+ .usage_cost_cents_by_user(std::slice::from_ref(&user), current_period()).await.unwrap();- // Chat and editing each fall back to $5 per million input tokens, with- // the 2.5x list-rate markup. Unpriced free features add nothing.+ // Chat and editing each fall back to $5 per million input tokens, counted+ // at cost. Unpriced free features add nothing.assert_eq!(usage,vec![SeatUsage {user,- used_cents: 2_500,+ used_cents: 1_000,}]);}diff --git a/crates/macro_db_client/migrations/20261005162028_ai_billing_period_allowance_at_cost.sql b/crates/macro_db_client/migrations/20261005162028_ai_billing_period_allowance_at_cost.sqlnew file mode 100644index 0000000000..408efcdac9--- /dev/null+++ b/crates/macro_db_client/migrations/20261005162028_ai_billing_period_allowance_at_cost.sql@@ -0,0 +1,13 @@+-- AI allowances are now measured at provider cost: every paid seat includes+-- INCLUDED_ALLOWANCE_CENTS ($20) of cost per period (crates/ai_billing/src/domain/pricing.rs).+--+-- Frozen per-period rosters in ai_billing_period_allowance.included_cents_by_user+-- were written in the retired list-rate unit. This migration runs before the new+-- binary and must stay readable by the one still deployed, so it only adds a+-- column: the new binary writes cost cents here (and mirrors them into the legacy+-- column, which stays NOT NULL for the old binary), reads this column when it is+-- present and matches the roster, and otherwise prices every frozen seat at the+-- current allowance. Rows the old binary writes leave it NULL. Drop the legacy+-- column in a later migration once no pre-cutover binary can run.+ALTER TABLE ai_billing_period_allowance+ ADD COLUMN included_cost_cents_by_user BIGINT[];diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex e7ee2aa86f..bb614703ba 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -498,8 +498,9 @@ must not make a fallback model call. Managed sessions use their persisted ownerfor quota, not a collaborating sender. Externally funded runtimes skip sessionquota, but Macro-funded tools and helpers still check independently.-In dev, paid plans include a monthly AI allowance (Premium $40, Max $200, at Macro's-usage rates). When it is used up and no credits or usage billing cover the+In dev, paid plans include a monthly AI allowance of $20 per seat, measured at+provider cost; usage beyond it is billed at a small markup (both are constants in+`crates/ai_billing/src/domain/pricing.rs`). When it is used up and no credits or usage billing cover therequest, sending a message answers HTTP 402 and the app opens the**AI usage limit** dialog (title `You've used this month's included AI`, or thespending-limit / failed-charge variants). It shows the same meter and controlsdiff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.mdindex df4806efd4..4465037a58 100644--- a/docs/AI_QUOTA_ENFORCEMENT.md+++ b/docs/AI_QUOTA_ENFORCEMENT.md@@ -47,7 +47,7 @@ for both `record()` and `record_now()`, before the[repository insert](../crates/ai_usage/src/outbound/pg_usage_repo.rs). Clients cannotsupply it. The [billing reader](../crates/ai_billing/src/outbound/pg_usage_reader.rs)uses the persisted literal `count_usage = TRUE`, not a mutable feature exclusion-list. User/team-seat scoping, `[start, end)` periods, list-rate arithmetic, and+list. User/team-seat scoping, `[start, end)` periods, at-cost arithmetic, andfallback pricing for null totals are retained. Admin analytics still includesuncounted rows; repricing can change totals, never eligibility.@@ -69,6 +69,19 @@ independent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:there is no longer an `Environment::Develop` safeguard, so a true value settlesin production.+Pricing is two constants in+[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs): each paid seat includes+`INCLUDED_ALLOWANCE_CENTS` ($20) of usage per period measured at provider cost, and+usage beyond that is converted to customer money at `OVERAGE_MARKUP_PERCENT` (5%)+over cost before credits are consumed or overage is charged. The markup is applied+to the period's cumulative chargeable cost, so settling in chunks books the same+money as settling once. Change a constant and redeploy to change pricing. The+plan catalog (`GET /ai-billing/plans`) publishes `included_ai_cents_per_seat`+for every tier, and the frontend reads allowances from it+(`useIncludedAiCentsByTier`) rather than hard-coding them. Frozen per-period+rosters keep their cost amounts in `ai_billing_period_allowance.included_cost_cents_by_user`;+rows written before that column existed are priced at the current allowance.+Only two hosts participate:| Host | Gate | When disabled |diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 706d3ab7a5..31791d6fc3 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -1139,13 +1139,17 @@ export type Permission = {*/export type PlanCatalogEntry = {/**- * Included AI per seat per period, list-rate cents.+ * Included AI per seat per period, in cents at provider cost.*/included_ai_cents_per_seat: number;/**- * Monthly list price per seat, cents.+ * Monthly subscription price per seat, cents.*/monthly_price_cents: number;+ /**+ * Whether a new purchase or plan move may pick this plan today.+ */+ purchasable: boolean;/*** The tier.*/@@ -1169,7 +1173,8 @@ export type PlanCatalogResponse = {*/overage_limit_min_cents: number;/**- * Free and every purchasable paid plan, cheapest first.+ * Every plan, cheapest first. Clients read allowances from here rather+ * than hard-coding them; `purchasable` marks the plans a user can buy.*/plans: Array<PlanCatalogEntry>;};@@ -1476,19 +1481,19 @@ export type UsageSnapshot = {*/can_manage_billing: boolean;/**- * Shared prepaid credit balance.+ * Shared prepaid credit balance, in customer cents.*/credit_balance_cents: number;/**- * Shared payer credits already applied to this period.+ * Shared payer credits already applied to this period, in customer cents.*/credits_consumed_cents: number;/**- * Included AI for this user's seat this period, in list-rate cents.+ * Included AI for this user's seat this period, in cents at provider cost.*/included_cents: number;/**- * Shared overage charged so far this period.+ * Shared overage charged so far this period, in customer cents.*/overage_charged_cents: number;/**@@ -1496,7 +1501,7 @@ export type UsageSnapshot = {*/overage_enabled: boolean;/**- * Per-period overage cap.+ * Per-period overage cap, in customer cents.*/overage_limit_cents: number;/**@@ -1516,8 +1521,9 @@ export type UsageSnapshot = {*/period_start: string;/**- * This seat's remaining allowance plus shared credit/overage headroom; 0- * when blocked.+ * Cost cents of usage this seat may still consume: its remaining allowance+ * plus whatever shared credit and overage headroom pays for at the markup.+ * 0 when blocked.*/remaining_cents: number;/**@@ -1529,8 +1535,9 @@ export type UsageSnapshot = {*/tier: PlanTier;/**- * Team-wide usage beyond per-seat allowances that is not yet covered by- * shared credits or charges (awaiting settlement).+ * Team-wide usage beyond per-seat allowances, at the overage markup, that+ * is not yet covered by shared credits or charges (awaiting settlement).+ * Customer cents.*/uncovered_cents: number;/**@@ -1538,7 +1545,7 @@ export type UsageSnapshot = {*/unlimited: boolean;/**- * AI used by this user this period, in list-rate cents.+ * AI used by this user this period, in cents at provider cost.*/used_cents: number;};diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 236ff61c0c..96272ca8e4 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -6145,18 +6145,23 @@"required": ["tier","monthly_price_cents",- "included_ai_cents_per_seat"+ "included_ai_cents_per_seat",+ "purchasable"],"properties": {"included_ai_cents_per_seat": {"type": "integer","format": "int64",- "description": "Included AI per seat per period, list-rate cents."+ "description": "Included AI per seat per period, in cents at provider cost."},"monthly_price_cents": {"type": "integer","format": "int64",- "description": "Monthly list price per seat, cents."+ "description": "Monthly subscription price per seat, cents."+ },+ "purchasable": {+ "type": "boolean",+ "description": "Whether a new purchase or plan move may pick this plan today."},"tier": {"$ref": "#/components/schemas/PlanTier",@@ -6197,7 +6202,7 @@"items": {"$ref": "#/components/schemas/PlanCatalogEntry"},- "description": "Free and every purchasable paid plan, cheapest first."+ "description": "Every plan, cheapest first. Clients read allowances from here rather\nthan hard-coding them; `purchasable` marks the plans a user can buy."}}},@@ -6618,22 +6623,22 @@"credit_balance_cents": {"type": "integer","format": "int64",- "description": "Shared prepaid credit balance."+ "description": "Shared prepaid credit balance, in customer cents."},"credits_consumed_cents": {"type": "integer","format": "int64",- "description": "Shared payer credits already applied to this period."+ "description": "Shared payer credits already applied to this period, in customer cents."},"included_cents": {"type": "integer","format": "int64",- "description": "Included AI for this user's seat this period, in list-rate cents."+ "description": "Included AI for this user's seat this period, in cents at provider cost."},"overage_charged_cents": {"type": "integer","format": "int64",- "description": "Shared overage charged so far this period."+ "description": "Shared overage charged so far this period, in customer cents."},"overage_enabled": {"type": "boolean",@@ -6642,7 +6647,7 @@"overage_limit_cents": {"type": "integer","format": "int64",- "description": "Per-period overage cap."+ "description": "Per-period overage cap, in customer cents."},"overage_suspended": {"type": "boolean",@@ -6665,7 +6670,7 @@"remaining_cents": {"type": "integer","format": "int64",- "description": "This seat's remaining allowance plus shared credit/overage headroom; 0\nwhen blocked."+ "description": "Cost cents of usage this seat may still consume: its remaining allowance\nplus whatever shared credit and overage headroom pays for at the markup.\n0 when blocked."},"seats": {"type": "integer",@@ -6680,7 +6685,7 @@"uncovered_cents": {"type": "integer","format": "int64",- "description": "Team-wide usage beyond per-seat allowances that is not yet covered by\nshared credits or charges (awaiting settlement)."+ "description": "Team-wide usage beyond per-seat allowances, at the overage markup, that\nis not yet covered by shared credits or charges (awaiting settlement).\nCustomer cents."},"unlimited": {"type": "boolean",@@ -6689,7 +6694,7 @@"used_cents": {"type": "integer","format": "int64",- "description": "AI used by this user this period, in list-rate cents."+ "description": "AI used by this user this period, in cents at provider cost."}}},