Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
Provider roles + integration topology (spec slice 2)
Spec: .ai/specs/implemented/2026-09-23-spend-management-push-only-mode.md §1, §1b, §1c, §5
Research: .ai/research/spend-management-one-way-push.md
Branch: independent of slice 1; foundation for slices 3–5
What this slice is and is not
No behaviour change. Every gate this introduces resolves to exactly today's answer,
because no integration declares ownsLedgerFamilies until slice 4. That is the point:
the ~13-call-site signature change and the four hard-coded-list removals land as a
reviewable refactor, not buried under a feature.
Two facts established by reading the code, which this slice fixes:
- "Which integrations are accounting providers" is answered five different ways —
Object.values(ProviderID)in three sweeps,ACCOUNTING_SYNC_INTEGRATION_IDS(accounting.service.ts:2938), an inline["xero","quickbooks","rillet"](x+/accounting+/_layout.tsx:51), andcategory === "Accounting"(integrations.$id.tsx:647). Spend is.eq("id","ramp"). - There is no exclusivity mechanism at all. Nothing in
IntegrationConfigexpresses a domain or conflict, and the schema permits several active accounting integrations per company —getPeriodExternalGlSyncReadinessliterally loops over "at most three".
Progress
- Task 1: Migration —
integration.providerRole+ exclusivity trigger - Task 2: Regenerate database types
- Task 3: Declare
providerRoleon the descriptors - Task 4: Unify the capability surface
- Task 5: Build
IntegrationTopology+resolveIntegrationTopology - Task 6: Thread the topology through the settings resolvers
- Task 7: Replace the hard-coded provider-id lists — 3 of 4 done;
ACCOUNTING_SYNC_INTEGRATION_IDSdocumented as structurally blocked - Task 8: Block conflicting installs in the UI and the OAuth callbacks
- Task 9: Add the
no-integration-id-branchingconformance check - Task 10: Full-suite verification — gates green; browser spot-check pending
Dependencies
- Task 2 needs Task 1. Task 3 needs Task 2 (types).
- Task 5 needs Tasks 3 and 4.
- Tasks 6 and 7 both need Task 5; they are independent of each other and may run as parallel subagents.
- Task 8 needs Task 1 (the trigger) and Task 3.
- Task 9 needs Task 7 (otherwise its baseline is enormous).
Task 1: Migration — integration.providerRole + exclusivity trigger
Depends on: none Files:
- Create:
packages/database/supabase/migrations/<generated>_integration-provider-role.sql - Copy from (precedent):
packages/database/supabase/migrations/20260919152233_ramp-integration.sql(idempotentDO $$ … IF NOT EXISTSguards and the registryINSERT … ON CONFLICT)
Steps:
- Create the file with
pnpm db:migrate:new integration-provider-role. Never hand-pick the timestamp and never use000000for HHMMSS; never a timestamp older than the newest migration onmain. - Write exactly the SQL in the spec's Data Model section. Points that are not
negotiable:
integrationis a global registry (id+jsonschema), NOT a tenant table — nocompanyId, no composite PK, no new RLS policies. The standard table template does not apply here; do not add one.- The trigger fires
BEFORE INSERT OR UPDATE OF "active"and returns early whenNEW."active" IS NOT TRUEor whenTG_OP = 'UPDATE' AND OLD."active" IS TRUE, so a company already holding two active accounting integrations is not retroactively invalidated — it simply cannot activate a third. SECURITY DEFINER+SET search_path = public, raising withERRCODE = '23505'so callers can distinguish a conflict from a generic failure.- Guard every statement (
ADD COLUMN IF NOT EXISTS, thepg_constraintexistence check,DROP TRIGGER IF EXISTSbeforeCREATE TRIGGER) — the deploy runner retries a failed file over committed partial state.
- Backfill
providerRoleforxero/quickbooks/rillet→'accounting'andramp→'spend', each withWHERE "providerRole" IS DISTINCT FROM …so a re-run writes nothing. - Run the report query from the spec and record the result in the PR description. If any company already has two active integrations of one role, STOP and report — do not repair data in a migration.
- Apply with
pnpm db:migrate.
Verify:
pnpm db:migrate
# Expected: applies cleanly.
psql "$DATABASE_URL" -c "SELECT id, \"providerRole\" FROM integration WHERE \"providerRole\" IS NOT NULL ORDER BY id;"
# Expected: quickbooks|accounting, ramp|spend, rillet|accounting, xero|accounting
psql "$DATABASE_URL" -c "SELECT tgname FROM pg_trigger WHERE tgname = 'companyIntegration_single_active_role';"
# Expected: one row
pnpm db:check:datasets && pnpm db:check:backups
# Expected: both pass
Out of scope: any application code.
Task 2: Regenerate database types
Depends on: Task 1 Files:
- Modify:
packages/database/src/types.ts(generated — never hand-edited)
Steps:
pnpm run generate:types- Commit the regenerated file. Regenerating and committing types after a migration is normal and expected.
Verify:
git diff --stat packages/database/src/types.ts
# Expected: a non-empty diff adding providerRole to the integration Row/Insert/Update types
pnpm exec turbo run typecheck --filter=@carbon/database
# Expected: exit 0
Out of scope: everything else.
Task 3: Declare providerRole on the descriptors
Depends on: Task 2 Files:
- Modify:
packages/ee/src/types.ts— addproviderRole?: "accounting" | "spend"toIntegrationConfig(nearcategory, line ~167) - Modify:
packages/ee/src/{xero,quickbooks,rillet}/config.tsx— addproviderRole: "accounting" - Modify:
packages/ee/src/ramp/config.tsx— addproviderRole: "spend" - Modify:
packages/ee/src/index.ts— exportgetIntegrationsByRole(role): Integration[]besidegetIntegrationConfigById
Steps:
- Add the optional field with a doc comment saying it is the behavioural role, that
categoryremains a display string, and that integrations without a role (Slack, Jira, Linear, Onshape, Paperless Parts, Email, Stripe Connect) are unconstrained. - Declare it on the four descriptors. Do not touch
categoryon any of them. - Add the lookup to
index.ts:export const getIntegrationsByRole = (role: "accounting" | "spend") => integrations.filter((i) => i.providerRole === role); - Add a test asserting the TS registry and the DB registry agree — every descriptor
with a
providerRolemust match the value Task 1 backfilled. Put it inpackages/ee/src/__tests__/provider-role.test.ts, reading the expected pairs from a literal (the test cannot reach the database).
Verify:
pnpm --filter @carbon/ee test -- provider-role
# Expected: passes
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=erp
# Expected: exit 0
Out of scope: using providerRole anywhere yet.
Task 4: Unify the capability surface
Depends on: Task 2 Files:
- Create:
packages/ee/src/sync/capabilities.ts - Modify:
packages/ee/src/accounting/core/types.ts— re-exportSyncProviderCapabilitiesasProviderCapabilitiesfor compatibility - Modify:
packages/ee/src/accounting/providers/{rillet,quickbooks-online}/provider.ts— addrole: "accounting"to the existingcapabilitiesobjects - Copy from (precedent):
packages/ee/src/accounting/core/types.ts:87-107(the currentProviderCapabilitiesand its "absent = legacy REST provider" doc)
Steps:
- Write the discriminated union exactly as the spec's §1b defines it:
SharedCapabilities(transport,supportsWebhooks,externalAddressing,searchableCounterparts) plus therole: "accounting"arm (supportsJournalPush,maxJournalDimensionSlots) and therole: "spend"arm (ownsRemoteCodingSurface,ownsLedgerFamilies). - Export
resolveCapabilities(provider)returning a fully-defaulted object, sinceXeroProviderdeliberately declares nocapabilitiesat all (providers/xero/provider.ts:208-222). Documented defaults:role: "accounting",transport: "rest",supportsWebhooks: false,supportsJournalPush: true,externalAddressing: { account: "code" },searchableCounterparts: [],ownsLedgerFamilies: []. Every read goes through this function — neverprovider.capabilities?.xat a call site. - Do NOT add
externalAddressingvalues to any provider in this slice; the default is correct for Xero and Rillet, and QBO's{ account: "id" }is only consumed in slice 5. Leaving it absent keeps this slice behaviour-free. - Migrate the two existing declaration sites to add
role, and update the three existingprovider.capabilities?.maxJournalDimensionSlotsreads (integrations.$id.tsx:382,:414) toresolveCapabilities(provider)— being careful that Xero's cap continues to come fromXERO_MAX_JOURNAL_DIMENSION_SLOTSat line 436, which is deliberately offcapabilities.
Verify:
pnpm --filter @carbon/ee test
# Expected: all pass
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=erp
# Expected: exit 0
If any existing capabilities read cannot be routed through resolveCapabilities
without changing its result, STOP and report — do not improvise a default.
Out of scope: searchableCounterparts implementations (slice 1), spend
descriptors (slice 4).
Task 5: Build IntegrationTopology + resolveIntegrationTopology
Depends on: Tasks 3, 4 Files:
- Create:
packages/ee/src/sync/topology.ts - Create:
packages/ee/src/sync/topology.test.ts - Modify:
packages/ee/package.json— add the./syncexport subpath - Copy from (precedent):
apps/erp/app/modules/settings/settings.server.ts:154-256(getCompanyIntegrations— the Redis-cached, secret-stripped read this must ride)
Steps:
- Define
LedgerOwner,IdentityScope,IntegrationTopologyexactly as the spec's §1c gives them. resolveIntegrationTopology(client, companyId)reads the company's integration rows once, picks the single active row per role (the Task 1 trigger guarantees at most one), and resolves:accounting/spend— id plusresolveCapabilities.ledgerOwnership—{ kind: "carbon" }for everyPostingSourceFamilyunless the spend integration's capabilities list that family inownsLedgerFamilies. In this slice nothing declares it, so every family resolves tocarbonand behaviour is unchanged. Say so in a comment.identityScope(targetIntegrationId)—{ kind: "delegated", toIntegrationId }when the target is the spend integration AND its capabilities sayownsRemoteCodingSurface === falseAND an accounting integration exists;{ kind: "carbon" }otherwise. Same note: nothing sets it in this slice.PostingSourceFamilyis already exported frompackages/ee/src/accounting/core/models.ts— import it, do not redefine it.
- Tests: no integrations → both null, all families carbon; accounting only → carbon;
accounting + spend with
ownsRemoteCodingSurface: true→ carbon identity scope; a fixture spend capability withownsLedgerFamilies: ["ap"]→ ap external, ar carbon (this proves the mechanism ahead of slice 4 using it); the same fixture with["ar"]→ invoice side external, proving the rule is not AP-shaped. - It must issue no database query beyond the one integrations read. Do not add a second lookup for capabilities — those come from the TS registry.
Verify:
pnpm --filter @carbon/ee test -- topology
# Expected: all cases pass, including both fixture ownsLedgerFamilies cases
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Out of scope: calling it from anywhere.
Task 6: Thread the topology through the settings resolvers
Depends on: Task 5 Files:
- Modify:
packages/ee/src/accounting/core/service.ts—resolveSyncConfig - Modify:
packages/ee/src/accounting/core/models.ts—resolvePostingSyncSettings - Modify: every call site the compiler flags (expect ~13, across
packages/jobs/src/inngest/functions/integrations/*andapps/erp/app/routes/x+/settings+/integrations.$id.tsx) - Copy from (precedent): the exhaustive
Record<>onPOSTING_POLICY(core/models.ts:317) — the same "omission is a compile error" idiom
Steps:
Add a required second parameter
topology: IntegrationTopologyto both functions. Required, not optional — an optional parameter defeats the entire point, which is that the compiler finds every call site.Apply the derivation inside them, using
POSTING_POLICYto find what to suppress — never a hard-coded"bill":- for each family whose
ledgerOwnershipis external, setfamilies[family] = "none"; - collect the distinct
backingEntityTypeof everyPOSTING_POLICYentry whosefamilymatches, skippingnull, skipping entries whose family is"per-line", and skipping the"per-party"sentinel, and setentities[thatEntity].enabled = false; - clear the matching flag in
PostingSyncDocumentSyncFlagsfor each entity disabled (billEnabled,reimbursementEnabled,invoiceEnabled,creditMemoEnabled,vendorCreditEnabled). Both sentinel skips are load-bearing. Aper-linefamily (Payment) is shared between AR and AP and resolved per journal from its control-account lines; aper-partyfamily (Credit Memo/Debit Memo) is resolved per record from the memo's party (posting.ts:333-356). Disabling either wholesale would break the side that is still Carbon-owned.
ledgerOwnershipis keyed on thepostingSync.familieskeys — now FOUR:ar,ap,creditMemo,vendorCredit— not onPostingSourceFamily, whoseper-line/per-partymembers are resolution strategies rather than ownable families. This changed on the branch; readcore/models.tsfor the current shape rather than trusting this plan's memory of it.Note
POSTING_POLICY.Reimbursementis{ family: "ap", backingEntityType: "reimbursement" }, so an AP-delegated company correctly disables bothbillandreimbursementwith no special case. If your implementation needs one, it is wrong.- for each family whose
Fix every compile error by threading a topology through. Where a call site already has a
companyIdand a client, callresolveIntegrationTopology; where it processes a batch of companies, resolve once per company outside the loop, not per row.Note
isPaymentSyncbackEnabled(core/posting.ts:77) callsresolvePostingSyncSettingswith one argument — it is one of the call sites and it is per family, so an AP-external company keeps AR syncback working. Do not "simplify" it to a single boolean.Behaviour must be identical after this task. Add a test asserting that with a carbon-owned topology,
resolveSyncConfigandresolvePostingSyncSettingsreturn byte-identical results to the pre-change implementation for a representative stored metadata fixture.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp
# Expected: exit 0 — and it MUST have failed before every call site was updated.
pnpm --filter @carbon/ee test && pnpm --filter @carbon/jobs test
# Expected: all pass with no assertion changes
Out of scope: changing what any resolver returns for a carbon-owned company.
Task 7: Replace the hard-coded provider-id lists
2026-09-24 — PARTIAL. Two converted, one structurally blocked.
Done:
ramp-sweepnow sweeps every SPEND-role integration instead of.eq("id","ramp"), and the accounting layout readsgetIntegrationIdsByRole("accounting").
ACCOUNTING_SYNC_INTEGRATION_IDScannot be converted as this task assumed.accounting.service.tsis a*.service.ts, re-exported through the module barrel that client components import, so it is BROWSER-BUNDLED — and the@carbon/eebarrel reaches@carbon/auth, which validates the full server env at import time. Importing the registry there fails the build with "server-only module referenced by client". (The file separately already avoids@carbon/ee/accountingfor a TS2589 reason it documents.)The fix is for the caller to pass the ids in — the convention this module already uses for
syncFromDate— butgetPeriodExternalGlSyncReadiness's only caller isgetPeriodReadinessin the same file, so the signature change cascades. Fold it into Task 6, which is already threading a resolved object through this layer.The
isAccountingInstalled/producesSyncOperationshalf of this task still needs Task 5's topology and is untouched.
Depends on: Task 5 Files:
- Modify:
apps/erp/app/modules/accounting/accounting.service.ts:2936-2970— deleteACCOUNTING_SYNC_INTEGRATION_IDS - Modify:
apps/erp/app/routes/x+/accounting+/_layout.tsx:45-52— delete the inline["xero","quickbooks","rillet"] - Modify:
apps/erp/app/routes/x+/settings+/integrations.$id.tsx:647-656— replacecategory === "Accounting"and the|| integration.id === "ramp" - Modify:
packages/jobs/src/inngest/functions/integrations/ramp-sweep.ts:20-25— replace.eq("id", "ramp")
Steps:
- Everywhere a query filters
companyIntegrationby a list of accounting ids, build the list fromgetIntegrationsByRole("accounting").map(i => i.id). isAccountingInstalledbecomestopology.accounting !== null;producesSyncOperationsbecomestopology.accounting !== null || topology.spend !== null— which is the spec's "providerRole != null" rule and removes the"ramp"literal.ramp-sweepfilters.in("id", getIntegrationsByRole("spend").map(i => i.id)). Keep the function id and cron unchanged.- Leave
Object.values(ProviderID)in the three accounting sweeps alone for now —ProviderIDis a legitimate typed registry, not a hard-coded literal, and those sweeps construct provider instances keyed on it. Note this in the PR.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs
# Expected: exit 0
grep -rn '"xero", *"quickbooks"\|\[.*"quickbooks".*"rillet"' apps/erp/app packages/jobs/src
# Expected: no matches
grep -rn 'eq("id", *"ramp")' packages/jobs/src
# Expected: no matches
Out of scope: SECRET_KEYS, integrationErrors, the server-hooks registry, and
charge.integration defaults — all legitimately id-keyed.
Task 8: Block conflicting installs in the UI and the OAuth callbacks
Depends on: Tasks 1, 3 Files:
- Modify:
apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx— disable Install on a role conflict - Modify:
apps/erp/app/routes/x+/settings+/integrations.tsx— the loader supplies the active role map - Modify:
apps/erp/app/modules/settings/integration-errors.ts— add arole-conflictcode forxero,quickbooks,rillet,ramp - Modify:
apps/erp/app/routes/api+/integrations.{xero,quickbooks,ramp}.oauth.ts— catch the trigger's23505and redirect withrole-conflict - Copy from (precedent):
IntegrationCard.tsx:125-135(theisStarterPlanbranch — an already-present "disabled with explanatory copy" treatment) andintegration-errors.ts(the existing per-integration code map)
Steps:
- The integrations loader already calls
getIntegrationsWithHealth; deriveactiveRoles: Record<"accounting"|"spend", string | null>from it and return it. - In
IntegrationCard, whenintegration.providerRoleis set andactiveRoles[role]is a different id, disable Install and render copy naming the incumbent: "Uninstall {incumbent} first — only one {role} integration can be active at a time." Match theisStarterPlanvisual treatment. - In each OAuth callback, wrap the activating write and map a
23505toconnectionFailed("role-conflict", …)so the user gets the existing redirect-with- error UX rather than a 500. - Run
/translate— all new strings are user-facing.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
pnpm run lint
# Expected: exit 0
Browser-verify via /test: with Rillet active, the QuickBooks and Xero cards show
Install disabled with copy naming Rillet; the Ramp card is unaffected.
Out of scope: the mode picker (slice 4).
Task 9: Add the no-integration-id-branching conformance check
Depends on: Task 7 Files:
- Create:
packages/checks/src/conformance/no-integration-id-branching.ts - Create:
packages/checks/src/conformance/no-integration-id-branching.test.ts - Modify:
packages/checks/src/conformance/baseline.json - Copy from (precedent):
packages/checks/src/conformance/no-raw-rounding.ts— theConformanceCheckshape withid,description,provenance,scan(file, contents)
Steps:
- Flag a string literal equal to a registered integration id
(
"xero" | "quickbooks" | "rillet" | "ramp") used in an equality comparison (=== "ramp",!== "ramp") or inside an array/Setliteral. - Exclude by path:
packages/ee/src/<id>/**(a provider may name itself),packages/ee/src/index.ts,packages/ee/src/hooks.server.ts,packages/ee/src/integrations/secrets.ts,apps/erp/app/modules/settings/integration-errors.ts, andpackages/database/supabase/migrations/**. - Baseline the remaining current hits rather than fixing them in this slice — the rule exists to stop NEW branching. Record the baseline count in the PR description.
- Register the check wherever the other TypeScript-source checks are registered
(see
packages/checks/src/sources/typescript.ts).
Verify:
pnpm --filter @carbon/checks test -- no-integration-id-branching
# Expected: passes, including a fixture asserting `integrationId === "ramp"` in a jobs
# file is a violation and the same literal inside packages/ee/src/ramp/ is not
pnpm --filter @carbon/checks test
# Expected: all pass with the new baseline
Out of scope: clearing the baseline.
Task 10: Full-suite verification
2026-09-24 — automated gates GREEN.
typecheck(ee, jobs, erp, checks),pnpm run lint, andpnpm run test(31 tasks) all pass. The migration and trigger were verified directly against the live schema in a rolled-back transaction: a second spend install is refused namingramp, a second accounting install refused namingrillet, a different role allowed alongside, an inactive row allowed.Step 2's browser spot-check has NOT been run. The no-behaviour-change claim rests on typecheck plus the fact that nothing declares
ownsLedgerFamilies, so every family resolves carbon-owned — but nobody has watched a purchase invoice post and confirmed the Bill still pushes and its journal still records DOC_BACKED rather than FAMILY_OFF. That needs an accounting provider connected; onlyrampis installed on the dev company.Deviation worth knowing: Task 6 shipped as a BRANDED TYPE on the policy decision, not the planned required argument on the parsers. Only two production sites reach
getJournalPostingPolicyDecision; most of the 21 parser call sites are syncers with no way to obtain a topology. See the commit message.
Depends on: Tasks 1–9 Files: none
Steps:
- Run the gates below.
- Confirm the no-behaviour-change property: with only an accounting integration
installed, sync behaviour is identical to
main— spot-check by posting a purchase invoice and confirming the Bill still pushes and the AP journal is stillDOC_BACKED, notFAMILY_OFF.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp --filter=@carbon/checks
# Expected: exit 0
pnpm run lint
# Expected: exit 0
pnpm run test
# Expected: all pass
pnpm db:check:datasets && pnpm db:check:backups
# Expected: both pass
Out of scope: install modes, scopes, identity resolution, GR/IR, item receipts — slices 3–5.