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.
Master data correctness — counterpart ladder + sweep (spec slice 1)
Spec: .ai/specs/implemented/2026-09-23-spend-management-push-only-mode.md §8
Research: .ai/research/spend-management-one-way-push.md
Branch: independent of push-only; ships alone
Why this is independent
This fixes a pre-existing correctness gap that exists today for every Rillet, Xero and QuickBooks customer, with no dependency on push-only mode or on the Ramp sandbox gates. Two facts established by reading the code:
- Master data has no correctness sweep.
accounting-outbound-sweep(cron15,45) pages onlyjournal,purchaseInvoice,salesInvoice,payment,charge. The weeklyaccounting-reconciliationis posting-sync only. So a supplier/customer/item reaches the provider ONLY via a row event or a JIT document dependency — a record predating the install, or one whose event was dropped, is never pushed and nothing catches up. - Rillet is the only provider that creates without looking first.
providers/xero/entities/contact.ts:635("Smart match: if no mapping exists, search Xero by name before creating") andproviders/quickbooks-online/entities/vendor.ts:346-347(findRemoteVendorByName) both match.RilletVendorSyncer.upsertRemote/RilletCustomerSyncerdo not — their header says so explicitly. So adding a sweep without fixing this would mint a duplicate Rillet vendor for every supplier a human already created there.
Task order is therefore load-bearing: the ladder (Tasks 1–5) must land before the sweep (Task 6).
Progress
- Task 1: Add counterpart types + the
searchableCounterpartscapability - Task 2: Write the pure resolution ladder + unit tests
- Task 3: Implement
findRemoteCandidatesfor Rillet vendor + customer - Task 4: Route the Rillet push path through the ladder
- Task 5: Migrate Xero and QuickBooks onto the shared ladder — done 2026-09-24 (the recorded blocker did not survive re-reading; see below)
- Task 6: Add master data to the outbound sweep
- Task 7: Unify the two one-shot jobs into
accounting-master-sync— done 2026-09-24 via option (b) - Task 8: Expose the import action on every accounting provider — done 2026-09-24
- [~] Task 9: Full-suite verification — gates green; browser step BLOCKED (local DB down)
Dependencies
- Task 2 needs Task 1 (types).
- Tasks 3 and 5 both need Task 2. Tasks 3+4 and Task 5 are independent of each other — may run as parallel subagents.
- Task 6 needs Task 4 (ladder live for Rillet) — see "Why this is independent".
- Task 7 is independent of Tasks 1–6; Task 8 needs Task 7.
- Task 9 needs everything.
Task 1: Add counterpart types + the searchableCounterparts capability
Depends on: none Files:
- Create:
packages/ee/src/accounting/core/counterpart-types.ts - Modify:
packages/ee/src/accounting/core/types.ts— addsearchableCounterpartstoProviderCapabilities; add the optionalfindRemoteCandidatesmethod toBaseProvider - Copy from (precedent):
packages/ee/src/accounting/core/types.ts:157-181(SupportsIncrementalPull+providerSupportsIncrementalPull— the established optional-capability + type-guard pattern)
Steps:
- In the new
counterpart-types.ts, export:export type ExternalIdentityKind = "account" | "vendor" | "customer" | "item"; export type CounterpartSearchKeys = { name?: string | null; taxId?: string | null; email?: string | null; /** The provider-side reference Carbon stamps on records it created. */ carbonReference?: string | null; }; export type RemoteCandidate = { remoteId: string; name?: string | null; taxId?: string | null; email?: string | null; carbonReference?: string | null; }; - In
types.ts, add toProviderCapabilities:/** * Entity kinds this provider can search for an existing counterpart before * creating one. Absent or empty = always create (the pre-2026-09 Rillet * behaviour), so the capability is opt-in and nothing regresses by default. */ searchableCounterparts?: ExternalIdentityKind[]; - In
types.ts, add toBaseProvider(optional method, mirroringjournalDimensionTargets?()at line 201):findRemoteCandidates?( kind: ExternalIdentityKind, keys: CounterpartSearchKeys ): Promise<RemoteCandidate[]>; - Export a type guard beside it, mirroring
providerSupportsIncrementalPull:
Both conditions are required:export function providerSupportsCounterpartSearch<T extends BaseProvider>( provider: T, kind: ExternalIdentityKind ): provider is T & Required<Pick<BaseProvider, "findRemoteCandidates">> { return ( typeof provider.findRemoteCandidates === "function" && (provider.capabilities?.searchableCounterparts ?? []).includes(kind) ); }XeroProviderdeliberately declares nocapabilitiesat all (providers/xero/provider.ts:208-222), so the?? []default must read as "no search" rather than throwing. - Re-export the new types from
packages/ee/src/accounting/index.ts.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0, no errors. Adding an optional field and an optional method
# must not break any existing provider.
Out of scope: implementing findRemoteCandidates on any provider; touching
upsertRemote anywhere.
Task 2: Write the pure resolution ladder + unit tests
Depends on: Task 1 Files:
- Create:
packages/ee/src/accounting/core/counterpart.ts - Create:
packages/ee/src/accounting/core/counterpart.test.ts - Copy from (precedent):
packages/ee/src/ramp/lib/spend.ts:214-250(resolveOrCreateRampSpendVendor— the existing ladder, including the ambiguity rule at lines 180-195)
Steps:
- Export a PURE function that decides, given already-fetched candidates:
Ladder order, each rung matched case-insensitively on a trimmed non-empty value:export type CounterpartDecision = | { action: "link"; remoteId: string; via: "carbonReference" | "taxId" | "email" | "name" } | { action: "create"; reason: "no-candidates" | "ambiguous" }; export function decideCounterpart( keys: CounterpartSearchKeys, candidates: readonly RemoteCandidate[] ): CounterpartDecision;carbonReference→taxId→email→name. The FIRST rung with exactly one match wins. A rung with two or more matches does not fall through to a weaker rung — it returns{ action: "create", reason: "ambiguous" }immediately. - Rationale to put in the file header, verbatim from the spec: ambiguity creates and never guesses, because a duplicate is recoverable by merging while a wrong link silently posts one company's bills against another company's vendor.
- Export the impure orchestrator, which does the I/O:
It returnsexport async function resolveOrCreateRemoteCounterpart(args: { provider: BaseProvider; kind: ExternalIdentityKind; keys: CounterpartSearchKeys; existingRemoteId: string | null; }): Promise<{ remoteId: string | null; decision: CounterpartDecision | null }>;{ remoteId: existingRemoteId, decision: null }immediately whenexistingRemoteIdis set; returns{ remoteId: null, decision: {action:"create"} }whenproviderSupportsCounterpartSearchis false; otherwise callsfindRemoteCandidatesand runsdecideCounterpart. It NEVER creates — the caller owns creation. - Write
counterpart.test.tscovering, at minimum: no candidates → create; one name match → link via name; two name matches → create/ambiguous; ataxIdmatch beating a conflicting singlenamematch; twotaxIdmatches → create/ambiguous without falling through to name; acarbonReferencematch winning over everything; empty and whitespace-only keys ignored on every rung; case-insensitive name matching. Use optional chaining on indexed access (candidates[0]?.remoteId) —noUncheckedIndexedAccessis on.
Verify:
pnpm --filter @carbon/ee test -- counterpart
# Expected: all counterpart tests pass, including the two ambiguity cases.
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Out of scope: calling this from any syncer.
Task 3: Implement findRemoteCandidates for Rillet vendor + customer
Depends on: Task 2 Files:
- Modify:
packages/ee/src/accounting/providers/rillet/provider.ts— addfindRemoteCandidatesand declaresearchableCounterparts: ["vendor", "customer"]oncapabilities(lines 375-382) - Copy from (precedent):
packages/ee/src/accounting/providers/rillet/provider.tslistVendors/listCustomersas used bypackages/jobs/src/inngest/functions/integrations/rillet-import-contacts.ts:134-138
Steps:
- Add
searchableCounterparts: ["vendor", "customer"]to the existingreadonly capabilities: ProviderCapabilitiesobject. - Implement
findRemoteCandidates(kind, keys):kind === "vendor"→listVendors();kind === "customer"→listCustomers(); anything else →return [].- Map each remote row to a
RemoteCandidate, reading its Carbon reference through the existingreadCarbonExternalReferencehelper (providers/rillet/entities/shared.ts) so thecarbonReferencerung works. - Cache the drained list per
(kind)on the provider instance for the lifetime of one sync run, the same wayrillet-import-contacts.ts:109caches instead of re-scanning per batch.
- If
listCustomers/listVendorsdo not exist with those exact names, STOP and report — do not invent an endpoint. The lesson at.ai/lessons.md("Rillet AP payment pull assumed an org-wideGET /bill-payments") is precisely this failure.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
pnpm --filter @carbon/ee test -- rillet
# Expected: existing Rillet tests still pass (no behaviour change yet — the
# capability is declared but nothing calls it until Task 4).
Out of scope: changing upsertRemote.
Task 4: Route the Rillet push path through the ladder
Depends on: Task 3 Files:
- Modify:
packages/ee/src/accounting/providers/rillet/entities/vendor.ts—upsertRemote(around line 533) - Modify:
packages/ee/src/accounting/providers/rillet/entities/customer.ts— the equivalentupsertRemote - Modify: both files' class-header comments, which currently state "no name-matching lookup before create" — that statement becomes false
- Copy from (precedent):
packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.ts:344-355(theexistingRemoteId ??= matchthen create-or-update shape)
Steps:
- In
upsertRemote, afterconst existingRemoteId = await this.getRemoteId(localId)and before the create branch, callresolveOrCreateRemoteCounterpartwithkind: "vendor"(or"customer"),existingRemoteId, andkeysbuilt from the mapped write payload:name,taxIdandemailif the payload carries them,carbonReference: carbonExternalReference(localId). - When it returns a
remoteId, take the update branch (PUT the existing record) and write the mapping row via the syncer's existinglinkEntitiespath, exactly as an update would. When it returns null, keep today's create-with-idempotency-key path unchanged. - Update both header comments to describe the ladder and cite
core/counterpart.ts. - Do NOT remove the
carbonexternal reference or the createIdempotency-Key— they remain the guards against Carbon double-creating, which the ladder does not replace.
Verify:
pnpm --filter @carbon/ee test -- rillet
# Expected: all existing Rillet vendor/customer tests pass.
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Then add one regression test in
packages/ee/src/accounting/providers/rillet/entities/__tests__/ asserting that a
supplier with no mapping, where findRemoteCandidates returns one same-named vendor,
results in an UPDATE and a mapping row — not a create.
Out of scope: Xero, QuickBooks, the sweep.
Task 5: Migrate Xero and QuickBooks onto the shared ladder
UNBLOCKED and done 2026-09-24. No shared-interface change was needed.
The recorded blocker rested on a false premise. It claimed QBO's
findRemoteVendorByNamecached the matched entity'sSyncTokenso the follow-up update could skip a GET, and that the resolver therefore had to return the matchedRemoteCandidatewith an opaquerawpayload. Re-reading the code:
updateWithSyncTokenRetrycallsfetchCurrent()unconditionally before it updates. The name-match's cached SyncToken was never used to avoid a GET.rememberRemoteEntity(match)is overwritten byrememberRemoteEntity(created)orrememberRemoteEntity(updated)a few lines later on every path throughupsertRemote. Its only surviving effect — seedinglinkEntities'remoteUpdatedAt— is re-supplied by the write's own response.So the cache was dead weight, and
{ remoteId, decision }is sufficient.RemoteCandidategained norawfield, and the resolver is unchanged.Deliberate behaviour changes, both toward the ladder's doctrine:
- Ambiguity creates instead of taking
[0]. Unreachable for QBO (DisplayNameis unique) and for Xero among ACTIVE contacts. If an archived Xero twin ever makes it reachable, the create surfaces as Xero's own duplicate-name refusal — a visible Failed op — rather than a silent link to the archived record.- A failed search now throws instead of reading as "no match". Xero's
findRemoteContactByNameswallowed the error and returned null, so a transient 500 created a duplicate contact permanently. QBO and Rillet already failed closed; Xero now matches them. The operation parks and retries instead.Two things found and fixed along the way, neither in the original plan:
- Xero's batch path bypassed name matching entirely.
upsertRemoteBatchconsulted the mapping row only, so the very backfill this matching exists for created duplicates whenever it ran batched. Both paths now route through one privateresolveExistingContact.escapeQboQueryValuehad to move. It lived inentities/shared.ts, which imports../provider— so the provider could not import it. Extracted to the leafquickbooks-online/query.tsand re-exported fromshared.ts, the same shape as the Rilletreferences.tsextraction.On Xero's capabilities object: declaring one opts OUT of every default, so an omitted field asserts the default rather than "unknown".
maxJournalDimensionSlotstherefore had to be declared (omitted, it means "no cap", which is false for Xero); it references the existingXERO_MAX_JOURNAL_DIMENSION_SLOTSconstant rather than repeating the literal. Three doc comments acrosscore/types.ts,sync/capabilities.tsandcounterpart-types.tscited Xero as the capability-less provider and are now updated.Keys passed:
nameonly, for both providers. Unlike Rillet — which has no search endpoint and so lists the org, making every rung live — Xero and QBO query by name, which bounds the candidate set to one name. An email or tax-id rung over a name-bounded set can only re-confirm the same record or find nothing, so passing those keys would change the reported rung and nothing else. Widening the ladder for these two means widening the query; that is a real behaviour change and was left out of scope.Gates:
@carbon/ee+@carbon/jobs+erptypecheck,pnpm run lint(37/37),pnpm run test(31/31, 1654 ee tests). New HTTP-boundary tests stubfetchonly and pin both providers' query shape, escaping, error behaviour and no-op cases — the same class of bug as the Rilletemails[]shape mismatch this slice already hit.Not verified in a browser — same blocker as the rest of slice 1: no accounting provider is connected to the local dev company.
Depends on: Task 2 Files:
- Modify:
packages/ee/src/accounting/providers/rillet/provider.ts— addfindRemoteCandidatesand declaresearchableCounterparts: ["vendor", "customer"]oncapabilities(lines 375-382) - Copy from (precedent):
packages/ee/src/accounting/providers/rillet/provider.tslistVendors/listCustomersas used bypackages/jobs/src/inngest/functions/integrations/rillet-import-contacts.ts:134-138
Steps:
- Add
searchableCounterparts: ["vendor", "customer"]to the existingreadonly capabilities: ProviderCapabilitiesobject. - Implement
findRemoteCandidates(kind, keys):kind === "vendor"→listVendors();kind === "customer"→listCustomers(); anything else →return [].- Map each remote row to a
RemoteCandidate, reading its Carbon reference through the existingreadCarbonExternalReferencehelper (providers/rillet/entities/shared.ts) so thecarbonReferencerung works. - Cache the drained list per
(kind)on the provider instance for the lifetime of one sync run, the same wayrillet-import-contacts.ts:109caches instead of re-scanning per batch.
- If
listCustomers/listVendorsdo not exist with those exact names, STOP and report — do not invent an endpoint. The lesson at.ai/lessons.md("Rillet AP payment pull assumed an org-wideGET /bill-payments") is precisely this failure.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
pnpm --filter @carbon/ee test -- rillet
# Expected: existing Rillet tests still pass (no behaviour change yet — the
# capability is declared but nothing calls it until Task 4).
Out of scope: changing upsertRemote.
Task 4: Route the Rillet push path through the ladder
Depends on: Task 3 Files:
- Modify:
packages/ee/src/accounting/providers/rillet/entities/vendor.ts—upsertRemote(around line 533) - Modify:
packages/ee/src/accounting/providers/rillet/entities/customer.ts— the equivalentupsertRemote - Modify: both files' class-header comments, which currently state "no name-matching lookup before create" — that statement becomes false
- Copy from (precedent):
packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.ts:344-355(theexistingRemoteId ??= matchthen create-or-update shape)
Steps:
- In
upsertRemote, afterconst existingRemoteId = await this.getRemoteId(localId)and before the create branch, callresolveOrCreateRemoteCounterpartwithkind: "vendor"(or"customer"),existingRemoteId, andkeysbuilt from the mapped write payload:name,taxIdandemailif the payload carries them,carbonReference: carbonExternalReference(localId). - When it returns a
remoteId, take the update branch (PUT the existing record) and write the mapping row via the syncer's existinglinkEntitiespath, exactly as an update would. When it returns null, keep today's create-with-idempotency-key path unchanged. - Update both header comments to describe the ladder and cite
core/counterpart.ts. - Do NOT remove the
carbonexternal reference or the createIdempotency-Key— they remain the guards against Carbon double-creating, which the ladder does not replace.
Verify:
pnpm --filter @carbon/ee test -- rillet
# Expected: all existing Rillet vendor/customer tests pass.
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Then add one regression test in
packages/ee/src/accounting/providers/rillet/entities/__tests__/ asserting that a
supplier with no mapping, where findRemoteCandidates returns one same-named vendor,
results in an UPDATE and a mapping row — not a create.
Out of scope: Xero, QuickBooks, the sweep.
Task 5: Migrate Xero and QuickBooks onto the shared ladder
BLOCKED 2026-09-24 — the shared interface cannot express what QBO needs.
Two findings from reading the code before writing any:
- The ambiguity change is a non-event. Both providers take the FIRST match (
Contacts[0],matches[0]) with no ambiguity check, so the ladder's "ambiguity creates" rule IS a behaviour change on paper — but Xero enforces unique active contact names and QBO enforces uniqueDisplayName, so it is unreachable in practice. Passing only thenamekey would reduce the ladder to exactly today's behaviour plus an unreachable guard. Safe.findRemoteCandidatesreturning ids loses QBO's entity cache. ItsfindRemoteVendorByNamecallsthis.rememberRemoteEntity(match), caching the full matched entity so the follow-up update has itsSyncTokenwithout another GET.resolveOrCreateRemoteCounterpartreturns aremoteIdonly, so adopting it as written would add a GET per matched vendor AND could reintroduce the sync-token retry pathupdateWithSyncTokenRetryexists to avoid.The fix is a shared-interface change, not a call-site workaround: the resolver should return the matched
RemoteCandidate, andRemoteCandidateshould carry an optional opaquerawpayload the provider can hand back to itself. That is a deliberate design decision affecting every provider, so it is not something to improvise unattended on two live providers this customer does not use.Xero's capabilities object is NOT the blocker (verified): only two
.capabilitiesreads exist repo-wide, both?.maxJournalDimensionSlots ?? null, and neither is Xero's path (it readsXERO_MAX_JOURNAL_DIMENSION_SLOTSdirectly).supportsWebhooks/supportsJournalPushhave no read sites at all. So declaring a capabilities object on Xero withtransport: "rest"andmaxJournalDimensionSlotsleft absent changes nothing observable. Note the original step 3 below asked to "keep every currently-absent field absent", which is impossible — those three fields are required byProviderCapabilities.Nothing regresses while this is blocked: Rillet now uses the ladder, Xero and QBO keep their own name matching, and Task 6's sweep is safe for all three.
Depends on: Task 2 Files:
- Modify:
packages/ee/src/accounting/providers/xero/entities/contact.ts:633-639— replace the inlinefindRemoteContactByNamecall - Modify:
packages/ee/src/accounting/providers/quickbooks-online/entities/vendor.ts:344-348and the customer equivalent — replace the inlinefindRemoteVendorByNamecall - Modify: both providers'
capabilitiesto declaresearchableCounterparts(QBO atproviders/quickbooks-online/provider.ts:368-374; Xero declares nocapabilitiesobject at all — add one, keeping every currently-absent field absent so the documented "absent = legacy REST provider" default is preserved, per the comment atproviders/xero/provider.ts:208-222)
Steps:
- Move each provider's existing private name-lookup into
findRemoteCandidates, returning candidates rather than a single id. Preserve each provider's current query exactly — Xero's contact-name search and QBO'sDisplayName = '<escaped>'query, includingescapeQboQueryValue. - Replace the inline call in
upsertRemotewithresolveOrCreateRemoteCounterpart. - Behaviour must be identical. Xero's existing comment asserts "Xero enforces unique contact names across all active contacts", so its ambiguity case cannot fire in practice; QBO's query is an equality match. If either provider's existing lookup silently took the first of several matches, the ladder will now CREATE instead — that is the intended fix, but note it in the PR description rather than hiding it.
- Xero's
ContactSyncerbacks bothcustomerandvendor(it reads both mapping types atcontact.ts:48-66) — declare both kinds and pass the syncer's ownentityTypeaskind.
Verify:
pnpm --filter @carbon/ee test -- xero
# Expected: all existing Xero contact tests pass unchanged.
pnpm --filter @carbon/ee test -- quickbooks
# Expected: all existing QBO vendor/customer tests pass unchanged.
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Out of scope: changing what either provider searches by. This task is a refactor onto shared code, not a behaviour change.
Task 6: Add master data to the outbound sweep
Depends on: Task 4 Files:
- Modify:
packages/jobs/src/inngest/functions/integrations/accounting-outbound-sweep.ts— add master-data pages alongside the existing document pages (lines ~212-358) - Copy from (precedent): the
purchaseInvoicepage block ataccounting-outbound-sweep.ts:238-252(config gate →pageIds→ map toReconcileRef[]→skippedReasons.pushon the else branch)
Steps:
- For each of
customer→suppliertable,vendor→suppliertable,item→itemtable, gated by the existingprovider.getSyncConfig(entityType)?.enabled && direction !== "pull-from-accounting"(the same predicateisEntityPushEnableduses), build the candidate set as the UNION of two bounded queries:- unmapped —
mappingService.getUnsyncedEntityIds(entityType, tableName, integration, limit), which already exists (core/external-mapping.ts:301). This set drains to zero and stays there. - changed since cursor — the existing
pageIdskeyset onupdatedAt.
- unmapped —
- Cap each per run:
MASTER_DATA_PAGE_SIZE = 200forcustomer/vendor,MASTER_DATA_ITEM_PAGE_SIZE = 500foritem. - Gate
itemto run only on the:15invocation (new Date().getUTCMinutes() < 30) so a six-figure item master is swept twice an hour at most, not four times. Add a comment saying why. reconcileMasterDataalready short-circuits a mapped-and-unchanged record ("unchanged since the last successful sync",reconcile.ts:485-492), so steady state enqueues nothing. Do not add a second freshness check.- Note
customerandvendorboth read the tablescustomerandsupplierrespectively — checksync-tables.tsTABLE_TO_ENTITY_MAPfor the authoritative table→entity mapping rather than assuming.
Verify:
pnpm --filter @carbon/jobs test -- outbound-sweep
# Expected: existing sweep tests pass; new tests assert that (a) an unmapped supplier
# is enqueued, (b) a mapped-and-unchanged supplier is not, (c) `item` is skipped on
# the :45 invocation.
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exit 0
Out of scope: changing reconcileMasterData; adding deletes.
Task 7: Unify the two one-shot jobs into accounting-master-sync
DONE 2026-09-24 — took option (b), and the split turned out bigger than either option described.
The stop condition was right that
accounting-backfillis not a master-data job. Reading it fully found two more things:
- Its two PULL phases were unreachable. They gated on the entity's configured
directionviashouldPull, and every provider'sbuild*SyncConfigforcescustomer/vendor/itemtopush-to-accounting/owner: "carbon". SoshouldPullwas always false — ~320 lines that could never run. That is also exactly WHYrillet-import-contactshad to exist: it enqueuespull-from-accountingoperations explicitly, overriding the direction.- The three push phases were copy-pasted per entity type, ~135 lines each differing only in the entity name and its table.
What shipped
accounting-journal-backfill.ts— phase 0 extracted verbatim as its own provider-agnostic job. It had only ever been reachable by clicking Xero's "Run Initial Sync" button, so on QBO and Rillet journal-disposition repair beyond the sweep's 7-day window did not exist at all.accounting-master-sync.ts— one job,directionas a payload field, one loop over entity types instead of three copies. Net ~1400 lines deleted.provider.listRemoteEntityIds(kind)+capabilities.importableEntities, withproviderSupportsMasterDataImportrequiring both — the same both-conditions rule as the counterpart ladder. This is what keeps the job free of provider branching, per the "neverif (rillet) else if (quickbooks)" constraint. Implemented on all three: Rillet reuses its memoized org lists, QBO runs an unfilteredSELECT, Xero pages/Contacts.MASTER_DATA_TABLESextracted inmaster-data-targets.tsso thevendor→supplierpairing has one definition shared with Task 6's sweep.Judgement calls worth reviewing
- Xero's enumeration does NOT reuse
listContacts. That method's filter isIsCustomer==true OR IsSupplier==true, so importing "customers" through it would have created Carbon customers out of supplier-only contacts.listRemoteEntityIdspages each kind separately. A contact that is genuinely both appears under both, which is correct — the mapping row is keyed by entity type.- A
withRateLimitRetryhelper was deleted, not carried over. It awaitedstep.sleepfrom INSIDE astep.run— a nested-step violation. ARatelimitErrornow propagates so Inngest retries with backoff, which is what the pull path already did.XeroProvider.listContacts/listItemsdeleted along with their four option/response interfaces: the dead pull phases were their only callers.- PULL ignores the configured direction; PUSH respects it. Asking to import is deliberately overriding the automatic direction; asking to push is asking the automatic direction to catch up, so a pull-only entity stays pull-only.
- A kind a provider cannot enumerate reports
notAttemptedwith a reason rather than importing nothing and returning success.Task 8 shipped with it. Two provider-agnostic routes (
integrations.master-sync.ts,integrations.journal-backfill.ts) replace the two per-provider ones. Parameters ride the QUERY STRING becauseIntegrationActionButtonPOSTsaction.endpointwith no body — worth knowing before designing any future action. All three accounting descriptors now declare the same TWO actions: Import customers & vendors, Push customers/vendors/items.A third action, Backfill journal postings, was added and then REMOVED the next day on Brad's challenge: it enqueues a push for every journal posted since
postingSync.syncFromDate, so a fresh connection whose account mapping is not yet complete would park a wall ofUNMAPPED_ACCOUNTSwarnings — every one retryable, but it reads as broken. The job and its route survive; only the button is gone. Re-add it behind agetAccountsBlockingSyncgate if it is ever wanted in the UI.Xero's existing "Entities to Sync" switches still drive its push selection; the other two fall through to all-three defaults. No
/translaterun — these descriptor strings are plain (the existing Rillet action was too), not Lingui macros.Docs synced:
.claude/rules/accounting-sync-handlers.md(job table + the section, retitled from "Rillet contact import"),packages/ee/AGENTS.md, and two stale code comments in the Rillet provider/customer syncer.Gates: ee + jobs + lib + erp + checks typecheck,
pnpm run lint(37/37),pnpm run test(31/31). Newfetch-boundary tests pin Xero's per-kind filters, its paging and its throw-on-partial-page, and QBO's unfiltered select.Not verified in a browser — no accounting provider is connected locally, so no button has been clicked. This is the largest untested surface in the slice: three new actions on three providers, and two jobs that replaced working ones.
Depends on: none (independent of Tasks 1–6) Files:
- Create:
packages/jobs/src/inngest/functions/integrations/accounting-master-sync.ts - Modify:
packages/jobs/src/inngest/index.ts— register it - Modify:
packages/lib/src/trigger.tsandpackages/lib/src/events.ts— addaccounting-master-sync→carbon/accounting-master-sync - Delete:
packages/jobs/src/inngest/functions/integrations/accounting-backfill.tsandrillet-import-contacts.tsonly after Task 8 repoints their routes - Copy from (precedent):
rillet-import-contacts.ts— itsenqueueSyncOperations+drainSyncOperationsshape is the more complete of the two
Steps:
- Payload:
{ companyId, provider: ProviderID, entityTypes: AccountingEntityType[], direction: "push-to-accounting" | "pull-from-accounting", batchSize }. - For
pull-from-accounting, reproducerillet-import-contacts's behaviour exactly: list the remote records, enqueue explicit pull operations, drain them. Forpush-to-accounting, reproduceaccounting-backfill's customers/vendors/items behaviour. - Keep the per-company concurrency key both jobs use today.
- If
accounting-backfillturns out to do anything beyond customers/vendors/items (it also haspullIntegration/pushIntegrationphases at lines 397, 577, 718, 855, 988), STOP and report — its scope may exceed master data and this task would then need to keep it and only absorb the contact import.
Verify:
pnpm --filter @carbon/jobs test -- master-sync
# Expected: new tests pass for both directions.
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exit 0
Out of scope: deleting the old jobs before Task 8 lands.
Task 8: Expose the import action on every accounting provider
Depends on: Task 7 Files:
- Create:
apps/erp/app/routes/api+/integrations.master-sync.ts— one route, provider-agnostic, replacingintegrations.rillet.import-contacts.tsandintegrations.xero.backfill.ts - Modify:
packages/ee/src/rillet/config.tsx:91-99— repoint the existingactionsentry - Modify:
packages/ee/src/xero/config.tsxandpackages/ee/src/quickbooks/config.tsx— add the sameactionsentry - Copy from (precedent):
packages/ee/src/rillet/config.tsx:91-99(theIntegrationActionshape) andapps/erp/app/routes/api+/integrations.rillet.import-contacts.ts(the route)
Steps:
- The route reads the integration id from the request body, resolves the provider via
the existing
Object.values(ProviderID)membership check (integrations.$id.tsx:343-348is the precedent), callsrequirePermissions(request, { update: "settings" }), and firestrigger("accounting-master-sync", { ... }). - Declare the action on all three accounting descriptors with
label: "Import customers & vendors"andendpoint: "/api/integrations/master-sync". - Delete the two old routes and the two old jobs once this is green.
- Run
/translate—label/descriptionare user-facing strings.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
pnpm run lint
# Expected: exit 0
Out of scope: UI beyond the existing action button (IntegrationForm already
renders actions).
Task 9: Full-suite verification
2026-09-24 — automated gates GREEN, browser verification BLOCKED.
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp,pnpm run lintandpnpm run test(31 tasks, all packages) all pass.Step 2's browser verification did NOT run: the local database is not up this session (
pg_isreadyfails onPORT_DB=49921; only thecarbon-rediscontainer is running), so there is no stack to drive and no Rillet integration to exercise. This is unproven, not disproven — the ladder's decision logic is unit-tested and the sweep's table pairing is pinned, but nothing has observed a real Carbon supplier linking to a real same-named Rillet vendor. Run it before merge:
crbn up, connect Rillet.- Create a supplier whose name matches an existing Rillet vendor; confirm ONE Rillet vendor and one mapping row, not two vendors.
- Run the import action twice; confirm no duplicate suppliers.
- Confirm the master-data sweep enqueues a pre-existing unmapped supplier.
Depends on: Tasks 1–8 Files: none
Steps:
- Run the gates below.
- Browser-verify via
/test: with a Rillet integration connected, create a supplier whose name matches an existing Rillet vendor, confirm it LINKS (one Rillet vendor, one mapping row) rather than duplicating; then run the import action twice and confirm no duplicate suppliers.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp
# Expected: exit 0
pnpm run lint
# Expected: exit 0
pnpm run test
# Expected: all pass
Out of scope: anything in spec §§1-7, 9-10 — those are slice 2 and later.