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.
Commercial Gating Refactor — overnight autonomous run
Branch: move-permissions-to-ee · Started: 2026-09-20 · Owner: [email protected]
This file is the LEDGER. It survives context resets — read it first, then continue
from the STATUS table. The pattern spec is .claude/rules/commercial-licensing.md.
Goal
Refactor every plan-gated commercial feature to the tamper-resistant pattern:
- Feature body lives in
packages/ee(using it requires running commercial code). requireEntitlement(client, companyId, FEATURE)embedded INSIDE the ee authoring functions (stripping the gate requires editing commercial code).- Client UX: visible + upgrade overlay, never hidden. Route loaders DON'T
requireFeature-redirect the primary page; write routes/actions keep it. - Gate helper:
companyHasFeature/requireFeature(community-blocked) — NOTcompanyHasPlan/requirePlan(Cloud-only no-op).
Per-feature refactor strategy (the loop)
For each feature, one focused subagent does:
- Confirm/add the
FEATURE_PLANSkey. - If the engine is in an app module /
packages/jobs, relocate it topackages/ee/src/<feature>/(or<feature>.server.ts). Fix~/deps (sanitize→@carbon/utils; redefine~/utils/querytypes locally; keeptrigger()/@carbon/notificationsin the ROUTE —@carbon/eecan't import@carbon/jobs/@carbon/notifications). - Embed
requireEntitlementat the top of every authoring write fn; runtime reads that must degrade usecompanyHasFeature→ return empty/no-op. - Repoint call sites; remove from the app module + barrel.
- Bundling gotchas (typecheck won't catch — only the dev build does): a client
barrel must NOT derive types via
ReturnType<service>(derive from@carbon/database); a*.service.tsmust NOT import@carbon/ee/<f>.server(move that caller to a*.server.ts). See the rule's "Bundling gotcha". - UI:
.ee.tsx; nav stays visible; gated page rendersusePlanGateoverlay (RulesUpgradeOverlayfor tables,UpgradeOverlayprimitives / a modal for editors — mirrorSalesRulesUpgradeOverlayand the per-user permissions modal). pnpm run generate:mcpif functions left a*.service.ts(they drop as MCP tools — usually correct; note it).
Verification per feature (what I CAN do autonomously)
pnpm exec turbo run typecheck --filter=@carbon/eecd apps/erp && pnpm run typecheck(ignore ONLY the pre-existingroot.tsx(57) Cannot find module './+types/root')pnpm exec biome check --write <touched files>- Relevant unit tests (
pnpm --filter @carbon/ee test, app vitest). - Add entitlement unit tests exercising BOTH editions where practical
(
companyHasFeature/requireEntitlement: Community→blocked, Enterprise/Cloud-Business→allowed). pnpm run translate(or leave a note) to fill the new overlay strings.- Commit each feature as its own checkpoint (message
feat(ee): gate <FEATURE> …).
Acceptance / testing — TWO PHASES (browser = human, in the morning)
The dev build's .server client-graph check is the thing typecheck misses; I prevent
it via the bundling rules but the browser boot is the real proof and is Brad's.
- Gated case —
CARBON_EDITION=community(current.env): each feature's nav entry is VISIBLE, the page shows the upgrade overlay, and writes are blocked (direct-URL POST returns blocked / no effect). Inviting users still works. - Non-gated case —
CARBON_EDITION=enterprise: switch.env, restart stack. Every feature is fully VISIBLE and FUNCTIONAL (create/edit/delete work, no overlay). → This validates the embeddedrequireEntitlementpasses for entitled companies and nothing was over-gated. A per-feature browser checklist is maintained in the STATUS table's Notes.
Context-management protocol (how the overnight run stays alive)
- This file is the ledger; update the STATUS table after every feature.
- Heavy work → one subagent per feature (fresh context). I verify + commit + update ledger + dispatch the next. Subagent completion re-invokes me, so the loop is self-sustaining as long as one subagent is always in flight.
- STOP and leave a
⚠ BLOCKEDnote (don't guess) when a feature needs a product decision (is X a Business feature? destructive surface? engine too woven into jobs). - Do NOT open a PR or merge — commits on the branch are the deliverable for review.
TODO (ranked — from inventory abfcc035)
Default decision (matches permissions/approvals precedent): convert requirePlan/
companyHasPlan → requireFeature/companyHasFeature (community-blocked) for every
gated feature; move authoring bodies into packages/ee + embed requireEntitlement;
runtime engines that live in packages/jobs/@carbon/notifications (can't move to ee)
just swap to companyHasFeature (degrade). Do these autonomously (A–I). FLAG the LARGE
product/architecture decisions (J–L) — don't guess.
- A. SALES_RULES + STORAGE_RULES (together — shared
upsertEnforcementRule/deleteEnforcementRuleinshared.service.ts:619,651). Evaluators already inpackages/ee/src/rules/{sales,storage}/server.ts→ swapcompanyHasPlan→companyHasFeature(sales/server.ts:48,storage/server.ts:50); move the shared enforcement-rule CRUD +assign/unassign*into ee, embedrequireEntitlement; routesrequirePlan→requireFeature. Watchshared.service.tsbarrel client-graph. - B. EMAIL_NOTIFICATIONS — body in
packages/jobsnotify.ts:537(can't move). JustcompanyHasPlan→companyHasFeaturethere +account+/notifications.tsx:49. Tiny. - C. INTEGRATIONS — bodies already in ee. Embed
requireEntitlement("INTEGRATIONS")inintegrations/hooks.server.ts/secrets.tsinstall/save (honorisIntegrationWhitelisted); routesintegrations.$id.tsx:1476,integrations.deactivate.$id.tsx:26→requireFeature. - D. TWO_FACTOR — move only the
requireMfacompany-policy writer into ee +requireEntitlement(mirrorupdateConsoleSetting);security.tsx:159→requireFeature. Leave GoTrue MFA. - E. API_KEYS — move
upsertApiKey/deleteApiKey(settings.service.ts:1317,98) to ee +requireEntitlement; routes→requireFeature. Leave@carbon/authruntime verify. Barrel client-graph risk. - F. WEBHOOKS — move
upsertWebhook/deleteWebhook(settings.service.ts:1478,112) to ee +requireEntitlement; routes→requireFeature; gate delivery via runtimecompanyHasFeaturein jobs. Barrel risk. - G. FORECAST — extract
upsertDemandForecasts/deleteDemandForecasts(production.service.ts:4753,498) to ee +requireEntitlement; routes→requireFeature. - H. CUSTOMER_PORTALS — move portal authoring (
shared.service.ts:256-298+ theupsertExternalLinkpath) to ee +requireEntitlement; keep public share-page (share+/customer.$id*) as runtimecompanyHasFeaturedegrade. - I. AUDIT_LOG — ⚠ RE-SCOPED → FLAGGED (see STATUS row). This original framing was
wrong: the
audit-logs.tsx:92requirePlanis in the ACTION (enable intent), not a loader redirect, and the list route ALREADY renders visible+overlay. The real gate target isenableAuditLog(the enable write), which has ITAR/compliance callers that make a hardrequireEntitlementunsafe without a licensing-policy decision. Flagged for Brad.
FLAGGED — do NOT do autonomously (need Brad)
- J. AI_AGENT ⚠ — LARGE; currently HIDDEN when gated (
useAgentAvailable.ts:12). Decision needed: hidden→visible+overlay? Core inmodules/agentdeeply~/-coupled (AI SDK, cross-module tools) — big relocation. - K. WORKFLOWS ⚠ — authoring movable to ee, but the runtime ENGINE is a full inngest
system in
packages/jobs(gate viacompanyHasFeature). LARGE; confirmedworkflows.service.tsReturnType/~/utils/queryclient-graph gotcha to fix. - L. BACKUPS ⚠ — engine deeply in
packages/jobs; rule says relocate LAST. Already gated viacanManageBackups(route-level). Big lift; keep thecanAccessBackupsinternal/local-dev escape hatch.
Every move: no *.service.ts may import @carbon/ee/<f>.server (barrel→client graph —
move the caller to *.server.ts); derive client types from @carbon/database, not
ReturnType<service>; run generate:mcp when fns leave a *.service.ts.
STATUS
| Feature | Size | State | Commit | Notes |
|---|---|---|---|---|
| PERMISSIONS | — | ✅ done | ba2787c2 | body in ee, requireEntitlement embedded, per-user modal overlay |
| console (PERMISSIONS) | — | ✅ done | ba2787c2 | console.server in ee, embedded; card gated-state |
| APPROVAL_RULES | — | ✅ done | ba2787c2 | approvals/ in ee, embedded, page overlay |
| BACKUPS | gate-only | ◑ gated | ba2787c2 | gated via canManageBackups; engine still in packages/jobs (LARGE relocation deferred — do last) |
| A. SALES_RULES + STORAGE_RULES | MEDIUM | ✅ done | (this) | CRUD → packages/ee/src/rules/service.server.ts (@carbon/ee/rules.server), requireEntitlement by family; evaluators swapped companyHasPlan→companyHasFeature; 12 write routes → requireFeature; verified (ee+erp typecheck, biome, 1041 ee tests, mcp shared 31→29). unassignStorageRule gained companyId arg. |
| B. EMAIL_NOTIFICATIONS | SMALL | ✅ done | (this) | companyHasPlan→companyHasFeature at notify.ts:537 (jobs, runtime degrade — email channel off for community) + account/notifications.tsx:49. Body stays in jobs (can't move to ee — @carbon/notifications dep). Verified jobs+erp typecheck. |
| C. INTEGRATIONS | MED (arch) | ⚠ FLAGGED — needs Brad | No single ee choke point for the install/save WRITE: it goes through community upsertCompanyIntegration (settings.server.ts:330, inline vault write), NOT ee persistIntegrationSecrets. Shared install/update dispatcher (hooks.server.ts:84) also serves uninstall+read (can't gate). Per-provider hooks have HOLES (jira/linear/onshape/paperless-parts/slack have no onInstall/onUpdate). Decision: (A) relocate the universal integration secret/metadata write into ee persistIntegrationSecrets + embed requireEntitlement (complete, covers OAuth callbacks; bigger) — RECOMMENDED; or (B) embed in the 4 existing provider hooks + accept documented holes. Route swap requirePlan→requireFeature held pending this (else it's a UX-only mislabeled moat). |
|
| D. TWO_FACTOR | SMALL-MED | ✅ done | (this) | updateRequireMfaSetting → packages/ee/src/two-factor.server.ts; requireEntitlement scoped to ENABLING only (downgrade can still disable); security.tsx route→requireFeature; mcp 1548→1547. Verified. |
| E. API_KEYS | MEDIUM | ✅ done | (this) | upsert/deleteApiKey → packages/ee/src/api-keys.server.ts + requireEntitlement (companyId from payload/row); 3 routes→requireFeature; key-gen/hash stays in route; mcp 1547→1545. Runtime verify (@carbon/auth) untouched. Verified. Doc-sync TODO: settings/AGENTS.md lists upsert/deleteApiKey (stale). |
| F. WEBHOOKS | MEDIUM | ✅ done | (this) | upsert/delete/deactivateWebhooks → packages/ee/src/webhooks.server.ts + requireEntitlement; delivery gated via companyHasFeature degrade in jobs events/webhook.ts:37; 3 routes→requireFeature; mcp −3. Verified. |
| G. FORECAST (demandForecast fns) | MEDIUM | ✅ done | (this) | PREMISE MISMATCH found: upsert/deleteDemandForecasts had NO app callers (MCP-only) — moved to packages/ee/src/forecast.server.ts + requireEntitlement (closes ungated DESTRUCTIVE MCP write path); mcp 252→250. The REAL forecast UI uses demandProjection — see G2. |
| G2. FORECAST (demandProjection = the real feature) | MEDIUM | ✅ done | 5446f132fa | upsert/deleteDemandProjections → packages/ee/src/forecast.server.ts + requireEntitlement("FORECAST"); 3 demand-forecasts.* routes → requireFeature; mcp 1540→1538. ALSO fixed a pre-existing red test: mcp-tool-metadata.test.ts "module-local type alias" case referenced shared_upsertApprovalRule (removed when approvals→ee, ba2787c2) — repointed to items_diffMethod (input: DiffMethodInput, same named-alias path). Verified ee+erp typecheck, biome, full mcp test 19/19. |
| H. CUSTOMER_PORTALS | MEDIUM | ✅ done | 0716bea88e | New packages/ee/src/customer-portals.server.ts: upsertCustomerPortal(client, companyId, portal) + deleteCustomerPortal(client, id, companyId), each requireEntitlement("CUSTOMER_PORTALS"). Did NOT gate the shared upsertExternalLink (also used by quote/RFQ/supplier-quote finalize) — added portal-specific ee writers instead. deleteCustomerPortal removed from shared.service.ts (now companyId-scoped); reads + upsertExternalLink stay. 3 routes → ee + requireFeature; list route already visible+overlay. Public share pages companyHasPlan→companyHasFeature (degrade). UI Form/Table → .ee.tsx. mcp 1538→1537 (shared_deleteCustomerPortal drops). Verified: ee+erp typecheck, biome, client-graph grep clean. |
| I. AUDIT_LOG | MEDIUM | ⚠ FLAGGED — needs Brad | NOT a clean surgical gate. (1) ITAR CONFLICT: enableAuditLog (the enable "write") has non-route compliance callers — company.new.tsx/companies.new.tsx call it at company creation under CONTROLLED_ENVIRONMENT, and audit-logs.tsx loader force-enables for controlled companies (audit is MANDATORY + non-disableable under ITAR). A hard requireEntitlement("AUDIT_LOG") inside enableAuditLog would BREAK audit enablement on a self-hosted Community ITAR install — UNLESS the invariant "CONTROLLED_ENVIRONMENT ⇒ Enterprise edition" is guaranteed (then companyHasFeature returns true and the gate is safe). That is a licensing/compliance policy call. (2) Body lives in @carbon/database/audit + @carbon/jobs (write path + archiving are Inngest), like K/L — a large relocation, not an app-service move. (3) No broken state today: list route already visible+overlay (AuditLogUpgradeOverlay + usePlanGate), settings action already has requirePlan UX gate. Same "incomplete moat" status as BACKUPS. Decision for Brad: is CONTROLLED_ENVIRONMENT always Enterprise-licensed? If yes → gate enableAuditLog in ee (safe). If a Community ITAR install is supported → the gate needs a CONTROLLED_ENVIRONMENT bypass. | |
| J. AI_AGENT | LARGE | ⚠ FLAGGED | hidden→overlay decision + big relocation; needs Brad | |
| K. WORKFLOWS | LARGE | ⚠ FLAGGED | engine in jobs; needs Brad | |
| L. BACKUPS engine | LARGE | ⚠ FLAGGED | relocate engine from jobs; do last; needs Brad |