Skip to content

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.

chore(license): relocate commercial engines into packages/ee; free planning + configurator (#1696)

Brad Barbin41a24bffc32a
diff --git a/.ai/plans/2026-09-21-ee-vs-ce-cleanup.md b/.ai/plans/2026-09-21-ee-vs-ce-cleanup.md
new file mode 100644
index 0000000000..e549d06a81
--- /dev/null
+++ b/.ai/plans/2026-09-21-ee-vs-ce-cleanup.md
@@ -0,0 +1,290 @@
+# EE vs CE Licensing Cleanup
+
+Branch: `ee-vs-ce-cleanup`
+Started: 2026-09-21
+Owner: Brad ([email protected])
+
+State legend: `[ ]` todo · `[~]` in progress · `[x]` done · `[!]` blocked/needs decision
+
+This plan is the durable state for a large licensing refactor. Update the
+checkboxes and the "Session log" as work lands. Each feature is a self-contained
+unit; the tree must stay green after each.
+
+Reference: `.claude/rules/commercial-licensing.md` (the pattern), `LICENSE` +
+`packages/ee/LICENSE` (the boundary: Enterprise = everything under `packages/ee`
+OR any filename containing `.ee.`).
+
+---
+
+## Task 1 — Configurator rules engine → CE ✅ DONE
+
+The configurator UI was freed in commit b99dd084a7; only the sandbox engine file
+was left marked EE.
+
+- [x] `git mv packages/database/supabase/functions/lib/sandbox.ee.ts → sandbox.ts`
+- [x] Update importer `packages/database/supabase/functions/get-method/index.ts:33`
+- [x] Update doc source `docs/content/docs/reference/configurator.mdx`
+- [x] Regenerate agent KB (`pnpm run generate:agent-kb`)
+- [x] Verify no `sandbox.ee` references remain
+
+---
+
+## Task 3 — License Section 2 wording ✅ DONE
+
+- [x] `packages/ee/LICENSE` Section 2 updated to add "…or otherwise without
+ making any Enterprise functionality available…"
+
+---
+
+## Task 4 — Material Planning (MRP + scheduler) → CE ✅ DONE
+
+The engine `packages/ee/src/planning/` was self-contained: zero EE-internal deps,
+no entitlement gating. Depended only on `@carbon/database` subpaths + `@carbon/utils`.
+
+**Decision: new package `packages/planning` (`@carbon/planning`).** Cleanest CE
+licensing boundary; no cycle risk. Source-exported `.ts` like `@carbon/ee`.
+
+### Steps
+- [x] Created `packages/planning/` (`package.json`, `tsconfig.json` extends
+ `base.json`, `vitest.config.ts`). deps: `@carbon/database`, `@carbon/utils`,
+ `@internationalized/date`, `@supabase/supabase-js`, `kysely`, `zod`.
+ devDeps: `@carbon/config`, `typescript`, `vitest`. (No `@logtape` needed —
+ planning reaches logging via `@carbon/database/logging`.)
+- [x] `git mv packages/ee/src/planning/{index.ts,mrp,scheduling}` → `packages/planning/src/`
+- [x] Removed `"./planning"` export from `packages/ee/package.json`
+- [x] Repointed 9 functional import sites → `@carbon/planning` (11 specifiers incl. 3 dynamic + vi.mock)
+- [x] Repointed test `$jobId.status.test.ts` (import + vi.mock)
+- [x] Added `@carbon/planning: workspace:*` to `packages/jobs` + `apps/erp` package.json
+- [x] Updated comment refs in the 7 `@carbon/database` files + `production.mcp.server.ts`
+- [x] Created `packages/planning/AGENTS.md`; updated `packages/ee/AGENTS.md`,
+ `.claude/rules/{mrp-system,scheduling-data-structures}.md` (paths + mentions),
+ `packages/database/AGENTS.md`, `apps/erp/app/modules/production/AGENTS.md`,
+ `docs/content/docs/reference/forecast.mdx` (+ regenerated agent KB)
+- [x] Verified: `@carbon/planning` typecheck ✓ + 183 tests ✓; `@carbon/jobs`
+ typecheck ✓; `erp` typecheck ✓ (after `react-router typegen`)
+- [x] `pnpm install` (workspace linked)
+- Note: 3 pre-existing biome style warnings in relocated test files (unchanged content).
+- Note: MCP `tool-manifest.digest.json` UNCHANGED (planning wasn't an MCP tool source).
+
+---
+
+## Task 2 — Move CE-located commercial engines into `packages/ee`
+
+All five already have `Feature` keys in `packages/ee/src/plan.ts`
+(`EMAIL_NOTIFICATIONS`, `MCP`, `BACKUPS`, `WORKFLOWS`, `AUDIT_LOG`) and route/UX
+gates. The remaining work per feature: relocate engine body into
+`packages/ee/src/<feature>/` and embed `requireEntitlement` (authoring) /
+`companyHasFeature` (runtime-degrade). Do them **one at a time, tree green each**.
+Order = ascending risk.
+
+### 2a. Audit log ✅ DONE
+Scoping revealed a CLEANER move than originally planned: only the ENGINE
+(`audit.ts`) moves; `audit.config.ts` + `audit.types.ts` STAY in `@carbon/database`
+(client-graph members holding generic schema types `TableName`/`ColumnOf` consumed
+by CE packages `@carbon/workflows`, `@carbon/jobs` — moving them would force
+community packages into a commercial dep for no licensing benefit). Cycle-safe:
+`@carbon/database` never imports audit internally; all 10 engine importers are apps.
+- [x] `git mv packages/database/src/audit.ts` → `packages/ee/src/audit/audit.ts`
+- [x] Rewired moved engine's imports: `./audit.config`→`@carbon/database/audit.config`,
+ `./audit.types`→`@carbon/database/audit.types`, `./event`→`@carbon/database/event`
+- [x] Embedded `requireEntitlement("AUDIT_LOG")` in `enableAuditLog`, guarded by
+ `if (!CONTROLLED_ENVIRONMENT)` (ITAR audit is mandatory; all 3 auto-enable
+ call sites are already CONTROLLED_ENVIRONMENT-gated). Left read getters +
+ `insertAuditLogEntries` ungated (capture is gated by subscription creation,
+ which `enableAuditLog` controls; avoids dropping security-audit events + hot-path cost).
+- [x] Removed `"./audit"` from `packages/database/package.json`; added
+ `"./audit.server": "./src/audit/audit.ts"` to `packages/ee/package.json`
+- [x] Repointed 10 app engine importers `@carbon/database/audit` → `@carbon/ee/audit.server`
+ (erp routes + mes itar.service; both apps already depend on `@carbon/ee`)
+- [x] Updated `.claude/rules/audit-log-system.md` (paths + wrapper location),
+ `commercial-licensing.md` (rollout ✅), `packages/database/AGENTS.md`, `packages/ee/AGENTS.md`
+- [x] Verified: `@carbon/ee`, `erp`, `mes`, `@carbon/jobs` all typecheck clean
+ (mes/erp after `react-router typegen`). No audit .test.ts to move.
+
+### 2b. MCP ✅ DONE — protocol engine → `@carbon/ee/mcp` + `@carbon/ee/mcp.server`
+Executed via DI (the dispatch is `~/`-bound and can't move): `git mv` server.ts +
+catalog-search/describe-format/format-result/instructions/types → `packages/ee/src/mcp/`;
+split exports — `@carbon/ee/mcp` (pure barrel `index.ts`, no auth/entitlement chain, for
+tests) and `@carbon/ee/mcp.server` (`server.ts`). `createMcpServer` is now generic over
+the auth context, takes injected `deps` `{ callOperation, operationsByName, isListOperation,
+isMcpBlockedTool, catalogSearch, toolMetadata }`, and embeds `requireEntitlement("MCP")`
+(async; route catches `EntitlementError` → 402, replacing the deletable in-route
+`companyHasFeature`). `types.ts` `McpContext` redefined structurally (no `~/` import) +
+`McpServerDeps`/`McpCallResult`; `instructions.ts` takes the catalog summary as an arg (no
+app-JSON import). Route `_index.ts` builds `catalogSearch` once + passes deps; imports
+`createCatalogSearch` from `@carbon/ee/mcp`, `createMcpServer` from `@carbon/ee/mcp.server`.
+`tool-metadata.json` + `mcp-blocked-tools.ts` + `manifest.ts` + `agent-setup-prompt.ts`
+stay in the app. Added ee deps: `@modelcontextprotocol/sdk`, `zbsearch` (runtime),
+`@carbon/api` (devDep, type-only). The 3 pure-logic tests stay in-app (real
+`tool-metadata.json`) importing from `@carbon/ee/mcp` (pure barrel avoids the glossary/auth
+load that broke them under the heavy barrel). Updated `.claude/rules/mcp-tools-reference.md`,
+`commercial-licensing.md` (✅), `packages/ee/AGENTS.md`.
+Verified: ee + erp typecheck green; **158 MCP tests pass** (49 lib + 109 generator/dispatch).
+⚠️ RESIDUAL: `server.ts` is `@ts-nocheck` and the live `POST /api/mcp` endpoint can't be
+exercised in this env — needs an endpoint smoke test before merge.
+
+#### (original scoping) ~1k lines; engine in `apps/erp/.../api+/mcp+/`
+- [ ] Move the dispatch core (`lib/server.ts` + helpers) into
+ `packages/ee/src/mcp/`; keep the thin route in the app calling it.
+- [ ] Embed `requireEntitlement("MCP")` in the ee entry (route keeps its
+ `companyHasFeature` choke as UX).
+- [ ] Watch `generate:mcp` digest: tools ARE the ERP `*.service.ts`; moving the
+ dispatcher does not move the tool bodies. Run `pnpm run generate:mcp`,
+ review digest diff.
+- [ ] Verify.
+
+### 2c. Email notifications ✅ DONE
+Scoping: the lockable seam is just the email-channel DECISION. `sendEmail`
+(`@carbon/lib`) is GENERIC transactional transport (invites, MFA, password,
+onboarding) — must NOT be gated. `content.ts`, in-app/slack channels, `send-email.ts`
+all stay CE.
+- [x] Created `packages/ee/src/email-notifications/deliver.server.ts` →
+ `emailNotificationsEnabled(client, companyId)` (wraps
+ `companyHasFeature("EMAIL_NOTIFICATIONS")`, DEGRADE not throw). Distinct dir
+ from the existing `packages/ee/src/email/` integration-config.
+- [x] Added `"./email-notifications.server"` export to `packages/ee/package.json`
+- [x] Rewired `notify.ts` `check-email-plan` step → `emailNotificationsEnabled`
+ (feature key + degrade contract now in commercial code); step id unchanged
+- [x] Verified: `@carbon/ee` + `@carbon/jobs` typecheck green
+
+### 2d. Backups ✅ DONE (gate-in-place — engine is Inngest-coupled, CANNOT move)
+Scoping: the durable functions import `@carbon/jobs`-internal `../../../db` + the
+inngest client, so the engine can't move to ee (would invert the dep). Onboarding
+(`company-template`) is a second caller of `buildCompanyBackup`/`wipeAndLoad` and
+must stay free. `packages/jobs/src/backups/` is import-light (bare-`tsx` CLI +
+`db:check:backups`) — left untouched.
+- [x] Created `packages/ee/src/backups.server.ts` → `requireBackupsEntitlement(companyId)`
+ = `if (IS_LOCAL_DEV) return; requireEntitlement(serviceRole, companyId, "BACKUPS")`.
+ Added `"./backups.server"` export.
+- [x] Embedded the gate at the top of all 5 durable functions: `companyExportFunction`
+ (company-export.ts), `companyRestore{,Finalize,Revert}Function` (company-restore.ts),
+ `companyImportFunction` (company-import.ts — exempts `referencedTemplate` onboarding).
+- [x] Left `canManageBackups` (app route UX gate) + `canAccessBackups` (browser-safe
+ hatch for nav/Demo Data) in place. Did NOT push the check into
+ `buildCompanyBackup`/`wipeAndLoad` (onboarding uses them).
+- [x] In-app purge/delete/upload stay route-gated by `canManageBackups` (they carry
+ `email` for the internal-staff hatch; heavy work funnels into the gated durable fns).
+- [x] Updated `commercial-licensing.md` (✅), `company-backup-restore.md`, `packages/ee/AGENTS.md`.
+- [x] Verified: `@carbon/ee` + `@carbon/jobs` typecheck green.
+- Accepted tightening: internal-staff export of a real customer Starter company on
+ Cloud is now blocked at the job (no email on the service-role path); backups is a paid
+ feature and this path is not a normal support flow.
+
+### 2e. Workflows ✅ DONE — moved the whole package into `@carbon/ee/workflows`
+Executed: created `@carbon/workflows-core` leaf (`run-trigger.ts` + `moments.ts`
+`MOMENT_OUTPUT_KEYS`/types); repointed `@carbon/lib` (events.ts + raise-moment.ts)
+to the leaf and swapped its dep (cycle broken); `git mv packages/workflows/src` →
+`packages/ee/src/workflows` + AGENTS.md; deleted `packages/workflows`; engine
+`run-trigger.ts`/`catalog/moments.ts` re-export the contracts from the leaf; added ee
+exports `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`
++ deps (`@carbon/workflows-core`, `@lingui/core`, glossary devDep); repointed all 94
+importers (`@carbon/workflows` → `@carbon/ee/workflows`); removed stale
+`@carbon/workflows` deps from erp/jobs package.json, swapped checks dep to `@carbon/ee`;
+fixed build-critical paths (turbo.json inputs, package.json generate script, lingui.config.js,
+scripts/{check,generate}-workflow-catalog.ts, checks `sources/typescript.ts` — removed the
+now-redundant `packages/workflows/src` entry since `packages/ee/src` already covers it);
+embedded gates — runtime DEGRADE `workflowsEnabledForCompany(companyId)` in jobs
+`engine/execute.ts` (Skipped when not entitled), authoring throw `requireWorkflowsEntitlement`
+in erp `publishWorkflowVersion`; added the `MOMENT_OUTPUT_KEYS`↔`WORKFLOW_MOMENTS` sync
+assertion to `check-workflow-catalog.ts`; added the ee mock to the 4 jobs engine test files.
+Verified: typecheck ee/jobs/erp/lib/checks/workflows-core green; ee tests 1499 pass, jobs
+tests 734 pass; `check:workflow-catalog` green. Docs update delegated to a subagent.
+
+<!-- original plan retained below for reference -->
+#### (original plan) ~23k lines, 96 importers
+Directive: **move the whole `@carbon/workflows` package** into `packages/ee`.
+
+**Cycle reality (scoped):** only **`@carbon/lib`** is a real cycle source —
+`@carbon/database` and `@carbon/checks` were FALSE alarms:
+- `@carbon/database` datasets only MENTION `@carbon/workflows` in comments (0 real
+ imports); the real edge runs the other way (`@carbon/database` EXPORTS
+ `./seed-workflows`, consumed test-only by workflows). No `database → workflows` dep.
+- `@carbon/checks` imports it (1 script) but `@carbon/ee` does NOT depend on checks
+ → `checks → ee` after repoint is safe.
+- `@carbon/lib` imports it in 2 files, **type-only**: `events.ts` (`type RunTrigger`),
+ `workflows/raise-moment.ts` (`type MomentKey, MomentPayload`). `@carbon/ee` depends
+ on `@carbon/lib` → this is the cycle to break.
+
+**Plan (confirmed: extract a tiny CE leaf, then move the rest):**
+- [ ] Create leaf package `@carbon/workflows-core` (dep: `zod` only) holding the
+ wire contracts lib needs:
+ - `run-trigger.ts` — move `runTriggerSchema` + `RunTrigger` VERBATIM (it's
+ already self-contained, imports only `zod`).
+ - moment contract — the derivation is `MomentPayload<K> = { [O in
+ keyof WORKFLOW_MOMENTS[K]["outputs"]]: MomentEntityRef }`, i.e. it needs the
+ per-moment OUTPUT KEY NAMES only (not the `t.entity(...)` types). So the leaf
+ holds `export const MOMENT_OUTPUT_KEYS = { "production.jobReleased": ["job",
+ "releasedBy"], ... } as const` (9 entries, keys+output-key-names copied from
+ `catalog/moments.ts` `WORKFLOW_MOMENTS`), then `MomentKey =
+ keyof typeof MOMENT_OUTPUT_KEYS`, `MomentEntityRef = { id: string }`,
+ `MomentPayload<K> = { [O in (typeof MOMENT_OUTPUT_KEYS)[K][number]]:
+ MomentEntityRef }`. The engine's `WORKFLOW_MOMENTS` stays the source of truth
+ (labels/permissions/`t.entity`); have the engine RE-EXPORT `MomentKey`/
+ `MomentPayload`/`MomentEntityRef` from `-core` (drop its local defs) so there
+ is ONE type. Add an assertion in `scripts/check-workflow-catalog.ts` that
+ `Object.keys(MOMENT_OUTPUT_KEYS)` === `Object.keys(WORKFLOW_MOMENTS)` AND each
+ moment's output keys match — this is the sync invariant typecheck won't catch.
+- [ ] Repoint `@carbon/lib` (`events.ts`, `workflows/raise-moment.ts`) →
+ `@carbon/workflows-core`; swap its `@carbon/workflows` dep for `-core`.
+- [ ] `git mv packages/workflows/src/**` (minus the extracted leaf) →
+ `packages/ee/src/workflows/`. Re-export `RunTrigger`/`runTriggerSchema` +
+ moment types from `-core` so `@carbon/ee/workflows` surface is unchanged.
+- [ ] Add ee exports: `./workflows`, `./workflows/help`, `./workflows/labels`.
+ Add ee deps: `@carbon/glossary` (devDep, type-only), `@lingui/core` (for
+ `./workflows/labels`), `@carbon/workflows-core`. (already has database, utils,
+ intl-date, kysely, zod.)
+- [ ] Repoint 96 importers → `@carbon/ee/workflows` (+`/help`, `/labels`):
+ erp 61, jobs 32, checks 1 (lib now off it). erp + jobs already dep ee; add
+ `@carbon/ee` to `packages/checks/package.json`.
+- [ ] Lock the runtime engine `packages/jobs/src/workflows/`: embed
+ `companyHasFeature("WORKFLOWS")` at `engine/execute.ts` (runs on background
+ events, bypassing route gates). Default: gate in place, keep in jobs (Inngest-coupled).
+- [ ] Embed `requireEntitlement("WORKFLOWS")` in
+ `apps/erp/app/modules/workflows/workflows.service.ts` authoring writes.
+- [ ] Move `packages/workflows/AGENTS.md` → ee; update rules referencing it.
+- [ ] Delete empty `packages/workflows`; `pnpm install`.
+- [ ] Verify typecheck erp + jobs + ee + checks + lib; run workflows test suites.
+
+---
+
+## Cross-cutting verification (run before considering any feature done)
+- `pnpm exec turbo run typecheck --filter=<pkg>` (scoped — whole-repo OOMs)
+- `pnpm run lint` (biome)
+- `pnpm --filter <pkg> test`
+- Dev build for `.server` client-graph errors (typecheck won't catch these)
+- Update `.claude/rules/commercial-licensing.md` "Rollout status" per feature
+- Update affected `AGENTS.md` and `.claude/rules/*` `paths:` frontmatter
+
+## Open decisions
+- [x] Task 4 destination: new `packages/planning` — DONE.
+- [x] Workflows cycle resolution (2e): scoped — only `@carbon/lib` (2 type-only
+ imports) is a real cycle; extract a tiny `@carbon/workflows-core` leaf (zod-only:
+ `RunTrigger` + moment contract), repoint lib, move the rest to `@carbon/ee/workflows`.
+- [!] Does the jobs workflow-execution engine (`packages/jobs/src/workflows/`)
+ physically move to ee, or gate-in-place? Default: gate-in-place
+ (`companyHasFeature` at `engine/execute.ts`); it's Inngest-coupled.
+
+## Session log
+- 2026-09-21: Tasks 1 & 3 done. Plan written. Task 4 DONE (new `@carbon/planning`
+ package; typechecks + 183 planning tests green). Task 2a (audit) DONE — engine →
+ `@carbon/ee/audit.server` with `requireEntitlement` (ITAR-guarded); config/types
+ stay in `@carbon/database`; ee/erp/mes/jobs typecheck green.
+- 2026-09-21 (cont.): 2c (email) DONE — `@carbon/ee/email-notifications.server`;
+ ee+jobs green. 2d (backups) DONE — gate-in-place `@carbon/ee/backups.server`
+ `requireBackupsEntitlement` embedded in all 5 durable functions; ee+jobs green.
+ 6 of 8 pieces complete and green (1, 3, 4, 2a, 2c, 2d). Tree is GREEN.
+ REMAINING (each must land atomically): **2e workflows** (whole-package move: new
+ `@carbon/workflows-core` leaf + move to `@carbon/ee/workflows` + repoint 96
+ importers + lock jobs `execute.ts`/erp `workflows.service.ts`) and **2b MCP** (DI
+ refactor of `@ts-nocheck` server.ts + 5 helpers → `@carbon/ee/mcp.server`, inject
+ app dispatch/metadata, +3 ee deps `@modelcontextprotocol/sdk`/`zbsearch`/`@carbon/api`;
+ metadata-coupled tests stay in app importing from ee). Both fully scoped above.
+- 2026-09-21 (final): ALL 8 pieces DONE. 2e (workflows) — whole package → `@carbon/ee/workflows`
+ + `@carbon/workflows-core` leaf; 94 importers repointed; gates in jobs `execute.ts` (runtime
+ degrade) + erp `publishWorkflowVersion` (authoring throw); moment-sync invariant added.
+ 2b (MCP) — engine → `@carbon/ee/mcp` (pure) + `@carbon/ee/mcp.server` via DI;
+ `requireEntitlement("MCP")` inside `createMcpServer`. Final consolidated typecheck GREEN
+ 9/9 (ee, jobs, planning, workflows-core, lib, checks, erp, mes). Tests green: ee 1499,
+ jobs 734, MCP 158, planning 183, `check:workflow-catalog`. Docs synced.
+ Committed 6703148569 + pushed; PR #1696 open (base main).
+ ✅ Brad smoke-tested MCP + the other flagged flows — all pass. No residuals.
diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.md
index 1bc679c50e..441ec3a921 100644
--- a/.claude/rules/audit-log-system.md
+++ b/.claude/rules/audit-log-system.md
@@ -1,6 +1,8 @@
---
paths:
- - packages/database/src/audit.*
+ - packages/ee/src/audit/audit.ts
+ - packages/database/src/audit.config.ts
+ - packages/database/src/audit.types.ts
- packages/jobs/src/inngest/functions/events/audit.ts
- packages/jobs/src/inngest/functions/scheduled/audit-archive.ts
- apps/erp/app/components/AuditLog/**
@@ -99,7 +101,7 @@ lookup per target table), and writes via `client.rpc("insert_audit_log_batch", {
- RPCs: `create_audit_log_table`, `insert_audit_log_batch`, `get_entity_audit_log` (optional `p_record_id`),
`get_audit_log` (filters + `totalCount`), `get_audit_logs_for_archive`, `delete_old_audit_logs`.
-- `packages/database/src/audit.ts` wrappers: `getEntityAuditLog`, `getGlobalAuditLog`, `insertAuditLogEntries`,
+- `packages/ee/src/audit/audit.ts` wrappers (commercial — `@carbon/ee/audit.server`; `enableAuditLog` embeds `requireEntitlement("AUDIT_LOG")`, skipped under `CONTROLLED_ENVIRONMENT` where audit is mandatory): `getEntityAuditLog`, `getGlobalAuditLog`, `insertAuditLogEntries`,
`enableAuditLog`, `disableAuditLog` (keeps data), `isAuditLogEnabled`, `syncAuditSubscriptions`
(adds triggers for entities added to config after enable), `getAuditLogArchives`, `getArchiveDownloadUrl`,
`getAuditLogsForArchive`, `deleteOldAuditLogs`, `recordAuditLogArchive`.
diff --git a/.claude/rules/commercial-licensing.md b/.claude/rules/commercial-licensing.md
index 430a0c2016..145865b4fb 100644
--- a/.claude/rules/commercial-licensing.md
+++ b/.claude/rules/commercial-licensing.md
@@ -139,11 +139,48 @@ Refactor one at a time; each PR should leave the tree green.
`packages/ee/src/customer-portals.server.ts`, `requireEntitlement("CUSTOMER_PORTALS")`;
the shared `upsertExternalLink` stays ungated (used by quote/RFQ finalize); public share
pages degrade via `companyHasFeature`.
-- ⬜ **Backups** — engine still in `packages/jobs`; gated via `canManageBackups` only
- (route-level). Biggest lift — relocate the engine last.
+- ✅ **Audit log** — engine moved to `packages/ee/src/audit/audit.ts`
+ (`@carbon/ee/audit.server`); `enableAuditLog` embeds `requireEntitlement("AUDIT_LOG")`,
+ skipped under `CONTROLLED_ENVIRONMENT` (ITAR audit is mandatory). `auditConfig`/types
+ stay client-safe in `@carbon/database` (generic schema types consumed by CE packages).
+- ✅ **Backups** — engine is Inngest-coupled and CANNOT move to `packages/ee` (it
+ imports `@carbon/jobs`-internal `../../../db` + the inngest client). Locked
+ gate-in-place: `requireBackupsEntitlement(companyId)`
+ (`packages/ee/src/backups.server.ts` → `@carbon/ee/backups.server`) is embedded at
+ the top of every START-action durable function — `companyExportFunction`,
+ `companyRestoreFunction`, `companyImportFunction`. Finalize/revert
+ (`companyRestore{Finalize,Revert}Function`) are deliberately NOT gated: they only
+ RESOLVE an already-started restore, so gating them would strand a pending restore
+ (marker stuck `ready`, snapshot orphaned) if BACKUPS lapsed while it sat pending.
+ Local-dev
+ exempt (`IS_LOCAL_DEV` — the service-role job path has no email for the
+ `isInternalEmail` hatch); onboarding demo-template apply/revert call
+ `buildCompanyBackup`/`wipeAndLoad` directly and are NOT gated (import exempts
+ `referencedTemplate`). `canManageBackups` stays the route-level UX gate.
+- ✅ **Email notifications** — the email-channel decision moved to
+ `@carbon/ee/email-notifications.server` (`emailNotificationsEnabled`, DEGRADE);
+ `sendEmail` transactional transport stays ungated in `@carbon/lib`.
+- ✅ **Workflows** — the engine moved to `@carbon/ee/workflows`
+ (`packages/ee/src/workflows/`, was the standalone `@carbon/workflows`). Runtime gate is
+ `workflowsEnabledForCompany` in `@carbon/ee/workflows.server` (DEGRADE — a non-entitled run
+ settles Skipped, embedded in `@carbon/jobs` `engine/execute.ts`); authoring gate is
+ `requireWorkflowsEntitlement` (embedded in the ERP's `publishWorkflowVersion`). The CE-safe
+ wire contracts (`runTriggerSchema`/`RunTrigger` + the moment contract) live in the leaf
+ `@carbon/workflows-core` so `@carbon/lib` need not depend on the commercial engine — that
+ edge would be a `lib → ee → lib` cycle. (The job-side executors in
+ `packages/jobs/src/workflows/` stay in jobs — Inngest-coupled, like backups.)
+- ✅ **MCP** — protocol engine moved to `packages/ee/src/mcp/` (`@carbon/ee/mcp`
+ pure logic; `@carbon/ee/mcp.server` = `server.ts`). `createMcpServer` embeds
+ `requireEntitlement("MCP")` (route catches `EntitlementError` → 402), replacing
+ the former deletable in-route `companyHasFeature`. The dispatch, tool manifest and
+ generated `tool-metadata.json` STAY in the app (derive from `~/modules/*`) and are
+ INJECTED as `deps`. Note: `server.ts` is `@ts-nocheck`, so the live endpoint needs a
+ smoke test before merge (typecheck can't cover its body).
+- Note (context): Planning was NOT a gated feature — MRP + scheduling are now the
+ community `@carbon/planning` package.
- ⬜ Still on `requirePlan`/`companyHasPlan`, pending an architecture/policy decision
- (integrations, audit log, AI agent, workflows engine) — migrate to
- `companyHasFeature`/`requireEntitlement` + move bodies into `packages/ee` when unblocked.
+ (integrations, AI agent) — migrate to `companyHasFeature`/`requireEntitlement` + move
+ bodies into `packages/ee` when unblocked.
## Bundling gotcha — the `.server` client-graph boundary
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 0bc00092e7..8dadb51fc5 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -46,6 +46,20 @@ on deny); the nav gates it in `useSettingsSubmodules.tsx` via `usePlanGate({ fea
"BACKUPS" })` OR `isInternal`/`isLocalDev` (Demo Data still uses `localOrInternalRoutes`).
Internal = `@carbon.ms` / `@carbon.us.org`.
+`canManageBackups` is the route-level UX gate (a deletable open-code `if`). The
+un-strippable commercial LOCK is `requireBackupsEntitlement(companyId)`
+(`packages/ee/src/backups.server.ts` → `@carbon/ee/backups.server`), embedded at the
+top of every START-action durable function — `companyExportFunction`,
+`companyRestoreFunction`, `companyImportFunction` (finalize/revert are NOT gated —
+they only resolve an already-started restore, and gating them would strand a
+pending restore if entitlement lapsed). It is
+`IS_LOCAL_DEV`-exempt (the service-role job path carries no `email`, so the
+`isInternalEmail` half of the hatch cannot apply there) and otherwise
+`requireEntitlement("BACKUPS")` — Community/Starter throw. Onboarding demo-template
+apply/revert call `buildCompanyBackup`/`wipeAndLoad` DIRECTLY, and the import fn
+exempts `referencedTemplate`, so templating stays free on every edition. Do NOT push
+the check into `buildCompanyBackup`/`wipeAndLoad` — that breaks onboarding.
+
The multi-tenant caveats below are real but are NOT a cross-tenant leak in the backup
feature — every entry point is scoped to the caller's `companyId`. They were the reason
this stayed internal-only, and exposing it to customers is a deliberate product decision:
diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.md
index 9d5908b3ad..c0301f2136 100644
--- a/.claude/rules/mcp-tools-reference.md
+++ b/.claude/rules/mcp-tools-reference.md
@@ -1,14 +1,22 @@
---
paths:
- "apps/erp/app/routes/api+/mcp+/**"
+ - "packages/ee/src/mcp/**"
- "scripts/generate-mcp.ts"
---
# Carbon ERP MCP Server
The ERP exposes an MCP (Model Context Protocol) server that wraps the module
-service functions as ERP tools. It lives entirely under
-`apps/erp/app/routes/api+/mcp+/`.
+service functions as ERP tools. The **protocol engine is commercial** — it lives
+in `packages/ee/src/mcp/` (`@carbon/ee/mcp` for the pure logic —
+catalog-search/describe-format/format-result/instructions/types; `@carbon/ee/mcp.server`
+for `server.ts`, which embeds the `requireEntitlement("MCP")` lock). The **dispatch,
+tool manifest and generated metadata stay in the app** under
+`apps/erp/app/routes/api+/mcp+/` (they derive from `~/modules/*` and cannot move
+into a package) and are INJECTED into the engine as `deps` by the thin route
+(`_index.ts`): `{ callOperation, operationsByName, isListOperation, isMcpBlockedTool,
+catalogSearch, toolMetadata }`.
> Don't recreate the old per-tool dump — it goes stale instantly (it still listed
> `inventory_getShelf`, removed when `shelf` was renamed to `storageUnit`). The
@@ -32,8 +40,9 @@ service functions as ERP tools. It lives entirely under
`OPTIONS` → 204 with CORS. JSON-RPC over
`WebStandardStreamableHTTPServerTransport` (`enableJsonResponse: true`,
`sessionIdGenerator: undefined` — stateless, no session).
-- A fresh `McpServer` (`createMcpServer(ctx)`) is built per request and connected
- to a fresh transport.
+- A fresh `McpServer` (`await createMcpServer(ctx, today, deps)` from
+ `@carbon/ee/mcp.server`) is built per request and connected to a fresh transport.
+ It is async because it `await requireEntitlement("MCP")` first.
## Public discovery endpoints (unauthenticated)
@@ -73,24 +82,26 @@ Three ways in, resolved in this order:
3. **No auth** → 401 with a `WWW-Authenticate: Bearer resource_metadata=…` header
so clients can discover the OAuth flow.
-Auth always yields an `McpContext` = `{ client, companyId, companyGroupId, userId }`
-(`lib/types.ts`). `companyId`/`userId` come from the auth context and are injected
-server-side — never trusted from tool arguments.
-
-**Edition/plan gate.** The MCP server is a Business+ feature. Immediately after
-`resolveAuth`, `action` calls `companyHasFeature(ctx.client, ctx.companyId, { feature: "MCP" })`
-and returns 402 when false — one check that covers BOTH auth paths and blocks the
-**Community** edition (self-hosted) as well as Cloud **Starter** companies. This is the
-edge enforcement (the MCP server code lives in `apps/erp`, community-licensed, so there is
-no `packages/ee` body to relocate); `companyHasFeature` is the same entitlement helper the
-rest of the gated features use. The unauthenticated discovery endpoints
+Auth always yields the app's `AuthedContext` (`../v1+/lib/base.server`; a superset
+of the engine's `McpContext` in `@carbon/ee/mcp` `types.ts`). `companyId`/`userId`
+come from the auth context and are injected server-side — never trusted from tool
+arguments.
+
+**Edition/plan gate (the commercial LOCK).** The MCP server is a Business+ feature.
+The gate lives INSIDE the commercial engine: `createMcpServer` (`@carbon/ee/mcp.server`)
+`await requireEntitlement(ctx.client, ctx.companyId, "MCP")` before building the server,
+throwing `EntitlementError`, which the route catches → 402 (`makeMcpDisabledResponse`).
+One check covers BOTH auth paths and blocks the **Community** edition (self-hosted) as
+well as Cloud **Starter** companies. It is un-strippable — serving MCP requires executing
+`@carbon/ee` code — replacing the former deletable in-route `companyHasFeature` check. The
+unauthenticated discovery endpoints
(`/.well-known/mcp.json`, `/agent-setup/prompt.md`) are NOT gated — they have no company
context and only advertise the endpoint; enforcement is at `POST /api/mcp`.
## The 3 meta-tools (the ONLY tools actually registered)
To avoid context exhaustion, `server.registerTool` registers just three discovery
-tools (`lib/server.ts`); the ~1200 ERP functions are reached through them, not
+tools (`packages/ee/src/mcp/server.ts` (`@carbon/ee/mcp.server`)); the ~1200 ERP functions are reached through them, not
registered individually:
| Tool | Purpose |
@@ -99,7 +110,7 @@ registered individually:
| `describe_tool` | Full contract for one `name` or up to 10 `names`: description, permission scope, list-op marker, input schema AND response schema. |
| `call_tool` | Execute any ERP tool: `{ name, arguments }`. `arguments` may arrive as a JSON string and is normalized to an object. |
-### Catalog search (`lib/catalog-search.ts`)
+### Catalog search (`packages/ee/src/mcp/catalog-search.ts`, `@carbon/ee/mcp`)
`search_tools` runs BM25 full-text search via **zbsearch** (pnpm catalog dep;
in-process, index built lazily once per process over `tool-metadata.json`),
@@ -119,19 +130,19 @@ not substring filtering. The typed, tested logic lives OUTSIDE the
concrete names for the enum `where` filter. Filter-only calls (no `query`)
bypass the index and keep metadata order.
- Output is one line per tool — `name [READ] (requiredParams, +N optional)`
- (`formatParamSummary`, `lib/describe-format.ts`); the description line only
+ (`formatParamSummary`, `packages/ee/src/mcp/describe-format.ts`); the description line only
renders when it differs from the name-derived text
(`deriveNameDescription`). `describe_tool` output (`formatToolDescription`)
adds `Permission:` and, for list ops (`isListOperation`), the default page
size, plus the compact response schema when the generator derived one.
-- Server instructions live in `lib/instructions.ts` (module list + interpolated
+- Server instructions live in `packages/ee/src/mcp/instructions.ts` (module list + interpolated
`MCP_DEFAULT_LIMIT`), importable by tests without server.ts's auth/env chain.
- Pinned by `lib/catalog-search.test.ts` and `lib/describe-format.test.ts`;
`lib/manifest.ts` carries its own copies of the meta-tool descriptions
(pinned >40 chars by `manifest.test.ts`) — keep them in sync with
`server.ts` by hand.
-### Response formatting is token-lean BY CONTRACT (`lib/format-result.ts`)
+### Response formatting is token-lean BY CONTRACT (`packages/ee/src/mcp/format-result.ts`)
MCP text responses deliberately differ from the HTTP API's exact data — the
HTTP/agent/workflow callers of `callOperation` are untouched:
@@ -362,7 +373,7 @@ exports into the same module namespace), and writes `apps/erp/app/routes/api+/mc
(e.g. `upsertQuoteLinePrices`, `replace*Steps`, favourite toggles) is
destructive-by-omission and the client must treat it as such; everything else →
`WRITE`. Drives the MCP annotations (`READ_ONLY_/WRITE_/DESTRUCTIVE_ANNOTATIONS`
- in `lib/types.ts`).
+ in `packages/ee/src/mcp/types.ts`).
- **Description** precedence: a function-level **JSDoc** on the service export
(first sentence, `@tag`s stripped, trailing period removed, leading letter
lowercased unless it starts an acronym, capped ~160 chars —
diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.md
index b1e1f6311f..6935800b22 100644
--- a/.claude/rules/mrp-system.md
+++ b/.claude/rules/mrp-system.md
@@ -2,7 +2,7 @@
description: MRP (Material Requirements Planning) — run flow, data model, planning UI
paths:
- "packages/jobs/src/inngest/functions/scheduled/mrp.ts"
- - "packages/ee/src/planning/mrp/**"
+ - "packages/planning/src/mrp/**"
- "packages/database/supabase/functions/lib/mrp-engine.ts"
- "apps/erp/app/modules/{production,purchasing}/ui/Planning/**"
---
@@ -12,7 +12,7 @@ paths:
MRP nets demand against supply per item/location/period and projects on-hand
forward so users can create planned purchase orders (purchasing) and jobs
(production). It runs **IN-PROCESS in Node** via `runMrp` (exported from
-`@carbon/ee/planning`, source `packages/ee/src/planning/mrp/mrp.ts`), driven
+`@carbon/planning`, source `packages/planning/src/mrp/mrp.ts`), driven
either by an **Inngest** scheduled cron or a manual route POST — NOT a Supabase
edge function (the old `mrp` Deno function and its `config.toml` entry were
DELETED), and NOT Trigger.dev. `runMrp(client, db, payload)` takes an injected
@@ -63,12 +63,12 @@ Phase-7 write) and throws on failure.
`runMRP(getCarbonServiceRole(), { type: locationId ? "location" : "company",
id: locationId ?? companyId, companyId, userId })`. `runMRP` lives in
`apps/erp/app/modules/production/production.service.ts`; it dynamic-imports
- `runMrp` from `@carbon/ee/planning`, gets a Kysely handle via
+ `runMrp` from `@carbon/planning`, gets a Kysely handle via
`getSchedulingDb()`, calls `runMrp(client, db, params)` **in-process**, and
preserves the `{ data, error }` shape (catching the throw). The planning tables
submit to this via `path.to.api.mrp(locationId)`.
-3. **In-process engine** — `packages/ee/src/planning/mrp/mrp.ts`
+3. **In-process engine** — `packages/planning/src/mrp/mrp.ts`
(`runMrp(client, db, payload)`, Node, ~1130 lines). Reads go through the
injected service-role Supabase client (PostgREST); the atomic Phase-7 write
goes through the injected Kysely handle. Payload validator accepts
@@ -212,7 +212,7 @@ All join through `itemReplenishment` to expose `replenishmentSystem`, `leadTime`
## Gotchas
- The cron is **Inngest**, not Trigger.dev. There is no `apps/erp/app/trigger/mrp.ts`.
- The engine itself is in-process Node (`runMrp` from `@carbon/ee/planning`), NOT
+ The engine itself is in-process Node (`runMrp` from `@carbon/planning`), NOT
a Supabase edge function — the `mrp` Deno function was deleted.
- MRP itself writes `demandForecast`/`demandActual`/`supplyActual`/
`demandForecastSource`; it does **not** write `supplyForecast` — that comes from
diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.md
index 7f0d6dc85f..30311191ff 100644
--- a/.claude/rules/scheduling-data-structures.md
+++ b/.claude/rules/scheduling-data-structures.md
@@ -1,6 +1,6 @@
---
paths:
- - "packages/ee/src/planning/scheduling/**"
+ - "packages/planning/src/scheduling/**"
- "apps/erp/app/routes/x+/priority+/**"
- "apps/mes/app/routes/x+/operations.tsx"
- "packages/database/supabase/migrations/*schedul*.sql"
@@ -10,11 +10,11 @@ paths:
How job operations get sequenced onto work centers, scheduled with dates, and
displayed. The scheduling engine lives in
-`packages/ee/src/planning/scheduling/` (relocated from the Supabase edge runtime)
+`packages/planning/src/scheduling/` (relocated from the Supabase edge runtime)
and runs **IN-PROCESS in Node** — the ERP app (route actions,
`production.service.ts`) and `@carbon/jobs` (the replan wave, the recalculate
task) import `runLocationSchedule` / `runExpediteWhatIf` from
-**`@carbon/ee/planning`** and execute it in-process, eliminating the edge
+**`@carbon/planning`** and execute it in-process, eliminating the edge
cold-start + HTTP round-trip that made a regen take >2s on trivial data. The
`schedule` Deno **edge function** was **DELETED** — there is no remaining edge
wrapper; every caller goes through the in-process engine. Not MES,
@@ -27,15 +27,15 @@ Spec/plan: `.ai/specs/2026-08-19-schedule-in-process-node.md` +
## Where it lives
-- **Orchestration:** `packages/ee/src/planning/scheduling/run-schedule.ts`
+- **Orchestration:** `packages/planning/src/scheduling/run-schedule.ts`
(`runLocationSchedule` / `runExpediteWhatIf`) loads a **whole LOCATION's** open
jobs and runs `new SchedulingEngine(...).run()` once per job in one
deterministic forward pass (§ Engine pipeline). Every Node caller goes through
it — one orchestration, zero drift. It is exported via
- `@carbon/ee/planning`; its shared edge-lib deps are reached through the
+ `@carbon/planning`; its shared edge-lib deps are reached through the
`@carbon/database` subpath barrels (types → `@carbon/database`, postgres →
`@carbon/database/client`). Modules in
- `packages/ee/src/planning/scheduling/` (`scheduling-engine.ts`,
+ `packages/planning/src/scheduling/` (`scheduling-engine.ts`,
`dependency-manager.ts`, `date-calculator.ts`, `need-by-calculator.ts`,
`work-center-selector.ts`,
`apply-work-center-selections.ts`, `priority-calculator.ts`, `material-manager.ts`,
@@ -50,7 +50,7 @@ Spec/plan: `.ai/specs/2026-08-19-schedule-in-process-node.md` +
`slot-allocator.ts` / `apply-work-center-selections.ts` / `duration-calculator.ts` /
`date-utils.ts` / `operator-eligibility.ts` / `people-utils.ts` /
`need-by-calculator.ts` are pure and have unit
- tests (`pnpm --filter @carbon/ee test`, vitest — colocated `*.test.ts`),
+ tests (`pnpm --filter @carbon/planning test`, vitest — colocated `*.test.ts`),
alongside the determinism + envelope suites. `date-utils.toIsoDate`
normalizes pg DATE columns (JS Date at local midnight) to "YYYY-MM-DD" —
required before any lexicographic date comparison (operator expiry).
@@ -225,11 +225,11 @@ the DELETE policy needs `production_delete`.
Other whole-location regen callers now run `runLocationSchedule(...)` IN-PROCESS
(no edge invoke): `recalculateJobOperationDependencies` (`production.service.ts`,
-resolves the job's `locationId` first — it dynamic-imports `@carbon/ee/planning`
+resolves the job's `locationId` first — it dynamic-imports `@carbon/planning`
+ `@carbon/database/client` (via `getSchedulingDb`) and uses a lazy Node pool, because
`production.service.ts` is also client-bundled and must not STATICALLY pull `pg`/`.server`
code), `recalculate.ts`, `kanban.$id.tsx`, and `job/$jobId.status.tsx` (the last two are
-route actions, which CAN import `@carbon/ee/planning` + `~/services/database.server`
+route actions, which CAN import `@carbon/planning` + `~/services/database.server`
directly since React Router strips their server code from the client bundle). The
expedite what-if uses `runExpediteWhatIf`. A `functions/reschedule/` dir exists but
is legacy.
@@ -493,7 +493,7 @@ capacity-planning migration and drive the dates board's forecast/stale surfaces.
- `methodOperationOrder`: `'After Previous' | 'With Previous'` (`20240619095417_methods.sql`).
- `jobOperationStatus`: `Canceled | Done | In Progress | Paused | Ready | Todo | Waiting`.
- `deadlineType`: `No Deadline | ASAP | Soft Deadline | Hard Deadline`.
-- Engine types (`packages/ee/src/planning/scheduling/types.ts`): `enum SchedulingStrategy
+- Engine types (`packages/planning/src/scheduling/types.ts`): `enum SchedulingStrategy
{ PriorityLeastTime, LeastTime, Random }`. The `SchedulingDirection` /
`SchedulingMode` types and the `initial`/`reschedule`/`backward`/`forward` plumbing
are **deleted** — one uniform forward-ASAP rule.
diff --git a/.claude/rules/workflow-actions.md b/.claude/rules/workflow-actions.md
index e3c1ab6315..6e5b36ed0e 100644
--- a/.claude/rules/workflow-actions.md
+++ b/.claude/rules/workflow-actions.md
@@ -1,6 +1,6 @@
---
description: Workflow actions and operations — the two hand-written catalogue sources plus the entity `write` allowlists, and the job-side executors that carry them out as the workflow's owner. Read before adding an action, an operation, or anything a workflow can write or call.
-paths: ["packages/jobs/src/workflows/actions/**", "packages/workflows/src/catalog/actions.ts", "packages/workflows/src/catalog/operations.ts"]
+paths: ["packages/jobs/src/workflows/actions/**", "packages/ee/src/workflows/catalog/actions.ts", "packages/ee/src/workflows/catalog/operations.ts"]
---
# Workflow Actions and Operations
@@ -15,14 +15,14 @@ Matcher: `workflow-matcher.md`.
## Where the catalogue comes from
```
-packages/workflows/src/catalog/actions.ts HAND-WRITTEN the actions with no generic form
-packages/workflows/src/catalog/operations.ts HAND-WRITTEN read-only computations
-packages/workflows/src/catalog/entities.ts HAND-WRITTEN `write` allowlist per entity
+packages/ee/src/workflows/catalog/actions.ts HAND-WRITTEN the actions with no generic form
+packages/ee/src/workflows/catalog/operations.ts HAND-WRITTEN read-only computations
+packages/ee/src/workflows/catalog/entities.ts HAND-WRITTEN `write` allowlist per entity
│
▼ scripts/generate-workflow-catalog.ts → buildCatalog (pure)
-packages/workflows/src/catalog/actions.generated.ts COMMITTED
+packages/ee/src/workflows/catalog/actions.generated.ts COMMITTED
WORKFLOW_ACTION_CATALOG + WORKFLOW_OPERATION_CATALOG (one file, both maps)
-packages/workflows/src/catalog/labels.generated.ts COMMITTED labels for events, actions and operations
+packages/ee/src/workflows/catalog/labels.generated.ts COMMITTED labels for events, actions and operations
```
Today: **16 actions** (6 hand-written, 10 generated `<entity>.update`) and
@@ -117,7 +117,7 @@ the dispatch layer (`enrichWithAuthContext` in
## `createWorkflowServices` — the one port
-`packages/workflows/src/runtime/types.ts` declares `WorkflowServices`
+`packages/ee/src/workflows/runtime/types.ts` declares `WorkflowServices`
(`runAction`, `runOperation`, `search`). It is **required** on `RuntimeContext`,
so a missing implementation is a compile error. The pure runtime knows nothing
else about the world.
diff --git a/.claude/rules/workflow-engine.md b/.claude/rules/workflow-engine.md
index 0c1ea13a46..aaea8b4ab1 100644
--- a/.claude/rules/workflow-engine.md
+++ b/.claude/rules/workflow-engine.md
@@ -2,7 +2,7 @@
description: The workflow engine — how a queued run walks its graph, one durable step per node, acting as the workflow's owner. Read before touching the engine, the runtime evaluation layer, or anything that reads records on a running workflow's behalf.
paths:
- "packages/jobs/src/workflows/engine/**"
- - "packages/workflows/src/runtime/**"
+ - "packages/ee/src/workflows/runtime/**"
---
# Workflow Engine
@@ -17,7 +17,7 @@ Catalog: `workflow-event-catalog.md`. What the nodes actually do:
## The two halves
```
-packages/workflows/src/runtime/ pure. no I/O, no client, no database.
+packages/ee/src/workflows/runtime/ pure. no I/O, no client, no database.
values.ts RuntimeValue + fromColumn coercion
resolve.ts {kind:"ref"|"item"|"literal"|"template"} -> a value, or a reason
compare.ts operator semantics + evaluateClauses
@@ -102,7 +102,9 @@ A workflow must never be able to do something its owner could not do by hand.
## `RunTrigger` — three variants
-`runTriggerSchema` / `RunTrigger` in `packages/workflows/src/run-trigger.ts` is a three-member
+`runTriggerSchema` / `RunTrigger` lives in the CE-safe leaf `@carbon/workflows-core`
+(`packages/workflows-core/`) and is re-exported by the engine
+(`packages/ee/src/workflows/run-trigger.ts`). It is a three-member
discriminated union: `kind: "record"` (a DB row change), `kind: "moment"` (a business event),
and `kind: "schedule"` (a scheduler wake, carrying only `dueAt: string`). `triggerOutputs` in
`engine/loader.ts` returns `{}` for `"schedule"` — a scheduled run starts with no record
@@ -125,7 +127,7 @@ later read. This is what makes `before.orderTotal <= 10000` mean what it says.
- Missing data is a **skip with a reason**, not an error. A condition whose
operand cannot be resolved stops there and does **not** fall through to its
`else`.
-- `packages/workflows` is compiled by `apps/erp`, which targets **ES2019** — no
+- `packages/ee/src/workflows` is compiled by `apps/erp`, which targets **ES2019** — no
BigInt literals, and no `node:crypto` (the phase-7 builder compiles it for the
browser too). `itemKeyFor` uses `fnv1a64` from `@carbon/utils`, which is two
32-bit passes for that reason, and is shared with the storage-rules cache key.
@@ -162,7 +164,7 @@ later read. This is what makes `before.orderTotal <= 10000` mean what it says.
Nothing is stored on a node saying "repeat". An action node works through a list
when a list is wired into an input the catalog declares as taking a **single**
value. `batchCandidates` + `batchPlan` in
-`packages/workflows/src/definition/batch.ts` are the only place that rule lives,
+`packages/ee/src/workflows/definition/batch.ts` are the only place that rule lives,
so `execute.ts` and the validator cannot pick different lists. Candidates are the
action's supplied, declared-scalar inputs in **declaration order**; an input
already reading the loop item is skipped, or resolving it would recurse. Two
@@ -198,7 +200,7 @@ shows a customer a green tick.
record into the existing `${ERP_URL}/api/link?...` URL. `renderTemplate` uses it ONLY for
inputs the catalog marks `linkify` (today: the notify action's `message`), wrapping an entity
part as `[name](url)`. A webhook body has no `linkify`, so it still renders a bare
- name with no markdown. `packages/workflows` constructs no URL — it calls the callback.
+ name with no markdown. `packages/ee/src/workflows` constructs no URL — it calls the callback.
- **How a record NAMES itself in prose.** `entityText` in `runtime/resolve.ts` reads the columns
`CatalogEntity.display` lists, best first, and falls back to the raw id only when none of them
is readable. `display` is REQUIRED on every registry entry and comes from the hand-written
diff --git a/.claude/rules/workflow-event-catalog.md b/.claude/rules/workflow-event-catalog.md
index aa64a90af4..f29cedf9dd 100644
--- a/.claude/rules/workflow-event-catalog.md
+++ b/.claude/rules/workflow-event-catalog.md
@@ -1,7 +1,7 @@
---
description: The workflow catalog — four hand-written inputs generate one committed catalog of every trigger, action and operation a customer can pick; never hand-edit the generated files, and every declared moment must be raised somewhere or the build fails.
paths:
- - "packages/workflows/src/catalog/**"
+ - "packages/ee/src/workflows/catalog/**"
- "packages/lib/src/workflows/**"
- "scripts/generate-workflow-catalog.ts"
- "scripts/check-workflow-catalog.ts"
@@ -16,20 +16,20 @@ customer-facing feature (a "when this happens, do that" rule built on a canvas)
`nonConformanceWorkflow`.
Spec: `.ai/specs/2026-07-30-workflows-event-catalog.md`. Package guide:
-`packages/workflows/AGENTS.md`.
+`packages/ee/src/workflows/AGENTS.md`.
## Four hand-written inputs, three generated files
```
-packages/workflows/src/catalog/entities.ts HAND-WRITTEN record types + watched columns + write allowlist
-packages/workflows/src/catalog/moments.ts HAND-WRITTEN business events + labels + outputs
-packages/workflows/src/catalog/actions.ts HAND-WRITTEN the actions with no generic form
-packages/workflows/src/catalog/operations.ts HAND-WRITTEN read-only computations
+packages/ee/src/workflows/catalog/entities.ts HAND-WRITTEN record types + watched columns + write allowlist
+packages/ee/src/workflows/catalog/moments.ts HAND-WRITTEN business events + labels + outputs
+packages/ee/src/workflows/catalog/actions.ts HAND-WRITTEN the actions with no generic form
+packages/ee/src/workflows/catalog/operations.ts HAND-WRITTEN read-only computations
│
▼ scripts/generate-workflow-catalog.ts (buildCatalog, pure)
-packages/workflows/src/catalog/events.generated.ts COMMITTED ids, outputs, permission, match
-packages/workflows/src/catalog/actions.generated.ts COMMITTED action + operation catalogs
-packages/workflows/src/catalog/labels.generated.ts COMMITTED one msg`` per event, action and operation id
+packages/ee/src/workflows/catalog/events.generated.ts COMMITTED ids, outputs, permission, match
+packages/ee/src/workflows/catalog/actions.generated.ts COMMITTED action + operation catalogs
+packages/ee/src/workflows/catalog/labels.generated.ts COMMITTED one msg`` per event, action and operation id
```
Today: 10 triggerable entities with 77 watched columns → 97 record events, plus 9 moments
@@ -75,7 +75,7 @@ A `.changed` event hands out `record`, `before` and `after`; `created`/`deleted`
`packages/database/src/swagger-docs-schema.ts` as an **argument**. That file is already generated and committed and — unlike `types.ts` — is
a runtime *value* carrying every column's type, enum values and foreign-key target, so no
TypeScript-compiler-API parsing is needed. Injecting it keeps `@carbon/database` out of
-`@carbon/workflows`' runtime graph (it is a **devDependency, types only**) and lets the
+`@carbon/ee/workflows`' runtime graph (it is a **devDependency, types only**) and lets the
transform be unit-tested in `build.test.ts`.
Entity properties are generated from the table's own columns, minus `companyId`,
@@ -112,7 +112,7 @@ Update a/an {entity} the generated <entity>.update action
Moment, action and operation labels are hand-written and mandatory (an empty one is a
build failure from `validateCatalogInputs`).
-`packages/workflows/src` is in `lingui.config.js`'s `erp` catalog `include` and in
+`packages/ee/src/workflows` is in `lingui.config.js`'s `erp` catalog `include` and in
`//#lingui:compile`'s `inputs` in `turbo.json`. After regenerating, run
`pnpm run lingui:extract && pnpm run lingui:clean` — the clean step strips the origin
references that otherwise churn every `.po` file.
diff --git a/.claude/rules/workflow-matcher.md b/.claude/rules/workflow-matcher.md
index 4ab426bb82..426318e904 100644
--- a/.claude/rules/workflow-matcher.md
+++ b/.claude/rules/workflow-matcher.md
@@ -3,7 +3,7 @@ description: The workflow matcher — how one database announcement or business
paths:
- "packages/jobs/src/workflows/**"
- "packages/jobs/src/inngest/functions/workflows/**"
- - "packages/workflows/src/sync.ts"
+ - "packages/ee/src/workflows/sync.ts"
---
# Workflow Matcher
@@ -45,9 +45,12 @@ Kysely client is the package-wide `getJobDatabaseClient()` from `packages/jobs/s
which `events/queue.ts` and the company backup/restore tasks share.
The trigger payload (`kind: "record" | "moment"`) is declared once as `runTriggerSchema` /
-`RunTrigger` in `packages/workflows/src/run-trigger.ts` — `@carbon/workflows` is the only
-package both `@carbon/lib` (which types `carbon/workflow-run.queued` with it) and
-`@carbon/jobs` (which parses with it) already depend on.
+`RunTrigger` in the CE-safe leaf `@carbon/workflows-core` (`packages/workflows-core/`).
+`@carbon/lib` (which types `carbon/workflow-run.queued` with it) imports it type-only from
+that leaf, and `@carbon/jobs` parses with it; the commercial engine
+(`@carbon/ee/workflows`) re-exports it from the leaf (`packages/ee/src/workflows/run-trigger.ts`).
+The leaf exists precisely so `@carbon/lib` does not have to depend on the commercial engine —
+that edge would be a `lib → ee → lib` cycle.
## Announcement → event ids
@@ -87,7 +90,7 @@ person-caused firing gets `{rootRunId: null, causedByRunId: null, depth: 0, path
- **Cycle** — the candidate workflow id is already in `path` → blocked,
`"Cycle: this workflow already ran in this chain"`.
-- **Depth** — `depth >= MAX_CHAIN_DEPTH` (10, from `@carbon/workflows`) → blocked,
+- **Depth** — `depth >= MAX_CHAIN_DEPTH` (10, from `@carbon/ee/workflows`) → blocked,
`"Chain depth limit reached (10 hops)"`.
A blocked firing is **recorded as a `Blocked` workflowRun, never silently dropped** — that
@@ -116,7 +119,7 @@ replay can never double-fire:
## Subscriptions are derived, never hand-managed
-`packages/workflows/src/sync.ts` owns both levels and keeps them in one transaction:
+`packages/ee/src/workflows/sync.ts` owns both levels and keeps them in one transaction:
- `deriveWorkflowTriggerRows(nodes)` — trigger nodes → one desired `workflowTriggerEvent`
row per event id, carrying that node's origin (first origin wins on a duplicate id).
@@ -139,8 +142,8 @@ The gate inside it is `workflow.publishedVersionId` alone — set means publishe
draft and an empty desired set. The old `active` boolean was removed in migration
`20260824163808_workflow-publish-unpublish.sql`.
-**Why this lives in `@carbon/workflows` and not `@carbon/database`:** it must read
-`WORKFLOW_EVENTS`, and `@carbon/workflows` already dev-depends on `@carbon/database` — the
+**Why this lives in `@carbon/ee/workflows` and not `@carbon/database`:** it must read
+`WORKFLOW_EVENTS`, and the engine already dev-depends on `@carbon/database` — the
reverse edge is a package cycle Turborepo rejects. Kysely is imported **type-only** here
(`import type { Kysely, Transaction }`), so the package gains no runtime dependency; node-pg
serializes plain objects/arrays for the JSONB and `TEXT[]` columns, so no runtime `sql` tag
@@ -150,7 +153,7 @@ is needed.
transaction. Reconciliation reads the company's ENTIRE subscription set inside a per-workflow
transaction, so two overlapping publishes would each compute `desired` from pre-commit state and
one could delete a subscription the other still needs — silently stopping delivery for that table.
-The caller owns it because `@carbon/workflows` imports Kysely **type-only** (the package is bundled
+The caller owns it because `@carbon/ee/workflows` imports Kysely **type-only** (the package is bundled
for the browser) and cannot run raw SQL; `workflows.server.ts` supplies
`` sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}))` ``.
diff --git a/.claude/rules/workflow-run-history.md b/.claude/rules/workflow-run-history.md
index fc768d7f72..540dd006ed 100644
--- a/.claude/rules/workflow-run-history.md
+++ b/.claude/rules/workflow-run-history.md
@@ -43,7 +43,7 @@ filters `isTest = false` — a test is the author's experiment, not the workflow
## Step list ordering
`WorkflowRunSteps` builds its row list using `topologicalNodeOrder(definition)` from
-`@carbon/workflows` — trigger first, then breadth-first over edges, ties broken by position in
+`@carbon/ee/workflows` — trigger first, then breadth-first over edges, ties broken by position in
`definition.nodes`. When `definition` is null (version unreadable), falls back to the steps'
own `sequence` order and omits "Not reached" rows. A node in `order` with no step rows renders
as a greyed "Not reached" row. Step rows whose `nodeId` is not in `order` (definition changed
@@ -68,10 +68,10 @@ exists — it was dropped in definition format v3.
## The `detail` column contract
`workflowStepRun.detail` is diagnostics, never node data. It holds the per-clause condition
-evaluation written by `conditionExecutor` (`packages/workflows/src/runtime/condition.ts`) and
+evaluation written by `conditionExecutor` (`packages/ee/src/workflows/runtime/condition.ts`) and
surfaced by `ConditionDetail.tsx`. It is only set on Succeeded and Skipped nodes — Failed nodes
leave it null (the error string is what matters there, and the inputs are already in `input`).
-The `detail` JSON shape is `NodeDetail` (`packages/workflows/src/runtime/types.ts`):
+The `detail` JSON shape is `NodeDetail` (`packages/ee/src/workflows/runtime/types.ts`):
`{ kind: "condition", paths: [{ pathId, combinator, evaluations: [{ left, operator, right, passed, reason? }], taken }] }`.
## Retention — four passes, nightly at 04:00
diff --git a/AGENTS.md b/AGENTS.md
index d728695eca..188a7261ec 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -96,7 +96,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
| Revision system | `.claude/rules/revision-system.md` |
| Item supersession (phase-out / successor swaps) | `.claude/rules/supersession-system.md` |
| Kanban | `.claude/rules/kanban-system.md` |
-| Workflows (customer automation rules) | `.claude/rules/workflow-event-catalog.md` + `.claude/rules/workflow-matcher.md` + `.claude/rules/workflow-engine.md` + `packages/workflows/AGENTS.md` |
+| Workflows (customer automation rules) | `.claude/rules/workflow-event-catalog.md` + `.claude/rules/workflow-matcher.md` + `.claude/rules/workflow-engine.md` + `packages/ee/src/workflows/AGENTS.md` |
| Workflow run history + retention | `.claude/rules/workflow-run-history.md` |
| Fixed assets | `.claude/rules/fixed-asset-lifecycle.md` |
| Risk register | `.claude/rules/risk-register-module.md` |
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/configurator.md b/apps/erp/app/modules/agent/kb/docs/reference/configurator.md
index 41de1f1d10..129b903bff 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/configurator.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/configurator.md
@@ -36,7 +36,7 @@ function configure(params: Params): number {
}
```
-Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ee.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.
+Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.
Rules can also **filter** the method wholesale: a `billOfMaterial` or `billOfProcess` rule returns the list of component or operation names to keep, so a boolean parameter can drop a whole subassembly or an outside-processing step from the recipe.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/forecast.md b/apps/erp/app/modules/agent/kb/docs/reference/forecast.md
index 9d37ecd979..c25d23e628 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/forecast.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/forecast.md
@@ -12,7 +12,7 @@ A projection lives on the `demandProjection` table, keyed by item, location, and
Only **make parts** carry projections. The item picker on the form is fixed to `type="Part"` with `replenishmentSystem="Make"` (`apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx:195-202`), so you project the things you build. Their purchased components inherit demand through the BOM explosion, not through their own projection.
-Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the MRP run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/ee/src/planning/mrp/mrp.ts:918-963`). The Projections screen only ever touches `demandProjection`.
+Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the MRP run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/planning/src/mrp/mrp.ts:918-963`). The Projections screen only ever touches `demandProjection`.
## How you enter one
@@ -24,11 +24,11 @@ The grid spans 52 weeks (`WEEKS_TO_PROJECT = 12 * 4`, `apps/erp/app/routes/x+/pr
## How planning consumes it
-Planning runs in-process from `@carbon/ee/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/ee/src/planning/mrp/mrp.ts:159-161`). A projected week's full quantity drives gross demand — open production you've already planned is *not* pre-subtracted here; instead firm job and purchase-order supply is credited exactly once during the BOM explosion's running balance, so a projection you're partway to covering doesn't get double-planned.
+Planning runs in-process from `@carbon/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/planning/src/mrp/mrp.ts:159-161`). A projected week's full quantity drives gross demand — open production you've already planned is *not* pre-subtracted here; instead firm job and purchase-order supply is credited exactly once during the BOM explosion's running balance, so a projection you're partway to covering doesn't get double-planned.
-A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production (`packages/ee/src/planning/mrp/mrp.ts:430-461`). Firm job/PO supply is instead credited once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Actual **sales orders** and **job material** demand are firm too — they're added in full alongside the projection (`packages/ee/src/planning/mrp/mrp.ts:463-531`).
+A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production (`packages/planning/src/mrp/mrp.ts:430-461`). Firm job/PO supply is instead credited once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Actual **sales orders** and **job material** demand are firm too — they're added in full alongside the projection (`packages/planning/src/mrp/mrp.ts:463-531`).
-That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/ee/src/planning/mrp/mrp.ts:653-712`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts:695-753`).
+That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/planning/src/mrp/mrp.ts:653-712`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts:695-753`).
The run turns projected demand into *suggested* jobs and purchase orders. Nothing is created until you act on a suggestion. See `docs/reference/planning` for how those suggestions surface and how you convert them, and `docs/reference/reordering` for the per-part numbers (lead time, lot size, safety stock) that shape what a projection turns into.
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 4bac4836ae..308ec8f952 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -10,11 +10,11 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.
- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.
- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.
-- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/ee/src/planning/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership: these routes invoke `issue` with the service role, so the edge fn's `inventory` permission check validates the service role rather than the operator. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.
+- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` edge-fn intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, edge-fn-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split` (Deno mirror under `supabase/functions/shared/`). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Mutations go through the `batch-operations` edge function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the edge fn's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the edge fn uses ids through the same value-agnostic fold, so they always agree. The edge fn's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the edge fn is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` edge fn — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch edge-fn refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the edge fn's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one edge-fn dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership: these routes invoke `issue` with the service role, so the edge fn's `inventory` permission check validates the service role rather than the operator. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.
- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.
- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
-- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/ee/planning` (the ERP app and `@carbon/jobs` call it directly — no edge cold-start/HTTP hop; the `schedule` Deno edge function was DELETED, and the engine now lives in `packages/ee/src/planning/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/ee/src/planning/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
+- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly — no edge cold-start/HTTP hop; the `schedule` Deno edge function was DELETED, and the engine now lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.
### Job completion
@@ -86,10 +86,10 @@ pnpm --filter @carbon/erp test
- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility
- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation
- `getJobOrderStatusMap` — procurement status indicators per material
-- `recalculateJobRequirements` / `recalculateJobOperationDependencies` — recalculation after changes (`recalculateJobOperationDependencies` resolves the job's location and runs the whole-location schedule regen in-process via `runLocationSchedule` from `@carbon/ee/planning`)
+- `recalculateJobRequirements` / `recalculateJobOperationDependencies` — recalculation after changes (`recalculateJobOperationDependencies` resolves the job's location and runs the whole-location schedule regen in-process via `runLocationSchedule` from `@carbon/planning`)
- `notifyScheduleInputsChanged(companyId, kind, reason, entityId?)` — thin emitter of `carbon/schedule.inputs.changed` (kinds: `ability`/`shift`/`employee-shift`/`work-center`/`location`/`reorder`/`people`); stamps affected jobs and the debounced replan wave regenerates each stale location
- `getJobPromiseDate` — promise date = `job.projectedCompletionAt` (forward-ASAP forecast finish), null before the first regen (no operation-date fallback — `jobOperation.dueDate` is the backward need-by target, so max(op.dueDate) would just echo the job due date); returns the §7 `{ promiseDate, basis: "schedule", confidence }` contract (`confidence` "low" when the job has a conflicted op or a `scheduleOutdatedReason`, else "scheduled")
-- `runMRP(client, db, params)` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/ee/planning`; the route action passes the Kysely handle (`getDatabaseClient()` from `~/services/database.server`) — it is NEVER constructed in this service file (which is bundled for the browser via the module barrel; enforced by the `no-db-client-in-service` conformance check). `recalculateJobOperationDependencies(client, db, params)` and `getJobExpediteForecast(client, db, …)` take the handle the same way. Formerly the `mrp` Deno edge function; preserves the `{ data, error }` shape
+- `runMRP(client, db, params)` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/planning`; the route action passes the Kysely handle (`getDatabaseClient()` from `~/services/database.server`) — it is NEVER constructed in this service file (which is bundled for the browser via the module barrel; enforced by the `no-db-client-in-service` conformance check). `recalculateJobOperationDependencies(client, db, params)` and `getJobExpediteForecast(client, db, …)` take the handle the same way. Formerly the `mrp` Deno edge function; preserves the `{ data, error }` shape
- `calculateJobPriority` — computes priority from deadline type and due date
- `getJobReceiptSnapshot(db, jobId, companyId)` — a job's `quantityReceivedToInventory` plus the `trackedEntity` ids its `Job Receipt` ledger rows already posted, in ONE statement so the two can never come from different moments. Kysely because `itemLedger` is RLS-hidden from users without inventory/accounting view. Served by `api/production/job/:jobId/receipts`, read when the Complete dialog opens
- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`)
diff --git a/apps/erp/app/modules/production/forecast.server.ts b/apps/erp/app/modules/production/forecast.server.ts
index f3e9cb6827..5c08dae965 100644
--- a/apps/erp/app/modules/production/forecast.server.ts
+++ b/apps/erp/app/modules/production/forecast.server.ts
@@ -2,7 +2,7 @@ import {
type LadderShiftRow,
resolveLocationWindows,
subtractIntervals
-} from "@carbon/ee/planning";
+} from "@carbon/planning";
/** The `shift` rows returned by getShiftsWithTimes (weekday flags + times). */
type ShiftRow = {
diff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.ts
index 4984a30c38..41cc0f619c 100644
--- a/apps/erp/app/modules/production/production.mcp.server.ts
+++ b/apps/erp/app/modules/production/production.mcp.server.ts
@@ -148,7 +148,7 @@ export async function completeJob(
/**
* Schedule or reschedule a job's operations. Routes through
* `recalculateJobOperationDependencies`, which resolves the job's location and
- * regenerates the whole location IN-PROCESS via `@carbon/ee/planning`
+ * regenerates the whole location IN-PROCESS via `@carbon/planning`
* (`runLocationSchedule`) — the same in-process path the rest of the app uses now
* that the `schedule` edge function is gone. Forecast-first scheduling is a single
* forward-ASAP pass, so there are no `mode`/`direction` knobs to validate.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 86c8da5007..1d947440bb 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -979,7 +979,7 @@ export async function getJobExpediteForecast(
// Simulate-only what-if, run IN-PROCESS (Node) — persists nothing.
try {
- const { runExpediteWhatIf } = await import("@carbon/ee/planning");
+ const { runExpediteWhatIf } = await import("@carbon/planning");
const expedite = await runExpediteWhatIf({
db,
client,
@@ -2647,7 +2647,7 @@ export async function recalculateJobOperationDependencies(
// client reads the (same-company) master data; writes go through the Node
// Kysely pool.
try {
- const { runLocationSchedule } = await import("@carbon/ee/planning");
+ const { runLocationSchedule } = await import("@carbon/planning");
const data = await runLocationSchedule({
db,
client,
@@ -2716,7 +2716,7 @@ export async function runMRP(
// the PostgREST reads; the atomic Phase-7 write goes through the Node Kysely
// pool. Preserves the `{ data, error }` shape the caller (api+/mrp.ts) returns.
try {
- const { runMrp } = await import("@carbon/ee/planning");
+ const { runMrp } = await import("@carbon/planning");
const data = await runMrp(client, db, params);
return { data, error: null };
} catch (err) {
diff --git a/apps/erp/app/modules/workflows/types.ts b/apps/erp/app/modules/workflows/types.ts
index 4e21e32ce6..3a9f9c91f6 100644
--- a/apps/erp/app/modules/workflows/types.ts
+++ b/apps/erp/app/modules/workflows/types.ts
@@ -1,4 +1,4 @@
-import type { WorkflowNode } from "@carbon/workflows";
+import type { WorkflowNode } from "@carbon/ee/workflows";
import type { Edge, Node } from "@xyflow/react";
export type BuilderNode = Node<
diff --git a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
index ea4bab6a89..6f642a2ad9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/BuilderHeader.tsx
@@ -1,3 +1,4 @@
+import type { WorkflowIssue } from "@carbon/ee/workflows";
import {
Button,
Modal,
@@ -12,7 +13,6 @@ import {
TooltipTrigger,
useDisclosure
} from "@carbon/react";
-import type { WorkflowIssue } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useRef, useState } from "react";
import { LuLock, LuPencil } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/IssueList.tsx b/apps/erp/app/modules/workflows/ui/Builder/IssueList.tsx
index 36250b67af..becbd9a36e 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/IssueList.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/IssueList.tsx
@@ -1,4 +1,4 @@
-import type { WorkflowIssue } from "@carbon/workflows";
+import type { WorkflowIssue } from "@carbon/ee/workflows";
import { useReactFlow } from "@xyflow/react";
import { useNodeLabel } from "../Runs/useNodeLabel";
import { useBuilderStore } from "./context";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx b/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
index 9b15207fe8..918bf79f01 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/LiveValidation.tsx
@@ -1,4 +1,4 @@
-import { referenceIssues } from "@carbon/workflows";
+import { referenceIssues } from "@carbon/ee/workflows";
import { useEffect } from "react";
import { useWorkflowCatalog } from "./catalog";
import { useBuilderStore, useBuilderStoreApi } from "./context";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/OutputHandle.tsx b/apps/erp/app/modules/workflows/ui/Builder/OutputHandle.tsx
index 278a4cee5a..04a5a88d02 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/OutputHandle.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/OutputHandle.tsx
@@ -1,5 +1,5 @@
+import type { AvailableVariable } from "@carbon/ee/workflows";
import { Popover, PopoverAnchor, PopoverContent } from "@carbon/react";
-import type { AvailableVariable } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { Handle, Position } from "@xyflow/react";
import { useCallback, useEffect, useRef, useState } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx b/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
index 4b04c18510..34e270d27e 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/TestRun/TestRunDialog.tsx
@@ -1,3 +1,4 @@
+import type { ValueType, WorkflowIssue } from "@carbon/ee/workflows";
import {
Button,
Combobox,
@@ -12,7 +13,6 @@ import {
ModalTitle,
VStack
} from "@carbon/react";
-import type { ValueType, WorkflowIssue } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useFetcher } from "react-router";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx b/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
index 90863e6b48..31101e9789 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
@@ -1,9 +1,9 @@
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup
} from "@carbon/react";
-import type { WorkflowNodeType } from "@carbon/workflows";
import type { IsValidConnection } from "@xyflow/react";
import {
Background,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/catalog.ts b/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
index d3c22ef7c9..ac02994f85 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/catalog.ts
@@ -1,13 +1,13 @@
-import type { TermId } from "@carbon/glossary";
-import type { WorkflowCatalog } from "@carbon/workflows";
+import type { WorkflowCatalog } from "@carbon/ee/workflows";
import {
buildCatalogOverlay,
CUSTOM_FIELD_PREFIX,
createWorkflowCatalog,
parseCustomFieldEventId
-} from "@carbon/workflows";
-import { WORKFLOW_FIELD_HELP } from "@carbon/workflows/help";
-import { WORKFLOW_LABELS } from "@carbon/workflows/labels";
+} from "@carbon/ee/workflows";
+import { WORKFLOW_FIELD_HELP } from "@carbon/ee/workflows/help";
+import { WORKFLOW_LABELS } from "@carbon/ee/workflows/labels";
+import type { TermId } from "@carbon/glossary";
import { useLingui } from "@lingui/react";
import { useLingui as useLinguiMacro } from "@lingui/react/macro";
import { useMemo } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
index cd68ecb7ad..79ada2eda2 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/ClauseRow.tsx
@@ -1,7 +1,10 @@
+import type { Clause, ValueType, WorkflowIssue } from "@carbon/ee/workflows";
+import {
+ expectedClauseRightType,
+ operatorsForType
+} from "@carbon/ee/workflows";
import { Combobox, cn, IconButton } from "@carbon/react";
import type { Operator } from "@carbon/utils";
-import type { Clause, ValueType, WorkflowIssue } from "@carbon/workflows";
-import { expectedClauseRightType, operatorsForType } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import type React from "react";
import { memo, useEffect, useMemo } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/InlineNodeName.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/InlineNodeName.tsx
index 34f47f0425..d6e90007d1 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/InlineNodeName.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/InlineNodeName.tsx
@@ -1,4 +1,4 @@
-import { slugifyNodeName } from "@carbon/workflows";
+import { slugifyNodeName } from "@carbon/ee/workflows";
import { useLingui } from "@lingui/react/macro";
import { useRef, useState } from "react";
import { LuPencil } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
index 7d08929673..3eb36f71f9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx
@@ -1,3 +1,14 @@
+import type {
+ ValueOrRef,
+ ValueType,
+ WorkflowCatalog
+} from "@carbon/ee/workflows";
+import {
+ isMultiSelect,
+ MAX_LIST_ITEMS,
+ WORKFLOW_ACTION_CATALOG,
+ WORKFLOW_ENTITY_REGISTRY
+} from "@carbon/ee/workflows";
import {
Command,
CommandEmpty,
@@ -15,13 +26,6 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
-import type { ValueOrRef, ValueType, WorkflowCatalog } from "@carbon/workflows";
-import {
- isMultiSelect,
- MAX_LIST_ITEMS,
- WORKFLOW_ACTION_CATALOG,
- WORKFLOW_ENTITY_REGISTRY
-} from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuCheck, LuChevronsUpDown, LuListOrdered } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
index 6dc05b099c..de83261667 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ComputeForm.tsx
@@ -1,3 +1,5 @@
+import type { ValueOrRef } from "@carbon/ee/workflows";
+import { WORKFLOW_OPERATION_CATALOG } from "@carbon/ee/workflows";
import {
Command,
CommandEmpty,
@@ -10,8 +12,6 @@ import {
PopoverContent,
PopoverTrigger
} from "@carbon/react";
-import type { ValueOrRef } from "@carbon/workflows";
-import { WORKFLOW_OPERATION_CATALOG } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuCheck, LuChevronsUpDown, LuListOrdered } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
index 302c0f7ea9..0a5799871a 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
@@ -1,5 +1,9 @@
+import type {
+ Clause,
+ ConditionPath,
+ WorkflowIssue
+} from "@carbon/ee/workflows";
import { Button, IconButton } from "@carbon/react";
-import type { Clause, ConditionPath, WorkflowIssue } from "@carbon/workflows";
import {
closestCenter,
DndContext,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
index b3e04f3daf..5315e9d50a 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx
@@ -1,3 +1,4 @@
+import type { Clause } from "@carbon/ee/workflows";
import {
Button,
Command,
@@ -11,8 +12,6 @@ import {
PopoverContent,
PopoverTrigger
} from "@carbon/react";
-
-import type { Clause } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
import { LuChevronDown, LuPlus } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
index ef55ca042f..e911703378 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/LookupForm.tsx
@@ -1,7 +1,7 @@
+import type { Clause, LookupMatch } from "@carbon/ee/workflows";
+import { REGISTRY_ENTRIES } from "@carbon/ee/workflows";
import { Combobox, cn } from "@carbon/react";
import type { Operator } from "@carbon/utils";
-import type { Clause, LookupMatch } from "@carbon/workflows";
-import { REGISTRY_ENTRIES } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useMemo } from "react";
import { LuPlus } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
index 655ac1bf15..f0f3fa7861 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx
@@ -1,3 +1,10 @@
+import type { Origin, Schedule } from "@carbon/ee/workflows";
+import {
+ customFieldEventId,
+ ENTITY_BY_TABLE,
+ WORKFLOW_ENTITY_REGISTRY,
+ WORKFLOW_EVENTS
+} from "@carbon/ee/workflows";
import {
Command,
CommandEmpty,
@@ -20,13 +27,6 @@ import {
ToggleGroupItem
} from "@carbon/react";
import { getTimezones } from "@carbon/utils";
-import type { Origin, Schedule } from "@carbon/workflows";
-import {
- customFieldEventId,
- ENTITY_BY_TABLE,
- WORKFLOW_ENTITY_REGISTRY,
- WORKFLOW_EVENTS
-} from "@carbon/workflows";
import { getLocalTimeZone } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useMemo, useState } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts b/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
index d5080d8e37..cd813437a4 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts
@@ -2,7 +2,7 @@ import type {
WorkflowIssue,
WorkflowNode,
WorkflowNodeType
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { ComponentType } from "react";
import type { BuilderNode } from "../../../../types";
import { ActionForm } from "./ActionForm";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
index d85c66c90b..852476d3ee 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/InlineValueEditor.tsx
@@ -1,9 +1,9 @@
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
import { cn } from "@carbon/react";
import {
VariableText,
type VariableTextPart
} from "@carbon/react/VariableText";
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useRef } from "react";
import { useCustomFieldLabels } from "../catalog";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
index 19424fa372..b99a4b1aae 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/LiteralControl.tsx
@@ -1,3 +1,4 @@
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
import {
DatePicker,
Input,
@@ -14,7 +15,6 @@ import {
SelectValue,
Switch
} from "@carbon/react";
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
import { parseDate } from "@internationalized/date";
import { useLingui } from "@lingui/react/macro";
import type { KeyboardEvent, ReactNode } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx
index e76b05a1fd..9b5ebd894b 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/MultiChoiceField.tsx
@@ -1,6 +1,6 @@
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
import type { TermId } from "@carbon/glossary";
import { ChoiceSelect, type ChoiceSelectOption } from "@carbon/react";
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import { Field } from "./Field";
import { choiceState, writeChoices } from "./multiChoice";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
index 6624d4cc61..7a57720bd9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/PairsField.tsx
@@ -1,5 +1,5 @@
+import type { PairEntry, ValueOrRef } from "@carbon/ee/workflows";
import { Button, cn, IconButton, Input } from "@carbon/react";
-import type { PairEntry, ValueOrRef } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback } from "react";
import { LuPlus, LuX } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
index 8f75485a4f..71f4a9fe33 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableChip.tsx
@@ -1,6 +1,6 @@
+import type { ItemRef, VariableRef } from "@carbon/ee/workflows";
import { cn, Tooltip, TooltipContent, TooltipTrigger } from "@carbon/react";
import { VARIABLE_TEXT_CHIP_CLASS } from "@carbon/react/VariableText";
-import type { ItemRef, VariableRef } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import { LuX } from "react-icons/lu";
import { namedPath, refLabel, refLeafLabel } from "./tokenId";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableMenuPopover.tsx b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableMenuPopover.tsx
index 0978cdc056..47ebed5880 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/VariableMenuPopover.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/VariableMenuPopover.tsx
@@ -1,5 +1,5 @@
+import type { ItemRef, ValueType, VariableRef } from "@carbon/ee/workflows";
import { Popover, PopoverAnchor, PopoverContent } from "@carbon/react";
-import type { ItemRef, ValueType, VariableRef } from "@carbon/workflows";
import { useLingui } from "@lingui/react/macro";
import type { ReactNode } from "react";
import { useEffect, useRef, useState } from "react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/control.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/control.ts
index 74682a7cb5..d850e7f37b 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/control.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/control.ts
@@ -1,4 +1,4 @@
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
import { hasRecordPicker } from "./recordPickers";
/** Which control a value field renders. */
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts
index d5ebaa80ba..e2150b7bb7 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.test.ts
@@ -1,4 +1,4 @@
-import type { ValueType } from "@carbon/workflows";
+import type { ValueType } from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import { choiceState, readChoices, writeChoices } from "./multiChoice";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts
index 686525460d..a73402816d 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/multiChoice.ts
@@ -1,4 +1,4 @@
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
// The value round-trip for a multi-select input, with no React and no macro, so the
// part that decides what gets STORED can be unit-tested.
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.test.ts
index e568b7e692..b9df03d06a 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.test.ts
@@ -1,4 +1,4 @@
-import type { PairEntry, ValueOrRef } from "@carbon/workflows";
+import type { PairEntry, ValueOrRef } from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import {
addRow,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.ts
index 1d19ebddb1..70813834e5 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/pairsRows.ts
@@ -1,4 +1,4 @@
-import type { PairEntry, PairValue, ValueOrRef } from "@carbon/workflows";
+import type { PairEntry, PairValue, ValueOrRef } from "@carbon/ee/workflows";
/** A new row starts with an empty name and an empty value — never absent, because
* a row's value is not optional. Blank rows are dropped before the request goes out. */
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
index 1d069329d4..af8ccddb5d 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/tokenId.ts
@@ -1,4 +1,4 @@
-import type { ItemRef, VariableRef } from "@carbon/workflows";
+import type { ItemRef, VariableRef } from "@carbon/ee/workflows";
import { nodeNameLabel, outputLabel } from "../labelKeys";
/** The two template parts that are not plain text. */
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
index 54d6c6aee6..298d10edd3 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/types.ts
@@ -1,5 +1,5 @@
+import type { ValueOrRef, ValueType } from "@carbon/ee/workflows";
import type { TermId } from "@carbon/glossary";
-import type { ValueOrRef, ValueType } from "@carbon/workflows";
export type FieldContext = {
nodeId: string;
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
index c3fcffdb4c..6d17b60447 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/useVariableMenuData.ts
@@ -1,4 +1,4 @@
-import type { ValueType } from "@carbon/workflows";
+import type { ValueType } from "@carbon/ee/workflows";
import { useCallback, useRef } from "react";
import { useWorkflowCatalog, useWorkflowLabel } from "../catalog";
import { describeVariable } from "../labelKeys";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.test.ts
index 3dd0ec4813..f6be77e621 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.test.ts
@@ -1,5 +1,5 @@
-import type { ValueOrRef } from "@carbon/workflows";
-import { operatorsForType } from "@carbon/workflows";
+import type { ValueOrRef } from "@carbon/ee/workflows";
+import { operatorsForType } from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import { encodeTokenId } from "./tokenId";
import {
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
index a2272bb900..2f4562e0fa 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/valueParts.ts
@@ -1,5 +1,5 @@
+import type { TemplatePart, ValueOrRef } from "@carbon/ee/workflows";
import type { VariableTextPart } from "@carbon/react/VariableText";
-import type { TemplatePart, ValueOrRef } from "@carbon/workflows";
import { decodeTokenId, encodeTokenId, namedPath, refLabel } from "./tokenId";
/** What the editor shows for a stored value. Labels are resolved here and nowhere else. */
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
index c2e7e3aeef..e2ef42656f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.test.ts
@@ -1,5 +1,5 @@
-import type { AvailableVariable } from "@carbon/workflows";
-import { createWorkflowCatalog } from "@carbon/workflows";
+import type { AvailableVariable } from "@carbon/ee/workflows";
+import { createWorkflowCatalog } from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import { decodeTokenId } from "./tokenId";
import {
diff --git a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
index 3394b97db5..16d94d581f 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/fields/variableMenu.ts
@@ -3,8 +3,8 @@ import type {
ValueType,
VariableRef,
WorkflowCatalog
-} from "@carbon/workflows";
-import { canAssign, rendersAsText } from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { canAssign, rendersAsText } from "@carbon/ee/workflows";
import {
describeVariable,
nodeNameLabel,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/graph.test.ts b/apps/erp/app/modules/workflows/ui/Builder/graph.test.ts
index a2da924fb8..cba57d8fed 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/graph.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/graph.test.ts
@@ -1,9 +1,9 @@
-import type { WorkflowNodeType } from "@carbon/workflows";
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
import {
NODE_KINDS,
nodeSchema,
workflowDefinitionSchema
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import type { BuilderEdge, BuilderNode } from "../../types";
import {
diff --git a/apps/erp/app/modules/workflows/ui/Builder/graph.ts b/apps/erp/app/modules/workflows/ui/Builder/graph.ts
index aa57454ccb..2c0aeab245 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/graph.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/graph.ts
@@ -2,11 +2,11 @@ import type {
WorkflowDefinition,
WorkflowNode,
WorkflowNodeType
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import {
CURRENT_DEFINITION_FORMAT_VERSION,
nextNodeName
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { nanoid } from "nanoid";
import type { BuilderEdge, BuilderNode } from "../../types";
import { MAX_NODE_CARD_WIDTH, NODE_ACCEPTS_INCOMING } from "./nodes/kinds";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/issues.ts b/apps/erp/app/modules/workflows/ui/Builder/issues.ts
index a2a73edcdc..d11d4a35e8 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/issues.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/issues.ts
@@ -1,4 +1,4 @@
-import type { WorkflowIssue } from "@carbon/workflows";
+import type { WorkflowIssue } from "@carbon/ee/workflows";
/**
* The message for the first issue that names one of these field paths. A bad
diff --git a/apps/erp/app/modules/workflows/ui/Builder/labelKeys.ts b/apps/erp/app/modules/workflows/ui/Builder/labelKeys.ts
index f1ef064f2a..93559630e6 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/labelKeys.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/labelKeys.ts
@@ -1,4 +1,4 @@
-import type { ValueType } from "@carbon/workflows";
+import type { ValueType } from "@carbon/ee/workflows";
// Pure label helpers, kept out of `catalog.ts` so they can be imported without
// pulling in the Lingui macro (which the unit-test runner does not transform).
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx b/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
index 9e157fab7b..6f00b89a7c 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx
@@ -1,3 +1,5 @@
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
+import { FAILURE_HANDLE } from "@carbon/ee/workflows";
import {
cn,
IconButton,
@@ -5,8 +7,6 @@ import {
TooltipContent,
TooltipTrigger
} from "@carbon/react";
-import type { WorkflowNodeType } from "@carbon/workflows";
-import { FAILURE_HANDLE } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import type { NodeProps } from "@xyflow/react";
import { useConnection } from "@xyflow/react";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/index.ts b/apps/erp/app/modules/workflows/ui/Builder/nodes/index.ts
index d495b48068..deba047c62 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/index.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/index.ts
@@ -1,4 +1,4 @@
-import type { WorkflowNodeType } from "@carbon/workflows";
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
import type { NodeProps } from "@xyflow/react";
import type { ComponentType } from "react";
import { WorkflowNodeCard } from "./WorkflowNodeCard";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/kinds.ts b/apps/erp/app/modules/workflows/ui/Builder/nodes/kinds.ts
index 968ec44e18..c152a1edfd 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/kinds.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/kinds.ts
@@ -1,4 +1,4 @@
-import type { WorkflowNodeType } from "@carbon/workflows";
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
// Per-kind facts that layout and store code need. Kept apart from `meta.ts`
// because that module reaches the translation catalog, which the unit-test
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.test.ts b/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.test.ts
index e3788dfdb7..20fdb47278 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
// Stands in for the Lingui macro's compiled output: a generated hash `id` plus the
// real text on `message`. Mocking the module (not the macro) keeps this test honest
// about which field `labelText` reads.
-vi.mock("@carbon/workflows/labels", () => ({
+vi.mock("@carbon/ee/workflows/labels", () => ({
WORKFLOW_LABELS: {
"purchaseOrder.created": {
id: "U2ehIB",
diff --git a/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.ts b/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.ts
index a22bc62005..38ef11b08c 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/nodes/meta.ts
@@ -1,6 +1,6 @@
+import type { WorkflowNode, WorkflowNodeType } from "@carbon/ee/workflows";
+import { WORKFLOW_LABELS } from "@carbon/ee/workflows/labels";
import { OPERATOR_LABELS } from "@carbon/utils";
-import type { WorkflowNode, WorkflowNodeType } from "@carbon/workflows";
-import { WORKFLOW_LABELS } from "@carbon/workflows/labels";
import type { IconType } from "react-icons";
import {
LuCalculator,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/ports.test.ts b/apps/erp/app/modules/workflows/ui/Builder/ports.test.ts
index e0ba1a67ab..697b51d0f2 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/ports.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/ports.test.ts
@@ -1,5 +1,5 @@
-import type { WorkflowNodeType } from "@carbon/workflows";
-import { getNodeHandles, NODE_KINDS } from "@carbon/workflows";
+import type { WorkflowNodeType } from "@carbon/ee/workflows";
+import { getNodeHandles, NODE_KINDS } from "@carbon/ee/workflows";
import type { MessageDescriptor } from "@lingui/core";
import { describe, expect, it, vi } from "vitest";
import { createNode } from "./graph";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/ports.ts b/apps/erp/app/modules/workflows/ui/Builder/ports.ts
index 17fc0b9297..f4a2724b77 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/ports.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/ports.ts
@@ -1,10 +1,10 @@
-import type { ConditionPath, WorkflowNode } from "@carbon/workflows";
+import type { ConditionPath, WorkflowNode } from "@carbon/ee/workflows";
import {
DEFAULT_HANDLE,
FAILURE_HANDLE,
getNodeHandles,
SUCCESS_HANDLE
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { MessageDescriptor } from "@lingui/core";
import { msg } from "@lingui/core/macro";
import type { PortTone } from "./handles";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/selectors.ts b/apps/erp/app/modules/workflows/ui/Builder/selectors.ts
index 86d7c1c283..16cf19e4e5 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/selectors.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/selectors.ts
@@ -1,4 +1,4 @@
-import { REFERENCE_ISSUE_CODES } from "@carbon/workflows";
+import { REFERENCE_ISSUE_CODES } from "@carbon/ee/workflows";
import type { BuilderState } from "./store";
// Primitives and stable references only: `nodes` is replaced on every drag frame,
diff --git a/apps/erp/app/modules/workflows/ui/Builder/store.ts b/apps/erp/app/modules/workflows/ui/Builder/store.ts
index 424eca4668..fce21b33f3 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/store.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/store.ts
@@ -2,12 +2,12 @@ import type {
BatchPlan,
WorkflowIssue,
WorkflowNodeType
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import {
getNodeHandles,
slugifyNodeName,
uniqueNodeName
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { Connection, EdgeChange, NodeChange } from "@xyflow/react";
import { addEdge, applyEdgeChanges, applyNodeChanges } from "@xyflow/react";
import { nanoid } from "nanoid";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts b/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
index c233cf66f5..8159ad8336 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
+++ b/apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts
@@ -5,13 +5,13 @@ import type {
ValueType,
WorkflowCatalog,
WorkflowDefinition
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import {
availableVariables,
batchPlan,
createContext,
variablesFromHandle
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { useCallback, useMemo } from "react";
import { useWorkflowCatalog } from "./catalog";
import { useBuilderStoreApi, useBuilderStoreShallow } from "./context";
diff --git a/apps/erp/app/modules/workflows/ui/Runs/ConditionDetail.tsx b/apps/erp/app/modules/workflows/ui/Runs/ConditionDetail.tsx
index e23c55481b..2d8fa90149 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/ConditionDetail.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/ConditionDetail.tsx
@@ -1,11 +1,11 @@
-import { Subheading } from "@carbon/react";
-import { OPERATOR_LABELS } from "@carbon/utils";
import type {
Clause,
ClauseEvaluation,
ConditionNode,
NodeDetail
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { Subheading } from "@carbon/react";
+import { OPERATOR_LABELS } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import { LuCheck, LuX } from "react-icons/lu";
import { humanizeField } from "../Builder/nodes/meta";
diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
index fc2d15101f..1f0d44a4d9 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunDetail.tsx
@@ -1,6 +1,6 @@
+import { readWorkflowVersion } from "@carbon/ee/workflows";
import { Alert, AlertDescription, AlertTitle, Badge, cn } from "@carbon/react";
import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
-import { readWorkflowVersion } from "@carbon/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuCircleAlert, LuCircleSlash, LuTriangle } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunSteps.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunSteps.tsx
index 9cfa63f5cf..442f6915c9 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunSteps.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunSteps.tsx
@@ -1,5 +1,5 @@
-import type { WorkflowDefinition, WorkflowNode } from "@carbon/workflows";
-import { topologicalNodeOrder } from "@carbon/workflows";
+import type { WorkflowDefinition, WorkflowNode } from "@carbon/ee/workflows";
+import { topologicalNodeOrder } from "@carbon/ee/workflows";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuChevronDown, LuChevronRight } from "react-icons/lu";
diff --git a/apps/erp/app/modules/workflows/ui/Runs/runOutcome.test.ts b/apps/erp/app/modules/workflows/ui/Runs/runOutcome.test.ts
index 118d177a26..e0821cb414 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/runOutcome.test.ts
+++ b/apps/erp/app/modules/workflows/ui/Runs/runOutcome.test.ts
@@ -1,4 +1,4 @@
-import type { WorkflowDefinition } from "@carbon/workflows";
+import type { WorkflowDefinition } from "@carbon/ee/workflows";
import { describe, expect, it, vi } from "vitest";
import type {
WorkflowRunDetail,
diff --git a/apps/erp/app/modules/workflows/ui/Runs/runOutcome.ts b/apps/erp/app/modules/workflows/ui/Runs/runOutcome.ts
index bb8b9654d1..e66acc1bec 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/runOutcome.ts
+++ b/apps/erp/app/modules/workflows/ui/Runs/runOutcome.ts
@@ -1,4 +1,4 @@
-import type { WorkflowDefinition } from "@carbon/workflows";
+import type { WorkflowDefinition } from "@carbon/ee/workflows";
import type { WorkflowRunDetail } from "../../workflows.service";
import type { LabelFor } from "../Builder/labelKeys";
import { nodeTitle } from "../Builder/labelKeys";
@@ -37,7 +37,7 @@ function stepTitle(
/**
* One sentence describing what a run actually did. Exists because a condition
* that matches no path still ends the run `Succeeded` — see
- * `conditionExecutor` in `packages/workflows/src/runtime/condition.ts`.
+ * `conditionExecutor` in `packages/ee/src/workflows/runtime/condition.ts`.
*/
export function runOutcome(
run: Pick<WorkflowRunDetail, "status" | "error" | "statusReason">,
diff --git a/apps/erp/app/modules/workflows/ui/Runs/useNodeLabel.ts b/apps/erp/app/modules/workflows/ui/Runs/useNodeLabel.ts
index 1cb36e3208..3175b79ef5 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/useNodeLabel.ts
+++ b/apps/erp/app/modules/workflows/ui/Runs/useNodeLabel.ts
@@ -1,4 +1,4 @@
-import type { WorkflowNode } from "@carbon/workflows";
+import type { WorkflowNode } from "@carbon/ee/workflows";
import { useWorkflowLabel } from "../Builder/catalog";
import { nodeTitle } from "../Builder/labelKeys";
import { NODE_KIND_META } from "../Builder/nodes/meta";
diff --git a/apps/erp/app/modules/workflows/workflows.server.ts b/apps/erp/app/modules/workflows/workflows.server.ts
index a72a256df3..eabdafd0ea 100644
--- a/apps/erp/app/modules/workflows/workflows.server.ts
+++ b/apps/erp/app/modules/workflows/workflows.server.ts
@@ -1,14 +1,15 @@
import type { Database } from "@carbon/database";
-import { trigger } from "@carbon/jobs";
-import { getLogger } from "@carbon/logger";
-import { datetime } from "@carbon/utils";
-import type { CompanyLock, WorkflowIssue } from "@carbon/workflows";
+import type { CompanyLock, WorkflowIssue } from "@carbon/ee/workflows";
import {
createWorkflowCatalog,
readWorkflowVersion,
syncWorkflowTriggers,
validateDefinition
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { requireWorkflowsEntitlement } from "@carbon/ee/workflows.server";
+import { trigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
+import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { sql } from "kysely";
import { getDatabaseClient } from "~/services/database.server";
@@ -98,6 +99,12 @@ export async function publishWorkflowVersion(
userId: string;
}
): Promise<WorkflowSyncResult> {
+ // Commercial LOCK: publishing a workflow is what makes it live, so the
+ // entitlement check sits here inside the server path (backstopping the route's
+ // strippable `requireFeature` UX gate). Throws `EntitlementError` on a
+ // non-entitled company.
+ await requireWorkflowsEntitlement(client, companyId);
+
const version = await getWorkflowVersion(client, versionId, companyId);
if (
version.error ||
diff --git a/apps/erp/app/routes/_public+/invite.$code.tsx b/apps/erp/app/routes/_public+/invite.$code.tsx
index 8459ec9066..b3b497b7d4 100644
--- a/apps/erp/app/routes/_public+/invite.$code.tsx
+++ b/apps/erp/app/routes/_public+/invite.$code.tsx
@@ -13,8 +13,8 @@ import {
getAuthSession,
updateCompanySession
} from "@carbon/auth/session.server";
-import { insertAuditLogEntries } from "@carbon/database/audit";
import { InviteEmail } from "@carbon/documents/email";
+import { insertAuditLogEntries } from "@carbon/ee/audit.server";
import { Ratelimit, redis } from "@carbon/kv";
import { sendEmail } from "@carbon/lib/email.server";
import { getLogger } from "@carbon/logger";
diff --git a/apps/erp/app/routes/api+/audit-log.ts b/apps/erp/app/routes/api+/audit-log.ts
index 1cb357fabc..cdd26eedb3 100644
--- a/apps/erp/app/routes/api+/audit-log.ts
+++ b/apps/erp/app/routes/api+/audit-log.ts
@@ -3,7 +3,7 @@ import {
getEntityAuditLog,
isAuditLogEnabled,
syncAuditSubscriptions
-} from "@carbon/database/audit";
+} from "@carbon/ee/audit.server";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 127e050d7c..9ead82e99f 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -2,10 +2,10 @@ import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
-import { runLocationSchedule } from "@carbon/ee/planning";
import { trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
import { getLogger } from "@carbon/logger";
+import { runLocationSchedule } from "@carbon/planning";
import { Loading } from "@carbon/react";
import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index 0147c3c73b..c092b26ea2 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -1,9 +1,12 @@
+import type { ManifestEntry } from "@carbon/api";
import { hashOAuthSecret } from "@carbon/auth/auth.server";
import {
getCarbonServiceRole,
getUserScopedClient
} from "@carbon/auth/client.server";
-import { companyHasFeature } from "@carbon/ee/plan.server";
+import { EntitlementError } from "@carbon/ee/entitlements.server";
+import { createCatalogSearch } from "@carbon/ee/mcp";
+import { createMcpServer } from "@carbon/ee/mcp.server";
import { getAppUrl } from "@carbon/env";
import { Ratelimit, redis } from "@carbon/kv";
import { withLogContext } from "@carbon/logger/middleware.server";
@@ -12,8 +15,22 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
import type { ActionFunctionArgs } from "react-router";
import { getCompanyTimeZone } from "~/modules/shared/timezone.server";
import { authenticateApiKey } from "../v1+/lib/authenticate.server";
-import { createMcpServer } from "./lib/server";
-import type { McpContext } from "./lib/types";
+import type { AuthedContext } from "../v1+/lib/base.server";
+import { callOperation } from "../v1+/lib/call.server";
+import {
+ isListOperation,
+ operationsByName
+} from "../v1+/lib/operations.server";
+import { isMcpBlockedTool } from "./lib/mcp-blocked-tools";
+import toolMetadata from "./lib/tool-metadata.json";
+
+// One catalog search index for the process (built lazily on first query); the
+// MCP engine now lives in `@carbon/ee/mcp.server` and takes the dispatch, the
+// manifest and this index as injected deps — they derive from `~/modules/*` and
+// cannot move into a package.
+const catalogSearch = createCatalogSearch(
+ toolMetadata.tools as unknown as ManifestEntry[]
+);
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -111,7 +128,7 @@ function make401Response(request: Request): Response {
}
async function resolveAuth(request: Request): Promise<{
- ctx: McpContext;
+ ctx: AuthedContext;
request: Request;
}> {
const authHeader = request.headers.get("Authorization");
@@ -177,36 +194,47 @@ async function resolveAuth(request: Request): Promise<{
export async function action({ request }: ActionFunctionArgs) {
const { ctx, request: authedRequest } = await resolveAuth(request);
- // Gate the whole server behind the MCP feature (Business+). One check here
- // covers every auth path, since both resolve to an McpContext first.
- if (
- !(await companyHasFeature(ctx.client, ctx.companyId, { feature: "MCP" }))
- ) {
- return addCorsHeaders(makeMcpDisabledResponse());
- }
-
// Stamp the authenticated identity into the logging context so every log
// line in this request carries it alongside the middleware's requestId.
- const response = await withLogContext(
- { companyId: ctx.companyId, userId: ctx.userId, authKind: ctx.authKind },
- async () => {
- // The agent is told what "today" is; it has to be the company's day, not
- // the server's, or every relative-date tool call it makes lands a day off.
- const server = createMcpServer(
- ctx,
- datetime
- .today(await getCompanyTimeZone(ctx.client, ctx.companyId))
- .toString()
- );
- const transport = new WebStandardStreamableHTTPServerTransport({
- sessionIdGenerator: undefined,
- enableJsonResponse: true
- });
-
- await server.connect(transport);
- return transport.handleRequest(authedRequest);
+ let response: Response;
+ try {
+ response = await withLogContext(
+ { companyId: ctx.companyId, userId: ctx.userId, authKind: ctx.authKind },
+ async () => {
+ // The agent is told what "today" is; it has to be the company's day, not
+ // the server's, or every relative-date tool call it makes lands a day off.
+ // `createMcpServer` embeds the MCP entitlement LOCK (Business+), covering
+ // every auth path since both resolve to an authed context first — it
+ // throws `EntitlementError` for community/starter, caught below as 402.
+ const server = await createMcpServer(
+ ctx,
+ datetime
+ .today(await getCompanyTimeZone(ctx.client, ctx.companyId))
+ .toString(),
+ {
+ callOperation,
+ operationsByName,
+ isListOperation,
+ isMcpBlockedTool,
+ catalogSearch,
+ toolMetadata
+ }
+ );
+ const transport = new WebStandardStreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true
+ });
+
+ await server.connect(transport);
+ return transport.handleRequest(authedRequest);
+ }
+ );
+ } catch (err) {
+ if (err instanceof EntitlementError) {
+ return addCorsHeaders(makeMcpDisabledResponse());
}
- );
+ throw err;
+ }
return addCorsHeaders(response);
}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts
index ffd1f4ed31..984c90484d 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/catalog-search.test.ts
@@ -1,11 +1,11 @@
import type { ManifestEntry } from "@carbon/api";
-import { describe, expect, test } from "vitest";
import {
collectFieldNames,
createCatalogSearch,
expandQueryTerm,
splitWords
-} from "./catalog-search";
+} from "@carbon/ee/mcp";
+import { describe, expect, test } from "vitest";
import toolMetadata from "./tool-metadata.json";
const tools = toolMetadata.tools as unknown as ManifestEntry[];
diff --git a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
index 9dfa1a99c4..ca355a8dd3 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/describe-format.test.ts
@@ -1,13 +1,13 @@
import type { ManifestEntry } from "@carbon/api";
-import { describe, expect, test } from "vitest";
import {
deriveNameDescription,
formatParamSummary,
formatToolDescription,
+ getServerInstructions,
+ MCP_DEFAULT_LIMIT,
paginatingSibling
-} from "./describe-format";
-import { MCP_DEFAULT_LIMIT } from "./format-result";
-import { getServerInstructions } from "./instructions";
+} from "@carbon/ee/mcp";
+import { describe, expect, test } from "vitest";
import toolMetadata from "./tool-metadata.json";
const baseTool: ManifestEntry = {
@@ -134,7 +134,10 @@ describe("paginatingSibling", () => {
});
describe("getServerInstructions", () => {
- const instructions = getServerInstructions("2026-09-11");
+ const instructions = getServerInstructions(
+ "2026-09-11",
+ toolMetadata as unknown as Parameters<typeof getServerInstructions>[1]
+ );
test("lists every module name", () => {
const modules = [...new Set(toolMetadata.tools.map((t) => t.module))];
diff --git a/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts b/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts
index d28af064c5..8a80deeb45 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/format-result.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, it } from "vitest";
import {
formatMcpResult,
MCP_MAX_ROWS,
pageMcpListResult,
stripNulls
-} from "./format-result";
+} from "@carbon/ee/mcp";
+import { describe, expect, it } from "vitest";
describe("stripNulls", () => {
it("drops null and undefined object entries, recursively", () => {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 76c7a3e0d5..fc1c3605d6 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -209,7 +209,7 @@
{"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"68cb4a73d5a9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"042595348810","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"6344f0c3583c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLines","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"07d244c0f017","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLineTrackedEntities","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"51dd622ce168","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -303,7 +303,7 @@
{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"8af29a9b1929","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false},
{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"404db2e47d09","response":"none","injectAuth":"companyId+createdBy","permission":"invoicing:update","paginates":false},
- {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"042595348810","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"6344f0c3583c","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view","paginates":false},
{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create","paginates":false},
@@ -408,7 +408,7 @@
{"name":"items_findChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"10c8230a9f49","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_findOtherOpenChangeNoticesForItem","classification":"READ","paramCount":2,"schema":"8a1da983320d","response":"e0196d4b0041","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getBomHasShelfLifeManagedInput","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"7cb541e84f22","injectAuth":"companyId","permission":"parts:view","paginates":false},
- {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"042595348810","injectAuth":"companyId","permission":"parts:view","paginates":false},
+ {"name":"items_getBomItemAttributes","classification":"READ","paramCount":1,"schema":"c4ca22fd1816","response":"6344f0c3583c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNotice","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"09c0b464284c","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeActions","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"949f86b5cda3","injectAuth":"companyId","permission":"parts:view","paginates":false},
{"name":"items_getChangeNoticeAffectedItems","classification":"READ","paramCount":1,"schema":"29578070edb2","response":"5483e69d7515","injectAuth":"companyId","permission":"parts:view","paginates":false},
@@ -788,13 +788,13 @@
{"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},
{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_issueMaterial","classification":"WRITE","paramCount":7,"schema":"0408bd8c9bde","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"042595348810","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_maxToolQuantityByItem","classification":"WRITE","paramCount":1,"schema":"8b9e90037b9a","response":"6344f0c3583c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_movePeopleAssignment","classification":"DESTRUCTIVE","paramCount":2,"schema":"a726aa587ccc","response":"fe5e1dc03da5","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_movePeopleWeek","classification":"DESTRUCTIVE","paramCount":5,"schema":"fec8ebf1add4","response":"3badaa1686e8","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},
{"name":"production_notifyScheduleInputsChanged","classification":"WRITE","paramCount":3,"schema":"172bee52ed70","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"042595348810","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"2145809b536b","injectAuth":"companyId","permission":"production:update","paginates":false},
- {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"042595348810","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerRemap","classification":"WRITE","paramCount":2,"schema":"e8a18fd41775","response":"6344f0c3583c","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planAssemblyStepMarkerSync","classification":"WRITE","paramCount":2,"schema":"f32958f213ae","response":"09dcd1bcb763","injectAuth":"companyId","permission":"production:update","paginates":false},
+ {"name":"production_planOrphanStepAdoption","classification":"WRITE","paramCount":3,"schema":"aae2658d9922","response":"6344f0c3583c","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_pullJobMaterialMakeMethod","classification":"WRITE","paramCount":2,"schema":"e27f48bbab4c","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"production:update","paginates":false},
{"name":"production_reassignAssemblyStepComponents","classification":"DESTRUCTIVE","paramCount":4,"schema":"99f3d689165d","response":"none","injectAuth":"companyId","permission":"production:update","paginates":false},
{"name":"production_recalculateJobMakeMethodRequirements","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},
diff --git a/apps/erp/app/routes/api+/mcp+/lib/types.ts b/apps/erp/app/routes/api+/mcp+/lib/types.ts
deleted file mode 100644
index 914ad558fc..0000000000
--- a/apps/erp/app/routes/api+/mcp+/lib/types.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { getLogger } from "@carbon/logger";
-import type { AuthedContext } from "~/routes/api+/v1+/lib/base.server";
-
-const logger = getLogger("erp", "mcp");
-
-/** MCP runs as the same identity every Carbon API call runs as. Type-only alias —
- * erased at runtime, so no server module enters a client graph through here. */
-export type McpContext = AuthedContext;
-
-export const READ_ONLY_ANNOTATIONS = {
- readOnlyHint: true,
- destructiveHint: false,
- idempotentHint: true,
- openWorldHint: false
-} as const;
-
-export const WRITE_ANNOTATIONS = {
- readOnlyHint: false,
- destructiveHint: false,
- idempotentHint: false,
- openWorldHint: false
-} as const;
-
-export const DESTRUCTIVE_ANNOTATIONS = {
- readOnlyHint: false,
- destructiveHint: true,
- idempotentHint: true,
- openWorldHint: false
-} as const;
-
-export function withErrorHandling<T extends Record<string, unknown>>(
- handler: (params: T) => Promise<{
- content: { type: "text"; text: string }[];
- isError?: boolean;
- }>,
- fallbackMessage: string
-) {
- return async (params: T) => {
- try {
- // No info logging here — each handler logs its own invocation/result;
- // this wrapper only reports the throw path.
- return await handler(params);
- } catch (error) {
- logger.error("Error in handler", {
- fallbackMessage,
- error,
- stack: error instanceof Error ? error.stack : "No stack"
- });
- return {
- content: [
- {
- type: "text" as const,
- text: error instanceof Error ? error.message : fallbackMessage
- }
- ],
- isError: true
- };
- }
- };
-}
diff --git a/apps/erp/app/routes/api+/schedule.ts b/apps/erp/app/routes/api+/schedule.ts
index 8ca010807a..bf545a865e 100644
--- a/apps/erp/app/routes/api+/schedule.ts
+++ b/apps/erp/app/routes/api+/schedule.ts
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { runLocationSchedule } from "@carbon/ee/planning";
+import { runLocationSchedule } from "@carbon/planning";
import type { ActionFunctionArgs } from "react-router";
import { getDatabaseClient } from "~/services/database.server";
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index 4934de5741..ba681f702c 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -613,7 +613,7 @@ describe("dispatchOperation service-call contract (golden, ex-executeFunction pa
});
// The exact ids the workflow engine's create actions dispatch
-// (packages/workflows/src/catalog/actions.ts). Their results must stay readable by
+// (packages/ee/src/workflows/catalog/actions.ts). Their results must stay readable by
// create.ts's idIn(): an `id` on the returned object, or on an element of a list.
//
// The payloads are the ones runCreateAction actually builds — the catalog's
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 20596696b1..9382ae7817 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -16,8 +16,8 @@ import {
requireAuthSession,
updateCompanySession
} from "@carbon/auth/session.server";
-import { isAuditLogEnabled } from "@carbon/database/audit";
import { isApprovalRequired } from "@carbon/ee/approvals.server";
+import { isAuditLogEnabled } from "@carbon/ee/audit.server";
import { getPlan } from "@carbon/ee/plan.server";
import {
detectImplementationSignals,
diff --git a/apps/erp/app/routes/x+/acknowledge.tsx b/apps/erp/app/routes/x+/acknowledge.tsx
index 374073f927..caf9e3c997 100644
--- a/apps/erp/app/routes/x+/acknowledge.tsx
+++ b/apps/erp/app/routes/x+/acknowledge.tsx
@@ -1,7 +1,7 @@
import { ITAR_RIDER_SHA256, ITAR_RIDER_VERSION } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { insertAuditLogEntries } from "@carbon/database/audit";
+import { insertAuditLogEntries } from "@carbon/ee/audit.server";
import { getLogger } from "@carbon/logger";
import { datetime, requiresItarEntityCertification } from "@carbon/utils";
import { parseAbsolute } from "@internationalized/date";
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index 1ec04578d7..82c6aa8024 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -1,7 +1,7 @@
import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { runLocationSchedule } from "@carbon/ee/planning";
+import { runLocationSchedule } from "@carbon/planning";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@carbon/auth", () => ({
@@ -18,7 +18,7 @@ vi.mock("@carbon/auth/client.server", () => ({
vi.mock("@carbon/auth/session.server", () => ({
flash: vi.fn(async () => ({}))
}));
-vi.mock("@carbon/ee/planning", () => ({
+vi.mock("@carbon/planning", () => ({
runLocationSchedule: vi.fn()
}));
vi.mock("@carbon/logger", () => ({
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index 5321c7fd42..51375a6ce5 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -2,8 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { runLocationSchedule } from "@carbon/ee/planning";
import { getLogger } from "@carbon/logger";
+import { runLocationSchedule } from "@carbon/planning";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { cancelOpenPickingListsForJob } from "~/modules/inventory";
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx
index 7835a220ca..5ab9f85045 100644
--- a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { getGlobalAuditLog } from "@carbon/database/audit";
+import { getGlobalAuditLog } from "@carbon/ee/audit.server";
import {
Drawer,
DrawerBody,
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
index 2f10761781..c8f59ab5e6 100644
--- a/apps/erp/app/routes/x+/settings+/audit-logs.tsx
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
@@ -9,7 +9,7 @@ import {
getAuditLogArchives,
isAuditLogEnabled,
syncAuditSubscriptions
-} from "@carbon/database/audit";
+} from "@carbon/ee/audit.server";
import { requireFeature } from "@carbon/ee/plan.server";
import { Button, Heading, ScrollArea, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
diff --git a/apps/erp/app/routes/x+/settings+/companies.new.tsx b/apps/erp/app/routes/x+/settings+/companies.new.tsx
index 0fef79bd88..7d2908bc97 100644
--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx
@@ -7,7 +7,7 @@ import {
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
-import { enableAuditLog } from "@carbon/database/audit";
+import { enableAuditLog } from "@carbon/ee/audit.server";
import { validationError, validator } from "@carbon/form";
import {
Modal,
diff --git a/apps/erp/app/routes/x+/settings+/company.new.tsx b/apps/erp/app/routes/x+/settings+/company.new.tsx
index 0e6e42be30..2d84583e93 100644
--- a/apps/erp/app/routes/x+/settings+/company.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.new.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { setCompanyId } from "@carbon/auth/company.server";
import { updateCompanySession } from "@carbon/auth/session.server";
-import { enableAuditLog } from "@carbon/database/audit";
+import { enableAuditLog } from "@carbon/ee/audit.server";
import { validationError, validator } from "@carbon/form";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
diff --git a/apps/erp/app/routes/x+/users+/revoke-invite.tsx b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
index 40aed3f228..0489a6ff85 100644
--- a/apps/erp/app/routes/x+/users+/revoke-invite.tsx
+++ b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { deactivateUser } from "@carbon/auth/users.server";
-import { insertAuditLogEntries } from "@carbon/database/audit";
+import { insertAuditLogEntries } from "@carbon/ee/audit.server";
import { validationError, validator } from "@carbon/form";
import { batchTrigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
diff --git a/apps/erp/app/routes/x+/workflow+/$id.save.tsx b/apps/erp/app/routes/x+/workflow+/$id.save.tsx
index 810dadc689..374e7f0e52 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.save.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.save.tsx
@@ -2,12 +2,12 @@ import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { Json } from "@carbon/database";
import { requireFeature } from "@carbon/ee/plan.server";
-import { validationError, validator } from "@carbon/form";
-import { getLogger } from "@carbon/logger";
import {
CURRENT_DEFINITION_FORMAT_VERSION,
workflowDefinitionSchema
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import {
diff --git a/apps/erp/app/routes/x+/workflow+/$id.test-run.tsx b/apps/erp/app/routes/x+/workflow+/$id.test-run.tsx
index 61e28c8728..c3f8a5bf9d 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.test-run.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.test-run.tsx
@@ -3,9 +3,6 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { fkDisplayRegistry } from "@carbon/database/audit.config";
import { requireFeature } from "@carbon/ee/plan.server";
-import { validator } from "@carbon/form";
-import { executeManualWorkflowRun, noAccess } from "@carbon/jobs/inngest";
-import { datetime } from "@carbon/utils";
import {
CURRENT_DEFINITION_FORMAT_VERSION,
createWorkflowCatalog,
@@ -14,7 +11,10 @@ import {
validateDefinition,
type WorkflowIssue,
workflowDefinitionSchema
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { validator } from "@carbon/form";
+import { executeManualWorkflowRun, noAccess } from "@carbon/jobs/inngest";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
import { getUserClaims } from "~/modules/users/users.server";
diff --git a/apps/erp/app/routes/x+/workflow+/$id.tsx b/apps/erp/app/routes/x+/workflow+/$id.tsx
index 2c04aa48bb..94e26623bc 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { requireFeature } from "@carbon/ee/plan.server";
+import { readWorkflowVersion } from "@carbon/ee/workflows";
import {
Alert,
AlertDescription,
@@ -7,7 +8,6 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { readWorkflowVersion } from "@carbon/workflows";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { ReactFlowProvider } from "@xyflow/react";
diff --git a/apps/erp/app/routes/x+/workflow+/$id.version.new.tsx b/apps/erp/app/routes/x+/workflow+/$id.version.new.tsx
index 79fcfb06e9..724f37b491 100644
--- a/apps/erp/app/routes/x+/workflow+/$id.version.new.tsx
+++ b/apps/erp/app/routes/x+/workflow+/$id.version.new.tsx
@@ -3,8 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { Json } from "@carbon/database";
import { requireFeature } from "@carbon/ee/plan.server";
+import { CURRENT_DEFINITION_FORMAT_VERSION } from "@carbon/ee/workflows";
import { validationError, validator } from "@carbon/form";
-import { CURRENT_DEFINITION_FORMAT_VERSION } from "@carbon/workflows";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import {
diff --git a/apps/erp/app/routes/x+/workflows+/new.tsx b/apps/erp/app/routes/x+/workflows+/new.tsx
index 710817a75d..7593020599 100644
--- a/apps/erp/app/routes/x+/workflows+/new.tsx
+++ b/apps/erp/app/routes/x+/workflows+/new.tsx
@@ -3,8 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { Json } from "@carbon/database";
import { requireFeature } from "@carbon/ee/plan.server";
+import { CURRENT_DEFINITION_FORMAT_VERSION } from "@carbon/ee/workflows";
import { validationError, validator } from "@carbon/form";
-import { CURRENT_DEFINITION_FORMAT_VERSION } from "@carbon/workflows";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import {
diff --git a/apps/erp/package.json b/apps/erp/package.json
index aecce84a42..c4136d8e66 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -28,12 +28,12 @@
"@carbon/logger": "workspace:*",
"@carbon/notifications": "workspace:*",
"@carbon/onboarding": "workspace:*",
+ "@carbon/planning": "workspace:*",
"@carbon/printing": "workspace:*",
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
"@carbon/viewer": "workspace:*",
- "@carbon/workflows": "workspace:*",
"@dagrejs/dagre": "^1.1.4",
"@dnd-kit/core": "catalog:",
"@dnd-kit/sortable": "catalog:",
diff --git a/apps/mes/app/services/itar.service.ts b/apps/mes/app/services/itar.service.ts
index 17e54c0d43..9aa3743d5a 100644
--- a/apps/mes/app/services/itar.service.ts
+++ b/apps/mes/app/services/itar.service.ts
@@ -4,7 +4,7 @@
import { ITAR_RIDER_SHA256, ITAR_RIDER_VERSION } from "@carbon/auth";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
-import { insertAuditLogEntries } from "@carbon/database/audit";
+import { insertAuditLogEntries } from "@carbon/ee/audit.server";
import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
import { parseAbsolute } from "@internationalized/date";
diff --git a/docs/content/docs/reference/configurator.mdx b/docs/content/docs/reference/configurator.mdx
index 180ea1eca8..6e2a75e9f7 100644
--- a/docs/content/docs/reference/configurator.mdx
+++ b/docs/content/docs/reference/configurator.mdx
@@ -40,7 +40,7 @@ function configure(params: Params): number {
```
<Callout type="note" title="Rules run in a sandbox — keep them pure">
-Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ee.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.
+Rule code is transpiled and executed in a restricted sandbox (`packages/database/supabase/functions/lib/sandbox.ts`): no `fetch`, no `setTimeout`/`setInterval`, no dynamic `import`, no `new Promise`, no `Function` constructor. A rule that trips a banned pattern is neutered to `return null`, and any rule that throws falls back to the field's default. Rules are for deriving a value from the inputs, not for side effects.
</Callout>
Rules can also **filter** the method wholesale: a `billOfMaterial` or `billOfProcess` rule returns the list of component or operation names to keep, so a boolean parameter can drop a whole subassembly or an outside-processing step from the recipe.
diff --git a/docs/content/docs/reference/forecast.mdx b/docs/content/docs/reference/forecast.mdx
index 1548422ea9..08c05fe92f 100644
--- a/docs/content/docs/reference/forecast.mdx
+++ b/docs/content/docs/reference/forecast.mdx
@@ -14,7 +14,7 @@ A projection lives on the `demandProjection` table, keyed by item, location, and
Only **make parts** carry projections. The item picker on the form is fixed to `type="Part"` with `replenishmentSystem="Make"` (`apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx:195-202`), so you project the things you build. Their purchased components inherit demand through the BOM explosion, not through their own projection.
<Callout type="note" title="Projection, not forecast">
-Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the <Term>MRP</Term> run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/ee/src/planning/mrp/mrp.ts:918-963`). The Projections screen only ever touches `demandProjection`.
+Two tables look alike. `demandProjection` is your input — the numbers you type. `demandForecast` is planning's output — the exploded, per-component demand the <Term>MRP</Term> run writes back (`forecastMethod` = `"mrp"`). You never edit `demandForecast` by hand; it's rebuilt on every run (`packages/planning/src/mrp/mrp.ts:918-963`). The Projections screen only ever touches `demandProjection`.
</Callout>
## How you enter one
@@ -27,13 +27,13 @@ The grid spans 52 weeks (`WEEKS_TO_PROJECT = 12 * 4`, `apps/erp/app/routes/x+/pr
## How planning consumes it
-Planning runs in-process from `@carbon/ee/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/ee/src/planning/mrp/mrp.ts:159-161`). A projected week's full quantity drives gross demand — open production you've already planned is *not* pre-subtracted here; instead firm job and purchase-order supply is credited exactly once during the BOM explosion's running balance, so a projection you're partway to covering doesn't get double-planned.
+Planning runs in-process from `@carbon/planning` (`runMrp`), and it reads `demandProjection` directly as a demand source (`packages/planning/src/mrp/mrp.ts:159-161`). A projected week's full quantity drives gross demand — open production you've already planned is *not* pre-subtracted here; instead firm job and purchase-order supply is credited exactly once during the BOM explosion's running balance, so a projection you're partway to covering doesn't get double-planned.
<Callout type="note" title="Projections don't double-plan production you've already got in flight">
-A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production (`packages/ee/src/planning/mrp/mrp.ts:430-461`). Firm job/PO supply is instead credited once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Actual **sales orders** and **job material** demand are firm too — they're added in full alongside the projection (`packages/ee/src/planning/mrp/mrp.ts:463-531`).
+A projection's full `forecastQuantity` enters gross demand at face value — it is *not* pre-netted against open production (`packages/planning/src/mrp/mrp.ts:430-461`). Firm job/PO supply is instead credited once through the BOM explosion's running on-hand/supply balance, so a projection partway covered by in-flight jobs isn't planned twice. Actual **sales orders** and **job material** demand are firm too — they're added in full alongside the projection (`packages/planning/src/mrp/mrp.ts:463-531`).
</Callout>
-That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/ee/src/planning/mrp/mrp.ts:653-712`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts:695-753`).
+That projection demand joins actual demand (open sales order lines and open job materials) in the gross-demand tally, and MRP explodes each make part's method to push component demand down the BOM. The result is written to `demandForecast` and to a `demandForecastSource` lineage table that tags every unit with where it came from: `"Sales Order"`, `"Job Material"`, or `"Demand Projection"` (`packages/planning/src/mrp/mrp.ts:653-712`). On a part's planning page you can open the demand for any week and see exactly which projections, orders, and parent jobs make it up (`apps/erp/app/modules/items/items.service.ts:695-753`).
<Callout type="warning" title="MRP suggests; it never places the order">
The run turns projected demand into *suggested* jobs and purchase orders. Nothing is created until you act on a suggestion. See [Planning (MRP)](/docs/reference/planning) for how those suggestions surface and how you convert them, and [Reordering policy](/docs/reference/reordering) for the per-part numbers (lead time, lot size, safety stock) that shape what a projection turns into.
diff --git a/lingui.config.js b/lingui.config.js
index 158849babe..fe9858b85f 100644
--- a/lingui.config.js
+++ b/lingui.config.js
@@ -21,7 +21,7 @@ export default defineConfig({
"packages/printing/src/ui",
"packages/glossary/src",
"packages/onboarding/src",
- "packages/workflows/src"
+ "packages/ee/src/workflows"
],
exclude: ["**/*.server.*", "**/*.test.*", "**/*.spec.*"]
},
diff --git a/package.json b/package.json
index 5477a5c9e1..44bd055dd2 100755
--- a/package.json
+++ b/package.json
@@ -61,7 +61,7 @@
"generate:mcp": "tsx scripts/generate-mcp.ts",
"generate:swagger": "tsx scripts/generate-swagger-docs.ts && pnpm exec biome format ./packages/database/src/swagger-docs-schema.ts --write --files-max-size=20000000",
"generate:types": "tsx scripts/generate-db-types.ts",
- "generate:workflow-catalog": "tsx scripts/generate-workflow-catalog.ts && pnpm exec biome check --write packages/workflows/src/catalog/",
+ "generate:workflow-catalog": "tsx scripts/generate-workflow-catalog.ts && pnpm exec biome check --write packages/ee/src/workflows/catalog/",
"install-skills": "bash .ai/scripts/install-skills.sh",
"lingui:check": "pnpm run lingui:extract && pnpm run lingui:compile",
"lingui:clean": "node ./scripts/strip-po-headers.mjs",
diff --git a/packages/checks/package.json b/packages/checks/package.json
index f2d7006ff4..eb88f29d8d 100644
--- a/packages/checks/package.json
+++ b/packages/checks/package.json
@@ -18,7 +18,7 @@
},
"devDependencies": {
"@carbon/config": "workspace:*",
- "@carbon/workflows": "workspace:*",
+ "@carbon/ee": "workspace:*",
"@types/node": "^22",
"@types/pg": "8.15.6",
"pg": "8.20.0",
diff --git a/packages/checks/src/scripts/check-workflow-events.ts b/packages/checks/src/scripts/check-workflow-events.ts
index 45e74de420..365304bfa6 100644
--- a/packages/checks/src/scripts/check-workflow-events.ts
+++ b/packages/checks/src/scripts/check-workflow-events.ts
@@ -9,7 +9,7 @@
* catch on its own — it PARSES those ids rather than looking them up, deliberately,
* so that it stays company-blind. The existence check therefore lives here.
*/
-import { createWorkflowCatalog, REGISTRY_ENTRIES } from "@carbon/workflows";
+import { createWorkflowCatalog, REGISTRY_ENTRIES } from "@carbon/ee/workflows";
import { Client } from "pg";
const CUSTOM_FIELD_EVENT =
diff --git a/packages/checks/src/sources/typescript.ts b/packages/checks/src/sources/typescript.ts
index 4ecb844df2..fbbe02cb13 100644
--- a/packages/checks/src/sources/typescript.ts
+++ b/packages/checks/src/sources/typescript.ts
@@ -23,8 +23,8 @@ const TYPESCRIPT_ROOTS = [
"packages/files/src",
"packages/form/src",
"packages/react/src",
- "packages/printing/src",
- "packages/workflows/src"
+ "packages/printing/src"
+ // (workflows source now lives under packages/ee/src, already scanned above)
];
const EXCLUDED_DIRS = new Set(["node_modules"]);
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index eff2d8cea1..7d8b001c8b 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -51,7 +51,7 @@ pnpm --filter @carbon/database typecheck
| `./datetime` | Node re-export of `supabase/functions/lib/datetime.ts` — the edge-runtime datetime helpers (`datetime`, `getCompanyTimeZone`, `getLocationTimeZone`) for Node consumers |
| `./methods` | Node re-export of `supabase/functions/lib/methods.ts` — shared make-method helpers |
| `./logging` | Node re-export of `supabase/functions/lib/logging.ts` (`getFunctionLogger`) |
-| `./mrp-engine` | Node re-export of `supabase/functions/lib/mrp-engine.ts` (`explodeBom`, `makeKey`, `makeLocationItemKey`, `makeActualKey`, …) — the pure MRP compute engine consumed by `@carbon/ee/planning`'s `runMrp` (the engine STAYS in the edge-lib; still used by the Deno `recalculate` function) |
+| `./mrp-engine` | Node re-export of `supabase/functions/lib/mrp-engine.ts` (`explodeBom`, `makeKey`, `makeLocationItemKey`, `makeActualKey`, …) — the pure MRP compute engine consumed by `@carbon/planning`'s `runMrp` (the engine STAYS in the edge-lib; still used by the Deno `recalculate` function) |
| `./fetch-all` | Node re-export of `supabase/functions/lib/fetch-all.ts` (`fetchAll` — paginated PostgREST reads) |
| `./supersession-pick` | Node re-export of `supabase/functions/lib/supersession-pick.ts` (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) |
| `./picked-consumption` | Node re-export of `supabase/functions/lib/picked-consumption.ts` (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush |
@@ -59,7 +59,7 @@ pnpm --filter @carbon/database typecheck
| `./event` | `QueueMessage`, `EventSchema`, `createEventSystemSubscription`, `deleteEventSystemSubscription` |
| `./quality` | Inspection execution engine shared by ERP + MES (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection` — optional one-shot `requireOpen`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `getOrCreateJobOperationInspection`, pure `valuateMeasurement`); Passed/Failed/Partial are all hard-terminal and samples linked from `productionQuantity.inspectionSampleId` are locked; every fn takes a `Kysely<KyselyDatabase>` first arg — authorize at the route, see `.claude/rules/inspection-system.md` |
| `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) |
-| `./audit` | Audit-log functions (`getEntityAuditLog`, `enableAuditLog`, `syncAuditSubscriptions`, …); `auditConfig` + `AuditEntityType` come from the separate `./audit.config` subpath |
+| `./audit.config` / `./audit.types` | `auditConfig`, `AuditEntityType`, `getAuditableTableNames`, and the audit type surface. The audit ENGINE (`getEntityAuditLog`, `enableAuditLog`, `insertAuditLogEntries`, …) MOVED to the commercial `@carbon/ee/audit.server`; config + types stay here (client-safe, generic schema types consumed by CE packages) |
| `./ratelimit` | `checkApiKeyRateLimit` (Postgres RPC wrapper) |
| `./datasets` | `applyDataset(pgClient, { companyId, userId, dataset, timeZone, wipeFirst? })` — the one entry point that fills a company with an industry dataset, in a single transaction; `wipeFirst` clears prior business data inside that same transaction while preserving bootstrap config. Plus `DATASETS`, `getDataset`, `datasetKeys`, `datasetForIndustry`. Consumed by onboarding (`industry.tsx`) and the `company-template` Inngest job. See Dev Seed below |
| `./seed-workflows` | `buildSeedWorkflows` — the seeded workflow definitions (`datasets/tiers/workflow-definitions.ts`) |
diff --git a/packages/database/package.json b/packages/database/package.json
index f0570454c3..54f76260d4 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -33,7 +33,6 @@
"./sampling": "./src/sampling.ts",
"./sequence": "./src/sequence.ts",
"./seed-workflows": "./src/datasets/tiers/workflow-definitions.ts",
- "./audit": "./src/audit.ts",
"./audit.config": "./src/audit.config.ts",
"./audit.types": "./src/audit.types.ts",
"./swagger-docs-schema": "./src/swagger-docs-schema.ts",
diff --git a/packages/database/src/datetime.ts b/packages/database/src/datetime.ts
index 0e563a7818..0d39334948 100644
--- a/packages/database/src/datetime.ts
+++ b/packages/database/src/datetime.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime datetime helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/datetime.ts";
diff --git a/packages/database/src/fetch-all.ts b/packages/database/src/fetch-all.ts
index 1c1799ec4c..277def25f6 100644
--- a/packages/database/src/fetch-all.ts
+++ b/packages/database/src/fetch-all.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime fetch-all helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/fetch-all.ts";
diff --git a/packages/database/src/logging.ts b/packages/database/src/logging.ts
index 0fca6ce879..c43f09c51e 100644
--- a/packages/database/src/logging.ts
+++ b/packages/database/src/logging.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime logging helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/logging.ts";
diff --git a/packages/database/src/methods.ts b/packages/database/src/methods.ts
index e4dd261d40..03a1d98cbf 100644
--- a/packages/database/src/methods.ts
+++ b/packages/database/src/methods.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime methods helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/methods.ts";
diff --git a/packages/database/src/mrp-engine.ts b/packages/database/src/mrp-engine.ts
index 1641212e38..0c8091e314 100644
--- a/packages/database/src/mrp-engine.ts
+++ b/packages/database/src/mrp-engine.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime mrp-engine helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/mrp-engine.ts";
diff --git a/packages/database/src/supersession-pick.ts b/packages/database/src/supersession-pick.ts
index 32a7660a8e..5b6dd83a43 100644
--- a/packages/database/src/supersession-pick.ts
+++ b/packages/database/src/supersession-pick.ts
@@ -1,5 +1,5 @@
// Node-side re-export of the edge-runtime supersession-pick helper. Same bridge pattern
// as client.ts / scheduling.ts: one copy lives under supabase/functions/lib
// (imported by Deno edge functions), re-exported here for Node consumers
-// (@carbon/ee/planning, the ERP app, @carbon/jobs).
+// (@carbon/planning, the ERP app, @carbon/jobs).
export * from "../supabase/functions/lib/supersession-pick.ts";
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 8a629ffa62..d813257dc8 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -41226,6 +41226,123 @@ export default {
tags: ["documentFavorite"]
}
},
+ "/scriptRun": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.ranAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.result"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/scriptRun"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["scriptRun"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.scriptRun"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["scriptRun"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.ranAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.result"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["scriptRun"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.ranAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.scriptRun.result"
+ },
+ {
+ $ref: "#/parameters/body.scriptRun"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["scriptRun"]
+ }
+ },
"/currencies": {
get: {
parameters: [
@@ -125078,6 +125195,25 @@ export default {
},
type: "object"
},
+ scriptRun: {
+ required: ["name", "ranAt"],
+ properties: {
+ name: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ ranAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ result: {
+ format: "jsonb"
+ }
+ },
+ type: "object"
+ },
currencies: {
properties: {
id: {
@@ -171825,6 +171961,33 @@ export default {
in: "query",
type: "string"
},
+ "body.scriptRun": {
+ name: "scriptRun",
+ description: "scriptRun",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/scriptRun"
+ }
+ },
+ "rowFilter.scriptRun.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.scriptRun.ranAt": {
+ name: "ranAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.scriptRun.result": {
+ name: "result",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.currencies": {
name: "currencies",
description: "currencies",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index a352c2f55f..4f4ae05f7f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -53867,6 +53867,24 @@ export type Database = {
}
]
}
+ scriptRun: {
+ Row: {
+ name: string
+ ranAt: string
+ result: Json | null
+ }
+ Insert: {
+ name: string
+ ranAt?: string
+ result?: Json | null
+ }
+ Update: {
+ name?: string
+ ranAt?: string
+ result?: Json | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 7dfec91b6f..bfe9efe937 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -30,7 +30,7 @@ import {
import { getFunctionLogger } from "../lib/logging.ts";
import { toJson, toJsonColumns } from "../lib/json.ts";
import { KyselyDatabase } from "../lib/postgres/index.ts";
-import { importTypeScript } from "../lib/sandbox.ee.ts";
+import { importTypeScript } from "../lib/sandbox.ts";
import { getStorageUnitId } from "../lib/storage-units.ts";
import { effectiveReplenishment } from "../lib/mrp-engine.ts";
import {
diff --git a/packages/database/supabase/functions/lib/logging.ts b/packages/database/supabase/functions/lib/logging.ts
index 0224cefbfe..58c2f35716 100644
--- a/packages/database/supabase/functions/lib/logging.ts
+++ b/packages/database/supabase/functions/lib/logging.ts
@@ -32,7 +32,7 @@ function ensureConfigured(): void {
configured = true;
// Dual-runtime: this module is imported by the scheduling engine, which runs
- // BOTH in the Deno edge runtime and in-process in Node (@carbon/ee/planning,
+ // BOTH in the Deno edge runtime and in-process in Node (@carbon/planning,
// the ERP/MES apps, @carbon/jobs).
//
// ONLY the edge runtime may configure LogTape. In Node the host app already
diff --git a/packages/database/supabase/functions/lib/sandbox.ee.ts b/packages/database/supabase/functions/lib/sandbox.ts
similarity index 100%
rename from packages/database/supabase/functions/lib/sandbox.ee.ts
rename to packages/database/supabase/functions/lib/sandbox.ts
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index a352c2f55f..4f4ae05f7f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -53867,6 +53867,24 @@ export type Database = {
}
]
}
+ scriptRun: {
+ Row: {
+ name: string
+ ranAt: string
+ result: Json | null
+ }
+ Insert: {
+ name: string
+ ranAt?: string
+ result?: Json | null
+ }
+ Update: {
+ name?: string
+ ranAt?: string
+ result?: Json | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 15614c0e23..8264fbef1f 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -1,6 +1,6 @@
# @carbon/ee
-Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero, QuickBooks Online, Rillet), plan gating, RBAC authoring (permissions), Slack, email, Jira, Linear, Onshape, the shared rules layer (storage + sales rules), the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)
+Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero, QuickBooks Online, Rillet), plan gating, RBAC authoring (permissions), Slack, email, Jira, Linear, Onshape, the shared rules layer (storage + sales rules), the workflows engine, and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`. The planning engines — MRP + finite scheduling — moved OUT to the community-licensed `@carbon/planning` package; Material Planning is free.)
## Always
@@ -9,7 +9,6 @@ Enterprise edition — integrations registry (incl. Ramp), accounting sync (Xero
- MUST register server lifecycle hooks in `src/hooks.server.ts`; integration config files are shared with browser bundles.
- MUST use the operation-specific helpers from `@carbon/ee/ramp.server` for Ramp state. `patchRampSettings`, `patchRampOAuthCredentials`, `patchRampRefreshedTokens`, `patchRampConnection`, `patchRampWebhook`, and `patchRampCursor` own disjoint paths and delegate to the atomic `patchIntegrationState()` RPC boundary.
- MUST use `FEATURE_PLANS` for client and server plan gating. `companyHasPlan()` and `requirePlan()` intentionally allow non-Cloud editions and bypass-listed companies. For features that must be BLOCKED on the **Community** edition (RBAC authoring/permissions, console mode, and the entitlement-gated feature writes), use `companyHasFeature`/`requireFeature`/`requireEntitlement` instead — they return false/throw on `Edition.Community` (Enterprise/Test still pass). See `.claude/rules/commercial-licensing.md`.
-- MUST pass caller-created Supabase/Kysely clients into `runMrp()`, `runLocationSchedule()`, `runExpediteWhatIf()`, and other planning entry points.
## Ask First
@@ -37,7 +36,6 @@ pnpm --filter @carbon/ee typecheck
|---------|----------|
| `.` | Integration descriptors/registry, `defineIntegration`, and secret-resolution helpers |
| `./accounting` | `SyncFactory`, provider adapters, mappings, posting policy, reconciliation helpers |
-| `./planning` | MRP and finite-scheduling entry points; server-only in practice because they import DB code |
| `./integrations/secrets` | `patchIntegrationState`, Vault split/persist/resolve helpers, `SECRET_KEYS` |
| `./ramp.server` | Ramp client, schemas, service operations, money/coding helpers, and key-owned state patches |
| `./ramp/hooks.server` | `rampOnInstall`, `rampOnUpdate`, `rampOnUninstall`, `rampHealthcheck` |
@@ -45,12 +43,16 @@ pnpm --filter @carbon/ee typecheck
| `./plan`, `./plan.server` | Client/server edition and feature-plan gates |
| `./sso.server` | SAML connection, domain verification, session, and provisioning helpers |
| `./storage-rules`, `./storage-rules.server` | Storage-rule schemas and server operations |
+| `./workflows`, `./workflows/help`, `./workflows/labels` | The workflows engine — definition schema, normaliser, validator, generated catalog, pure runtime, and the `sync.ts` trigger/subscription reconciler (moved from `@carbon/workflows`). `./workflows/labels` (`WORKFLOW_LABELS`) is Vite-only — the `msg` macro throws in plain Node |
+| `./mcp`, `./mcp.server` | The MCP protocol engine (moved from `apps/erp/.../api+/mcp+/lib`). `./mcp` = pure logic (catalog search, formatters, instructions, types) with no auth/entitlement chain — safe for tests; `./mcp.server` = `server.ts` (`createMcpServer`, embeds `requireEntitlement("MCP")`). The dispatch + generated tool metadata stay in the app and are injected as `deps`. `server.ts` is `@ts-nocheck` |
+| `./workflows.server` | Workflows runtime lock: `workflowsEnabledForCompany(companyId)` (runtime DEGRADE — a non-entitled run settles Skipped, embedded in `@carbon/jobs` `engine/execute.ts`) and `requireWorkflowsEntitlement(client, companyId)` (authoring throw, embedded in the ERP's `publishWorkflowVersion`) |
| `./jira`, `./jira.server`, `./linear`, `./linear.server`, `./onshape`, `./paperless-parts` | Integration client/server seams |
| `./slack.server`, `./stripe-connect.server`, `./xero/hooks.server`, `./quickbooks/hooks.server`, `./rillet/hooks.server` | Integration-specific server seams |
## Key Patterns
-- **Planning** (`./planning`, `src/planning/`): the two planning engines, relocated from the Supabase edge runtime to run **in-process in Node**. `runMrp(client, db, payload)` — Material Requirements Planning (formerly the `mrp` edge function; `src/planning/mrp/mrp.ts`). `runLocationSchedule` / `runExpediteWhatIf` + the window resolvers (`resolveLocationWindows` / `resolveWorkCenterWindows` / `subtractIntervals`) — finite scheduling (formerly reached via `@carbon/database/scheduling`; `src/planning/scheduling/`). Every entry point is **dependency-injected**: a `Kysely` handle (and, for MRP, a service-role Supabase client) supplied by the caller, which authenticates first. **Server-only** — pulls in `pg`/Kysely + `@logtape`, so import from route actions, `*.service.ts`, `*.server.ts`, or `@carbon/jobs` handlers, never client code. Shared edge-lib deps are reached through `@carbon/database` subpath barrels (types → `@carbon/database`, postgres → `@carbon/database/client`, `explodeBom` → `@carbon/database/mrp-engine`).
+- **Planning** — MOVED OUT of `@carbon/ee`. MRP + finite scheduling now live in the community-licensed `@carbon/planning` package (`packages/planning/`), so Material Planning is free/CE. See `packages/planning/AGENTS.md`.
+- **Workflows** — MOVED IN to `@carbon/ee` from `@carbon/workflows`. The whole engine (definition schema, validator, generated catalog, pure runtime, `sync.ts` reconciler) is now commercial under `src/workflows/` — see `packages/ee/src/workflows/AGENTS.md` and `.claude/rules/workflow-{event-catalog,matcher,engine,actions}.md`. The lock is two seams in `./workflows.server`: `workflowsEnabledForCompany` (runtime DEGRADE, embedded in `@carbon/jobs` `engine/execute.ts`) and `requireWorkflowsEntitlement` (authoring throw, embedded in the ERP's `publishWorkflowVersion`). The CE-safe wire contracts (`runTriggerSchema`/`RunTrigger`, the moment contract `MOMENT_OUTPUT_KEYS`/`MomentKey`/`MomentEntityRef`/`MomentPayload`) live in the leaf package `@carbon/workflows-core` (`packages/workflows-core/`), which `@carbon/lib` imports type-only — that leaf is what breaks the `lib → ee → lib` cycle the move would otherwise create. The engine's `catalog/moments.ts` keeps `WORKFLOW_MOMENTS` (source of truth) and re-exports the moment TYPES from the leaf; `scripts/check-workflow-catalog.ts` asserts the two never drift.
- **Accounting sync**: class-per-entity syncers in `accounting/providers/{xero,quickbooks-online,rillet}/entities/`; `SyncFactory.getSyncer()` dispatches
- **Subscriptions are code-derived**: `accounting/core/subscriptions.ts` — `REQUIRED_SYNC_SUBSCRIPTIONS` + idempotent `ensureProviderSubscriptions()` (exported from `./accounting`), converged from the install/`onUpdate` hooks and the outbound sweep — never a write-once install artifact, never a migration backfill
- **Card charges represented once**: `accounting/core/posting.ts` and every charge syncer's `shouldSync()` must agree on `isChargeBackedCardTransaction()` so a Ramp card spend pushes as either a native charge object OR a journal entry, never both
@@ -61,11 +63,11 @@ pnpm --filter @carbon/ee typecheck
- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)
- **Rillet contact import**: the `actions` entry in `src/rillet/config.tsx` posts to `/api/integrations/rillet/import-contacts`, which fires `rillet-import-contacts` (`@carbon/jobs`). It is the only on-demand PULL of master data — `buildRilletSyncConfig` still forces customer/vendor `push-to-accounting`, and the job enqueues `pull-from-accounting` ledger rows by hand. `RilletCustomerSyncer`/`RilletVendorSyncer` implement `mapToLocal`/`upsertLocal` for it and extend `RilletEntitySyncer`; the pull rejections now live in `RilletPushOnlyEntitySyncer` (item + every transaction syncer). Importing exists to write the mapping row: `upsertRemote` reads `getRemoteId(localId)` first, so a Carbon sales invoice for an imported customer PUTs the original Rillet customer instead of creating a duplicate
- **Permissions** (`./permissions.server`, `src/permissions.server.ts`): the licensed RBAC-authoring logic, gated to Business via the `PERMISSIONS` feature. `updatePermissions` (builds/persists the flattened `userPermission.permissions` object + audit diff + claims-cache bust), `updateEmployee`, employee-type CRUD (`insert/upsert/deleteEmployeeType`, `upsertEmployeeTypePermissions`), and the translators (`makeEmptyPermissionsFromModules`, `makeCompanyPermissionsFromClaims`, `makeCompanyPermissionsFromEmployeeType`). This is the ONLY copy of `updatePermissions` — the `@carbon/jobs` `carbon/update-permissions` (bulk-edit) task imports it here. **Server-only.** The ERP authoring UI stays `.ee.tsx` in `apps/erp` (couples to `~/components/Form`); routes stay in the app and gate with `requireFeature({ feature: "PERMISSIONS" })`. The community invite primitives (`setUserPermissions`, `makePermissionsFromEmployeeType`) deliberately stay in the app's `users.server.ts`. Console/kiosk mode is a sibling: `./console.server` (`updateConsoleSetting`) provisions the protected "Console Operator" employee type + a PIN, gated by the same `PERMISSIONS` feature.
-- **Commercial entitlement pattern** (`./entitlements.server`, `./plan.server`, and the per-feature `.server` modules): `requireEntitlement(client, companyId, feature)` (throws `EntitlementError`) is embedded at the top of every commercial authoring function so the gate lives in commercial code, not a strippable open route. Feature bodies moved here with in-code gates: `./approvals` (approval rules), `./rules.server` (sales + storage rules), `./api-keys.server`, `./webhooks.server`, `./two-factor.server` (the `requireMfa` policy), `./forecast.server` (demand forecasts + projections), `./customer-portals.server`, plus permissions/console above. Runtime paths that must degrade (not throw) use `companyHasFeature` (e.g. email notifications, webhook delivery). Full rationale: `.claude/rules/commercial-licensing.md`.
+- **Commercial entitlement pattern** (`./entitlements.server`, `./plan.server`, and the per-feature `.server` modules): `requireEntitlement(client, companyId, feature)` (throws `EntitlementError`) is embedded at the top of every commercial authoring function so the gate lives in commercial code, not a strippable open route. Feature bodies moved here with in-code gates: `./approvals` (approval rules), `./rules.server` (sales + storage rules), `./api-keys.server`, `./webhooks.server`, `./two-factor.server` (the `requireMfa` policy), `./forecast.server` (demand forecasts + projections), `./customer-portals.server`, `./audit.server` (the audit-log engine — `enableAuditLog` embeds `requireEntitlement("AUDIT_LOG")`, skipped under `CONTROLLED_ENVIRONMENT` where audit is mandatory; `auditConfig`/types stay client-safe in `@carbon/database`), `./email-notifications.server` (`emailNotificationsEnabled` — the EMAIL notification-channel gate, runtime DEGRADE; `sendEmail` transactional transport stays ungated in `@carbon/lib`), `./backups.server` (`requireBackupsEntitlement(companyId)` — embedded at the top of the Inngest backup/restore/import durable functions in `@carbon/jobs`, `IS_LOCAL_DEV`-exempt; the engine is Inngest-coupled and stays in jobs), plus permissions/console above. Runtime paths that must degrade (not throw) use `companyHasFeature` (e.g. email notifications, webhook delivery). Full rationale: `.claude/rules/commercial-licensing.md`.
- **Ramp state helpers**: `src/ramp/lib/service.ts` is a compatibility facade. Put connection/auth in `connection.ts`, coding masters in `chart-of-accounts.ts`/`cost-centers.ts`, parties in `suppliers.ts`, PO/bill transport in `spend.ts`, confirms in `sync-confirmation.ts`, remote webhook lifecycle in `webhooks.ts`, and metadata/Vault writes in `state.ts`; `@carbon/ee/ramp.server` remains stable
- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions
- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`
-- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, etc.
+- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, etc.
## Cross-References
diff --git a/packages/ee/LICENSE b/packages/ee/LICENSE
index 15ffc956d9..eb50df567e 100644
--- a/packages/ee/LICENSE
+++ b/packages/ee/LICENSE
@@ -23,7 +23,8 @@ described in the LICENSE file at the root of the repository.
whether signed, purchased online, or accepted by click-through. Your use
must stay within what that agreement allows. The execution of the
Enterprise files by Carbon's AGPLv3-licensed code solely for the purpose
- of determining the existence or validity of a commercial license shall
+ of determining the existence or validity of a commercial license, or
+ otherwise without making any Enterprise functionality available, shall
not, by itself, constitute use of the Enterprise files under this
Section 2.
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 644e89ec80..b75a1356a3 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -8,11 +8,15 @@
"./api-keys.server": "./src/api-keys.server.ts",
"./approvals": "./src/approvals/index.ts",
"./approvals.server": "./src/approvals/service.ts",
+ "./audit.server": "./src/audit/audit.ts",
+ "./backups.server": "./src/backups.server.ts",
"./console.server": "./src/console.server.ts",
"./customer-portals.server": "./src/customer-portals.server.ts",
+ "./email-notifications.server": "./src/email-notifications/deliver.server.ts",
"./entitlements.server": "./src/entitlements.server.ts",
"./forecast.server": "./src/forecast.server.ts",
- "./planning": "./src/planning/index.ts",
+ "./mcp": "./src/mcp/index.ts",
+ "./mcp.server": "./src/mcp/server.ts",
"./integrations/secrets": "./src/integrations/secrets.ts",
"./action-task-entity": "./src/lib/actionTaskEntity.ts",
"./rules": "./src/rules/index.ts",
@@ -38,7 +42,11 @@
"./xero/hooks.server": "./src/xero/hooks.server.ts",
"./stripe-connect.server": "./src/stripe-connect/payment.server.ts",
"./two-factor.server": "./src/two-factor.server.ts",
- "./webhooks.server": "./src/webhooks.server.ts"
+ "./webhooks.server": "./src/webhooks.server.ts",
+ "./workflows": "./src/workflows/index.ts",
+ "./workflows.server": "./src/workflows.server.ts",
+ "./workflows/help": "./src/workflows/catalog/help.generated.ts",
+ "./workflows/labels": "./src/workflows/catalog/labels.generated.ts"
},
"private": true,
"scripts": {
@@ -60,7 +68,10 @@
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
+ "@carbon/workflows-core": "workspace:*",
"@internationalized/date": "catalog:",
+ "@lingui/core": "catalog:",
+ "@modelcontextprotocol/sdk": "1.29.0",
"@slack/bolt": "4.4.0",
"@slack/oauth": "3.0.5",
"@slack/types": "2.20.1",
@@ -81,11 +92,14 @@
"sst": "catalog:",
"supabase": "catalog:",
"tsup": "catalog:",
+ "zbsearch": "catalog:",
"zod": "catalog:",
"zod-form-data": "catalog:"
},
"devDependencies": {
+ "@carbon/api": "workspace:*",
"@carbon/config": "workspace:*",
+ "@carbon/glossary": "workspace:*",
"@logtape/logtape": "catalog:",
"@logtape/testing": "catalog:",
"@types/nodemailer": "6.4.21",
diff --git a/packages/database/src/audit.ts b/packages/ee/src/audit/audit.ts
similarity index 93%
rename from packages/database/src/audit.ts
rename to packages/ee/src/audit/audit.ts
index cf5ebcd4d5..6bd463c8d8 100644
--- a/packages/database/src/audit.ts
+++ b/packages/ee/src/audit/audit.ts
@@ -1,16 +1,22 @@
-import type { SupabaseClient } from "@supabase/supabase-js";
-import { auditConfig, getAuditableTableNames } from "./audit.config.ts";
+import type { Database } from "@carbon/database";
+import {
+ auditConfig,
+ getAuditableTableNames
+} from "@carbon/database/audit.config";
import type {
AuditLogArchive,
AuditLogEntry,
AuditLogFilters,
AuditLogResponse,
CreateAuditLogEntry
-} from "./audit.types.ts";
+} from "@carbon/database/audit.types";
import {
createEventSystemSubscription,
deleteEventSystemSubscriptionsByName
-} from "./event.ts";
+} from "@carbon/database/event";
+import { CONTROLLED_ENVIRONMENT } from "@carbon/env";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "../entitlements.server";
// Type for Supabase client with our custom RPC functions
type AuditRpcClient = {
@@ -232,6 +238,20 @@ export async function enableAuditLog(
client: SupabaseClient,
companyId: string
): Promise<void> {
+ // The commercial LOCK. Enabling audit logging is a Business feature, so the
+ // entitlement check lives here inside `@carbon/ee` (not a strippable open
+ // route). CONTROLLED_ENVIRONMENT (ITAR/CUI) audit is mandatory and
+ // non-disableable — it must never be blocked by entitlement, so the gate is
+ // skipped there (a controlled deployment is Enterprise edition and would pass
+ // `companyHasFeature` anyway; this is belt-and-suspenders).
+ if (!CONTROLLED_ENVIRONMENT) {
+ await requireEntitlement(
+ client as unknown as SupabaseClient<Database>,
+ companyId,
+ "AUDIT_LOG"
+ );
+ }
+
// Create the per-company audit log table
const { error: createError } = await (
client as unknown as AuditRpcClient
diff --git a/packages/ee/src/backups.server.ts b/packages/ee/src/backups.server.ts
new file mode 100644
index 0000000000..81265eb05b
--- /dev/null
+++ b/packages/ee/src/backups.server.ts
@@ -0,0 +1,28 @@
+import { IS_LOCAL_DEV } from "@carbon/auth";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { requireEntitlement } from "./entitlements.server";
+
+/**
+ * The un-strippable BACKUPS lock. Embedded at the top of every durable
+ * backup / restore / import function in `@carbon/jobs` so that RUNNING a backup
+ * requires executing this commercial code — the route-level `canManageBackups`
+ * gate (`apps/erp`) is the friendly UX gate this backstops, and a future direct
+ * `trigger()` cannot route around it.
+ *
+ * Local dev is exempt: the durable functions run with a service-role client and
+ * no `email`, so the internal-staff hatch (`canAccessBackups` = `IS_LOCAL_DEV ||
+ * isInternalEmail`) cannot be evaluated here — `IS_LOCAL_DEV` preserves the dev
+ * workflow, and `companyHasFeature` still passes for Enterprise/Test self-hosted,
+ * bypass-listed, and carbon-owned companies. Community/Starter are blocked.
+ *
+ * Onboarding's demo-template apply/revert call `buildCompanyBackup` /
+ * `wipeAndLoad` DIRECTLY (not these gated functions), so templating stays
+ * available on every edition — do NOT push this check down into those engine
+ * helpers.
+ */
+export async function requireBackupsEntitlement(
+ companyId: string
+): Promise<void> {
+ if (IS_LOCAL_DEV) return;
+ await requireEntitlement(getCarbonServiceRole(), companyId, "BACKUPS");
+}
diff --git a/packages/ee/src/email-notifications/deliver.server.ts b/packages/ee/src/email-notifications/deliver.server.ts
new file mode 100644
index 0000000000..5d61a162fa
--- /dev/null
+++ b/packages/ee/src/email-notifications/deliver.server.ts
@@ -0,0 +1,27 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { companyHasFeature } from "../plan.server";
+
+/**
+ * Commercial gate for the EMAIL notification channel. The notification fan-out
+ * (`@carbon/jobs` `notify`) calls this to decide whether to deliver email;
+ * in-app and Slack channels are unaffected. This is a runtime DEGRADE path — it
+ * returns a boolean rather than throwing, so a company without the feature
+ * simply skips email rather than failing the whole notification.
+ *
+ * The point of it living here (not as an inline `companyHasFeature(...,
+ * "EMAIL_NOTIFICATIONS")` in community `@carbon/jobs`) is that the feature key
+ * and the gate decision sit on the COMMERCIAL side of the license boundary:
+ * removing the lock requires editing `@carbon/ee`, not deleting an `if` in
+ * open-licensed code. Generic transactional email (invites, password/MFA,
+ * onboarding) goes through `@carbon/lib` `sendEmail` and is deliberately NOT
+ * gated here.
+ */
+export async function emailNotificationsEnabled(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<boolean> {
+ return companyHasFeature(client, companyId, {
+ feature: "EMAIL_NOTIFICATIONS"
+ });
+}
diff --git a/apps/erp/app/routes/api+/mcp+/lib/catalog-search.ts b/packages/ee/src/mcp/catalog-search.ts
similarity index 100%
rename from apps/erp/app/routes/api+/mcp+/lib/catalog-search.ts
rename to packages/ee/src/mcp/catalog-search.ts
diff --git a/apps/erp/app/routes/api+/mcp+/lib/describe-format.ts b/packages/ee/src/mcp/describe-format.ts
similarity index 100%
rename from apps/erp/app/routes/api+/mcp+/lib/describe-format.ts
rename to packages/ee/src/mcp/describe-format.ts
diff --git a/apps/erp/app/routes/api+/mcp+/lib/format-result.ts b/packages/ee/src/mcp/format-result.ts
similarity index 100%
rename from apps/erp/app/routes/api+/mcp+/lib/format-result.ts
rename to packages/ee/src/mcp/format-result.ts
diff --git a/packages/ee/src/mcp/index.ts b/packages/ee/src/mcp/index.ts
new file mode 100644
index 0000000000..8490087778
--- /dev/null
+++ b/packages/ee/src/mcp/index.ts
@@ -0,0 +1,10 @@
+// The PURE MCP logic (`@carbon/ee/mcp`): catalog search, result/description
+// formatting, connect-time instructions, and the shared types. It pulls in NO
+// auth/entitlement chain, so tests and the app route can import these helpers
+// without loading the server (`@carbon/ee/mcp.server` → `server.ts`, which embeds
+// the `requireEntitlement` lock and its heavier dependency graph).
+export * from "./catalog-search";
+export * from "./describe-format";
+export * from "./format-result";
+export * from "./instructions";
+export * from "./types";
diff --git a/apps/erp/app/routes/api+/mcp+/lib/instructions.ts b/packages/ee/src/mcp/instructions.ts
similarity index 78%
rename from apps/erp/app/routes/api+/mcp+/lib/instructions.ts
rename to packages/ee/src/mcp/instructions.ts
index 8f5e1ac826..6bb5599e2b 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/instructions.ts
+++ b/packages/ee/src/mcp/instructions.ts
@@ -1,20 +1,30 @@
// The MCP server's connect-time instructions, in their own module so they are
-// testable without server.ts's import chain (callOperation → auth → env).
+// testable without server.ts's import chain (callOperation → auth → env). The
+// tool catalog is passed in (the generated `tool-metadata.json` lives in the app,
+// derived from its `~/modules/*`), never imported here.
+import type { ManifestEntry } from "@carbon/api";
import { MCP_DEFAULT_LIMIT } from "./format-result";
-import toolMetadata from "./tool-metadata.json";
-const MODULE_NAMES = [
- ...new Set(toolMetadata.tools.map((tool) => tool.module))
-].sort();
+export type ToolCatalogSummary = {
+ tools: Pick<ManifestEntry, "module">[];
+ totalTools: number;
+ modules: number;
+};
-export function getServerInstructions(today: string): string {
+export function getServerInstructions(
+ today: string,
+ toolMetadata: ToolCatalogSummary
+): string {
+ const moduleNames = [
+ ...new Set(toolMetadata.tools.map((tool) => tool.module))
+ ].sort();
return `Carbon ERP Manufacturing System
==========================================
Date: ${today}
IMPORTANT: Tool Discovery System
This server has ${toolMetadata.totalTools} tools available across ${toolMetadata.modules} modules:
-${MODULE_NAMES.join(", ")}
+${moduleNames.join(", ")}
To prevent context exhaustion, tools are loaded on-demand using call_tool.
diff --git a/apps/erp/app/routes/api+/mcp+/lib/server.ts b/packages/ee/src/mcp/server.ts
similarity index 78%
rename from apps/erp/app/routes/api+/mcp+/lib/server.ts
rename to packages/ee/src/mcp/server.ts
index 671607988f..58b382f03f 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/server.ts
+++ b/packages/ee/src/mcp/server.ts
@@ -1,54 +1,73 @@
// @ts-nocheck
import { getLogger } from "@carbon/logger";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
-import type { McpContext } from "./types";
import { z } from "zod";
-import { withErrorHandling, READ_ONLY_ANNOTATIONS, WRITE_ANNOTATIONS } from "./types";
-import toolMetadata from "./tool-metadata.json";
-import { isMcpBlockedTool } from "./mcp-blocked-tools";
-import { callOperation } from "../../v1+/lib/call.server";
-import {
- isListOperation,
- operationsByName
-} from "../../v1+/lib/operations.server";
-import {
- formatMcpResult,
- MCP_DEFAULT_LIMIT,
- pageMcpListResult
-} from "./format-result";
-import { createCatalogSearch } from "./catalog-search";
+import { requireEntitlement } from "../entitlements.server";
import {
deriveNameDescription,
formatParamSummary,
formatToolDescription,
paginatingSibling
} from "./describe-format";
+import {
+ formatMcpResult,
+ MCP_DEFAULT_LIMIT,
+ pageMcpListResult
+} from "./format-result";
import { getServerInstructions } from "./instructions";
+import {
+ type McpContext,
+ type McpServerDeps,
+ READ_ONLY_ANNOTATIONS,
+ WRITE_ANNOTATIONS,
+ withErrorHandling
+} from "./types";
const logger = getLogger("erp", "mcp");
-// One index for the process; createMcpServer runs per request.
-const catalogSearch = createCatalogSearch(toolMetadata.tools);
+// The MCP protocol server — the commercial feature body. The app's dispatch,
+// tool manifest, blocked-tool predicate and generated catalog are INJECTED via
+// `deps` (they derive from `apps/erp`'s `~/modules/*` and cannot move into a
+// package); the entitlement LOCK lives here so serving MCP requires executing
+// commercial code. `Ctx` is the caller's full auth context (the app's
+// `AuthedContext`), passed straight through to `deps.callOperation`.
+export async function createMcpServer<Ctx extends McpContext>(
+ ctx: Ctx,
+ today: string,
+ deps: McpServerDeps<Ctx>
+): Promise<McpServer> {
+ await requireEntitlement(ctx.client, ctx.companyId, "MCP");
+
+ const {
+ callOperation,
+ operationsByName,
+ isListOperation,
+ isMcpBlockedTool,
+ catalogSearch,
+ toolMetadata
+ } = deps;
-export function createMcpServer(ctx: McpContext, today: string): McpServer {
const server = new McpServer(
{
name: "carbon-erp",
- version: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) ?? "1.0.0",
+ version: process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 7) ?? "1.0.0"
},
{
- instructions: getServerInstructions(today),
- },
+ instructions: getServerInstructions(today, toolMetadata)
+ }
);
-
// Register describe_tool to get schema information for any tool
server.registerTool(
"describe_tool",
{
- description: "Get the full contract for one or more tools: description, permission, input schema and response schema",
+ description:
+ "Get the full contract for one or more tools: description, permission, input schema and response schema",
inputSchema: z.object({
- name: z.string().optional().describe("The name of the tool to describe"),
+ name: z
+ .string()
+ .optional()
+ .describe("The name of the tool to describe"),
names: z
.array(z.string())
.max(10)
@@ -65,10 +84,12 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
if (requested.length === 0) {
return {
- content: [{
- type: "text" as const,
- text: "Pass a tool `name` or a `names` array"
- }],
+ content: [
+ {
+ type: "text" as const,
+ text: "Pass a tool `name` or a `names` array"
+ }
+ ],
isError: true
};
}
@@ -100,7 +121,9 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
}
return {
- content: [{ type: "text" as const, text: sections.join("\n\n---\n\n") }],
+ content: [
+ { type: "text" as const, text: sections.join("\n\n---\n\n") }
+ ],
...(missing.length === requested.length ? { isError: true } : {})
};
}, "Describe tool failed")
@@ -127,24 +150,31 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
args = args.trim().length > 0 ? JSON.parse(args) : {};
} catch {
return {
- content: [{ type: "text" as const, text: "Invalid JSON in call_tool.arguments" }],
+ content: [
+ {
+ type: "text" as const,
+ text: "Invalid JSON in call_tool.arguments"
+ }
+ ],
isError: true
};
}
}
-
+
logger.info("call_tool invoked", { name, arguments: args });
if (isMcpBlockedTool(name)) {
return {
- content: [{
- type: "text" as const,
- text: `Tool disabled: ${name} is not available via MCP.`
- }],
+ content: [
+ {
+ type: "text" as const,
+ text: `Tool disabled: ${name} is not available via MCP.`
+ }
+ ],
isError: true
};
}
-
+
// List reads apply no limit unless the caller passes one (the schema's
// `default: 100` is documentation, not enforcement — an argless call
// returned up to PostgREST's 1000-row cap). MCP-only; the other
@@ -168,7 +198,9 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
? (args as Record<string, unknown>)
: null;
const wrapped =
- body?.args && typeof body.args === "object" && !Array.isArray(body.args)
+ body?.args &&
+ typeof body.args === "object" &&
+ !Array.isArray(body.args)
? (body.args as Record<string, unknown>)
: null;
if (meta.paginates) {
@@ -226,10 +258,15 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
responseTime
});
return {
- content: [{
- type: "text" as const,
- text: result.errorKind === "database" ? result.error : `Error: ${result.error}`
- }],
+ content: [
+ {
+ type: "text" as const,
+ text:
+ result.errorKind === "database"
+ ? result.error
+ : `Error: ${result.error}`
+ }
+ ],
isError: true
};
}, "Call tool failed")
@@ -239,9 +276,15 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
server.registerTool(
"search_tools",
{
- description: "Relevance-ranked search over ERP tools; understands common abbreviations (PO, RMA, BOM, NCR) and matches schema field names too",
+ description:
+ "Relevance-ranked search over ERP tools; understands common abbreviations (PO, RMA, BOM, NCR) and matches schema field names too",
inputSchema: z.object({
- query: z.string().optional().describe("Keywords to match against tool names, descriptions and schema field names"),
+ query: z
+ .string()
+ .optional()
+ .describe(
+ "Keywords to match against tool names, descriptions and schema field names"
+ ),
module: z.string().optional().describe("Filter by module name"),
classification: z.enum(["READ", "WRITE", "DESTRUCTIVE"]).optional(),
limit: z.number().int().min(1).max(100).default(20),
@@ -261,7 +304,7 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
limit,
offset
});
- const toolNames = matches.map(t => t.name);
+ const toolNames = matches.map((t) => t.name);
logger.info("search_tools invoked", {
query,
@@ -320,4 +363,4 @@ export function createMcpServer(ctx: McpContext, today: string): McpServer {
);
return server;
-}
\ No newline at end of file
+}
diff --git a/packages/ee/src/mcp/types.ts b/packages/ee/src/mcp/types.ts
new file mode 100644
index 0000000000..074229fdee
--- /dev/null
+++ b/packages/ee/src/mcp/types.ts
@@ -0,0 +1,101 @@
+import type { ManifestEntry } from "@carbon/api";
+import type { Database } from "@carbon/database";
+import { getLogger } from "@carbon/logger";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { CatalogSearch } from "./catalog-search";
+
+const logger = getLogger("erp", "mcp");
+
+/** The minimum an MCP request context must carry for the engine — the caller
+ * (the app route) passes its full `AuthedContext`, which is a superset. The
+ * engine is generic over the concrete context (see `createMcpServer`), so the
+ * app's dispatch (`deps.callOperation`) receives the real context unchanged;
+ * the engine itself only reads `client`/`companyId` (for the entitlement gate). */
+export type McpContext = {
+ client: SupabaseClient<Database>;
+ companyId: string;
+ companyGroupId: string;
+ userId: string;
+};
+
+/** The result shape the app's `callOperation` returns, redeclared here so the
+ * engine need not import app code. */
+export type McpCallResult =
+ | { success: true; data?: unknown; count?: number }
+ | { success: false; error: string; errorKind?: string };
+
+/** Everything the MCP engine needs from the APP side, injected by the route.
+ * The dispatch (`callOperation`), its manifest (`operationsByName` /
+ * `isListOperation`), the blocked-tool predicate and the generated tool
+ * metadata all derive from `apps/erp`'s `~/modules/*` and cannot move into a
+ * package — so they are passed in rather than imported. */
+export interface McpServerDeps<Ctx> {
+ callOperation: (
+ name: string,
+ ctx: Ctx,
+ args?: string | Record<string, unknown>
+ ) => Promise<McpCallResult>;
+ operationsByName: Map<string, ManifestEntry>;
+ isListOperation: (meta: ManifestEntry) => boolean;
+ isMcpBlockedTool: (name: string) => boolean;
+ /** Built once at module scope by the route from `tool-metadata.json`. */
+ catalogSearch: CatalogSearch;
+ /** The generated catalog summary the instructions + search footer read. */
+ toolMetadata: {
+ tools: Pick<ManifestEntry, "module">[];
+ totalTools: number;
+ modules: number;
+ };
+}
+
+export const READ_ONLY_ANNOTATIONS = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false
+} as const;
+
+export const WRITE_ANNOTATIONS = {
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: false
+} as const;
+
+export const DESTRUCTIVE_ANNOTATIONS = {
+ readOnlyHint: false,
+ destructiveHint: true,
+ idempotentHint: true,
+ openWorldHint: false
+} as const;
+
+export function withErrorHandling<T extends Record<string, unknown>>(
+ handler: (params: T) => Promise<{
+ content: { type: "text"; text: string }[];
+ isError?: boolean;
+ }>,
+ fallbackMessage: string
+) {
+ return async (params: T) => {
+ try {
+ // No info logging here — each handler logs its own invocation/result;
+ // this wrapper only reports the throw path.
+ return await handler(params);
+ } catch (error) {
+ logger.error("Error in handler", {
+ fallbackMessage,
+ error,
+ stack: error instanceof Error ? error.stack : "No stack"
+ });
+ return {
+ content: [
+ {
+ type: "text" as const,
+ text: error instanceof Error ? error.message : fallbackMessage
+ }
+ ],
+ isError: true
+ };
+ }
+ };
+}
diff --git a/packages/ee/src/workflows.server.ts b/packages/ee/src/workflows.server.ts
new file mode 100644
index 0000000000..bf7fee5713
--- /dev/null
+++ b/packages/ee/src/workflows.server.ts
@@ -0,0 +1,38 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { requireEntitlement } from "./entitlements.server";
+import { companyHasFeature } from "./plan.server";
+
+/**
+ * The commercial gate for the workflows engine. The engine itself moved into
+ * `@carbon/ee/workflows`, but the RUNTIME (`@carbon/jobs` `executeWorkflowRun`)
+ * and the AUTHORING service (`apps/erp`) live in community code, so the lock has
+ * to sit on the commercial side here.
+ *
+ * `workflowsEnabledForCompany` is the RUNTIME DEGRADE path — a queued run for a
+ * non-entitled company settles `Skipped` rather than throwing. A run executes on
+ * a background event, entirely bypassing the route-level `requireFeature` gate,
+ * so without this a Community/Starter company's workflows would still fire.
+ *
+ * `requireWorkflowsEntitlement` is the AUTHORING throw — used by the server-only
+ * publish/save path so creating or publishing a workflow requires executing
+ * commercial code (the route `requireFeature` redirect is the strippable UX gate
+ * this backstops).
+ */
+export async function workflowsEnabledForCompany(
+ companyId: string
+): Promise<boolean> {
+ // Reads the plan via the service role internally (see `plan.server`), so the
+ // Inngest runtime caller need not build/inject a client.
+ return companyHasFeature(getCarbonServiceRole(), companyId, {
+ feature: "WORKFLOWS"
+ });
+}
+
+export async function requireWorkflowsEntitlement(
+ client: SupabaseClient<Database>,
+ companyId: string
+): Promise<void> {
+ await requireEntitlement(client, companyId, "WORKFLOWS");
+}
diff --git a/packages/workflows/AGENTS.md b/packages/ee/src/workflows/AGENTS.md
similarity index 93%
rename from packages/workflows/AGENTS.md
rename to packages/ee/src/workflows/AGENTS.md
index f1bd8ab695..dfa2070133 100644
--- a/packages/workflows/AGENTS.md
+++ b/packages/ee/src/workflows/AGENTS.md
@@ -1,10 +1,26 @@
-# @carbon/workflows
+# @carbon/ee/workflows
The shared contract for a **workflow definition** — the zod schema, the read-time
normaliser, the validator that decides whether a workflow may be activated, the
generated catalog of everything a customer can pick, and the pure runtime that
evaluates a node. It runs nothing and reads no database.
+**Commercial.** This engine lives under `packages/ee/src/workflows/` (moved from the
+old standalone `@carbon/workflows` package) and is covered by the `packages/ee`
+commercial license. Import it as `@carbon/ee/workflows` (main barrel),
+`@carbon/ee/workflows/help`, and `@carbon/ee/workflows/labels` (Vite-only — the `msg`
+macro throws in plain Node). The runtime/authoring entitlement lock lives beside it in
+`@carbon/ee/workflows.server` (`workflowsEnabledForCompany` / `requireWorkflowsEntitlement`) —
+see `.claude/rules/commercial-licensing.md`.
+
+The CE-safe wire contracts stayed OUT of the commercial package, in the leaf
+`@carbon/workflows-core` (`packages/workflows-core/`): `runTriggerSchema`/`RunTrigger`
+(what fired a run) and the moment contract (`MOMENT_OUTPUT_KEYS`, `MomentKey`,
+`MomentEntityRef`, `MomentPayload`). `@carbon/lib` (`events.ts`, `workflows/raise-moment.ts`)
+imports these **type-only** from the leaf, never from this engine — that is what breaks the
+`lib → ee → lib` cycle the move would otherwise create. This engine re-exports both from the
+leaf (see `run-trigger.ts` and `catalog/moments.ts` below).
+
"Workflow" here means the customer-facing feature: a "when this happens, do that" rule a customer
builds on a canvas. It is **not** the generic sense used by the `.claude/rules/workflow-*.md`
developer-procedure files, and unrelated to `nonConformanceWorkflow`.
@@ -92,7 +108,7 @@ src/definition/
src/catalog/
├── entities.ts # HAND-WRITTEN. 16 record types — 10 triggerable (watch) + 6 reference-only; write = the update allowlist
-├── moments.ts # HAND-WRITTEN. 9 business events, their labels and outputs
+├── moments.ts # HAND-WRITTEN. 9 business events (WORKFLOW_MOMENTS, source of truth) + labels + outputs; re-exports the moment TYPES from @carbon/workflows-core
├── actions.ts # HAND-WRITTEN. 6 actions — 4 creates, notify, webhook
├── operations.ts # HAND-WRITTEN. 15 read-only computations over one record
├── build.ts # buildCatalog(registry, moments, actions, operations, schema) — pure, schema injected
@@ -118,7 +134,7 @@ src/runtime/
├── fixtures.ts # TEST-ONLY fake loader/context. Not exported from the package root
└── index.ts # barrel
-src/run-trigger.ts # runTriggerSchema — what fired a run; shared with @carbon/lib and @carbon/jobs
+src/run-trigger.ts # re-exports runTriggerSchema / RunTrigger from @carbon/workflows-core — what fired a run; the leaf (not this engine) is what @carbon/lib and @carbon/jobs depend on
src/sync.ts # trigger-event + subscription reconciler
```
@@ -157,7 +173,7 @@ RLS** — the caller authorizes first (the activation route gates on `workflows_
This is the one thing here that lives in this package for a dependency reason rather than a
conceptual one: it needs `WORKFLOW_EVENTS`, and `@carbon/database` (its more natural home,
-beside `event.ts`) cannot depend on `@carbon/workflows` without creating the package cycle
+beside `event.ts`) cannot depend on `@carbon/ee/workflows` without creating the package cycle
Turborepo rejects. See `.claude/rules/workflow-matcher.md`.
## The event catalog
@@ -313,9 +329,9 @@ event id still exists in the catalog.
## Validation Commands
```bash
-pnpm --filter @carbon/workflows test # vitest
-pnpm --filter @carbon/workflows exec tsgo --noEmit # typecheck
-pnpm exec biome check packages/workflows # lint
+pnpm --filter @carbon/ee test # vitest
+pnpm --filter @carbon/ee exec tsgo --noEmit # typecheck
+pnpm exec biome check packages/ee/src/workflows # lint
pnpm run generate:workflow-catalog # after editing entities/moments/actions/operations.ts
pnpm run check:workflow-catalog # the CI `catalog` job
```
diff --git a/packages/workflows/src/catalog/actions.generated.ts b/packages/ee/src/workflows/catalog/actions.generated.ts
similarity index 100%
rename from packages/workflows/src/catalog/actions.generated.ts
rename to packages/ee/src/workflows/catalog/actions.generated.ts
diff --git a/packages/workflows/src/catalog/actions.ts b/packages/ee/src/workflows/catalog/actions.ts
similarity index 100%
rename from packages/workflows/src/catalog/actions.ts
rename to packages/ee/src/workflows/catalog/actions.ts
diff --git a/packages/workflows/src/catalog/build.test.ts b/packages/ee/src/workflows/catalog/build.test.ts
similarity index 100%
rename from packages/workflows/src/catalog/build.test.ts
rename to packages/ee/src/workflows/catalog/build.test.ts
diff --git a/packages/workflows/src/catalog/build.ts b/packages/ee/src/workflows/catalog/build.ts
similarity index 100%
rename from packages/workflows/src/catalog/build.ts
rename to packages/ee/src/workflows/catalog/build.ts
diff --git a/packages/workflows/src/catalog/catalog.test.ts b/packages/ee/src/workflows/catalog/catalog.test.ts
similarity index 100%
rename from packages/workflows/src/catalog/catalog.test.ts
rename to packages/ee/src/workflows/catalog/catalog.test.ts
diff --git a/packages/workflows/src/catalog/catalog.ts b/packages/ee/src/workflows/catalog/catalog.ts
similarity index 100%
rename from packages/workflows/src/catalog/catalog.ts
rename to packages/ee/src/workflows/catalog/catalog.ts
diff --git a/packages/workflows/src/catalog/custom-fields.test.ts b/packages/ee/src/workflows/catalog/custom-fields.test.ts
similarity index 100%
rename from packages/workflows/src/catalog/custom-fields.test.ts
rename to packages/ee/src/workflows/catalog/custom-fields.test.ts
diff --git a/packages/workflows/src/catalog/custom-fields.ts b/packages/ee/src/workflows/catalog/custom-fields.ts
similarity index 100%
rename from packages/workflows/src/catalog/custom-fields.ts
rename to packages/ee/src/workflows/catalog/custom-fields.ts
diff --git a/packages/workflows/src/catalog/entities.ts b/packages/ee/src/workflows/catalog/entities.ts
similarity index 100%
rename from packages/workflows/src/catalog/entities.ts
rename to packages/ee/src/workflows/catalog/entities.ts
diff --git a/packages/workflows/src/catalog/events.generated.ts b/packages/ee/src/workflows/catalog/events.generated.ts
similarity index 100%
rename from packages/workflows/src/catalog/events.generated.ts
rename to packages/ee/src/workflows/catalog/events.generated.ts
diff --git a/packages/workflows/src/catalog/help.generated.ts b/packages/ee/src/workflows/catalog/help.generated.ts
similarity index 100%
rename from packages/workflows/src/catalog/help.generated.ts
rename to packages/ee/src/workflows/catalog/help.generated.ts
diff --git a/packages/workflows/src/catalog/index.ts b/packages/ee/src/workflows/catalog/index.ts
similarity index 100%
rename from packages/workflows/src/catalog/index.ts
rename to packages/ee/src/workflows/catalog/index.ts
diff --git a/packages/workflows/src/catalog/labels.generated.ts b/packages/ee/src/workflows/catalog/labels.generated.ts
similarity index 100%
rename from packages/workflows/src/catalog/labels.generated.ts
rename to packages/ee/src/workflows/catalog/labels.generated.ts
diff --git a/packages/workflows/src/catalog/moments.ts b/packages/ee/src/workflows/catalog/moments.ts
similarity index 78%
rename from packages/workflows/src/catalog/moments.ts
rename to packages/ee/src/workflows/catalog/moments.ts
index 24344f944e..f5ecf45e33 100644
--- a/packages/workflows/src/catalog/moments.ts
+++ b/packages/ee/src/workflows/catalog/moments.ts
@@ -61,11 +61,14 @@ export const WORKFLOW_MOMENTS = {
}
} as const satisfies Record<string, MomentDeclarationLike>;
-export type MomentKey = keyof typeof WORKFLOW_MOMENTS;
-
-/** Entity outputs are passed as an id, never a row snapshot. */
-export type MomentEntityRef = { id: string };
-
-export type MomentPayload<K extends MomentKey> = {
- [O in keyof (typeof WORKFLOW_MOMENTS)[K]["outputs"]]: MomentEntityRef;
-};
+// `MomentKey` / `MomentEntityRef` / `MomentPayload` are the CE-safe moment
+// contract, defined in `@carbon/workflows-core` (so `@carbon/lib` can use them
+// without a cycle into this commercial engine) and derived there from
+// `MOMENT_OUTPUT_KEYS`. `WORKFLOW_MOMENTS` above stays the source of truth for the
+// labels/permissions/entity types; `scripts/check-workflow-catalog.ts` asserts the
+// two never drift (same keys, same output-key names).
+export type {
+ MomentEntityRef,
+ MomentKey,
+ MomentPayload
+} from "@carbon/workflows-core";
diff --git a/packages/workflows/src/catalog/operations.ts b/packages/ee/src/workflows/catalog/operations.ts
similarity index 100%
rename from packages/workflows/src/catalog/operations.ts
rename to packages/ee/src/workflows/catalog/operations.ts
diff --git a/packages/workflows/src/definition/batch.test.ts b/packages/ee/src/workflows/definition/batch.test.ts
similarity index 100%
rename from packages/workflows/src/definition/batch.test.ts
rename to packages/ee/src/workflows/definition/batch.test.ts
diff --git a/packages/workflows/src/definition/batch.ts b/packages/ee/src/workflows/definition/batch.ts
similarity index 100%
rename from packages/workflows/src/definition/batch.ts
rename to packages/ee/src/workflows/definition/batch.ts
diff --git a/packages/workflows/src/definition/catalog.ts b/packages/ee/src/workflows/definition/catalog.ts
similarity index 100%
rename from packages/workflows/src/definition/catalog.ts
rename to packages/ee/src/workflows/definition/catalog.ts
diff --git a/packages/workflows/src/definition/issues.ts b/packages/ee/src/workflows/definition/issues.ts
similarity index 100%
rename from packages/workflows/src/definition/issues.ts
rename to packages/ee/src/workflows/definition/issues.ts
diff --git a/packages/workflows/src/definition/names.ts b/packages/ee/src/workflows/definition/names.ts
similarity index 100%
rename from packages/workflows/src/definition/names.ts
rename to packages/ee/src/workflows/definition/names.ts
diff --git a/packages/workflows/src/definition/nodes.ts b/packages/ee/src/workflows/definition/nodes.ts
similarity index 100%
rename from packages/workflows/src/definition/nodes.ts
rename to packages/ee/src/workflows/definition/nodes.ts
diff --git a/packages/workflows/src/definition/normalize.test.ts b/packages/ee/src/workflows/definition/normalize.test.ts
similarity index 100%
rename from packages/workflows/src/definition/normalize.test.ts
rename to packages/ee/src/workflows/definition/normalize.test.ts
diff --git a/packages/workflows/src/definition/normalize.ts b/packages/ee/src/workflows/definition/normalize.ts
similarity index 100%
rename from packages/workflows/src/definition/normalize.ts
rename to packages/ee/src/workflows/definition/normalize.ts
diff --git a/packages/workflows/src/definition/order.test.ts b/packages/ee/src/workflows/definition/order.test.ts
similarity index 100%
rename from packages/workflows/src/definition/order.test.ts
rename to packages/ee/src/workflows/definition/order.test.ts
diff --git a/packages/workflows/src/definition/order.ts b/packages/ee/src/workflows/definition/order.ts
similarity index 100%
rename from packages/workflows/src/definition/order.ts
rename to packages/ee/src/workflows/definition/order.ts
diff --git a/packages/workflows/src/definition/paths.test.ts b/packages/ee/src/workflows/definition/paths.test.ts
similarity index 100%
rename from packages/workflows/src/definition/paths.test.ts
rename to packages/ee/src/workflows/definition/paths.test.ts
diff --git a/packages/workflows/src/definition/paths.ts b/packages/ee/src/workflows/definition/paths.ts
similarity index 100%
rename from packages/workflows/src/definition/paths.ts
rename to packages/ee/src/workflows/definition/paths.ts
diff --git a/packages/workflows/src/definition/schedule.test.ts b/packages/ee/src/workflows/definition/schedule.test.ts
similarity index 100%
rename from packages/workflows/src/definition/schedule.test.ts
rename to packages/ee/src/workflows/definition/schedule.test.ts
diff --git a/packages/workflows/src/definition/schedule.ts b/packages/ee/src/workflows/definition/schedule.ts
similarity index 100%
rename from packages/workflows/src/definition/schedule.ts
rename to packages/ee/src/workflows/definition/schedule.ts
diff --git a/packages/workflows/src/definition/schema.test.ts b/packages/ee/src/workflows/definition/schema.test.ts
similarity index 100%
rename from packages/workflows/src/definition/schema.test.ts
rename to packages/ee/src/workflows/definition/schema.test.ts
diff --git a/packages/workflows/src/definition/schema.ts b/packages/ee/src/workflows/definition/schema.ts
similarity index 100%
rename from packages/workflows/src/definition/schema.ts
rename to packages/ee/src/workflows/definition/schema.ts
diff --git a/packages/workflows/src/definition/types.test.ts b/packages/ee/src/workflows/definition/types.test.ts
similarity index 100%
rename from packages/workflows/src/definition/types.test.ts
rename to packages/ee/src/workflows/definition/types.test.ts
diff --git a/packages/workflows/src/definition/types.ts b/packages/ee/src/workflows/definition/types.ts
similarity index 100%
rename from packages/workflows/src/definition/types.ts
rename to packages/ee/src/workflows/definition/types.ts
diff --git a/packages/workflows/src/definition/validate.test.ts b/packages/ee/src/workflows/definition/validate.test.ts
similarity index 100%
rename from packages/workflows/src/definition/validate.test.ts
rename to packages/ee/src/workflows/definition/validate.test.ts
diff --git a/packages/workflows/src/definition/validate.ts b/packages/ee/src/workflows/definition/validate.ts
similarity index 100%
rename from packages/workflows/src/definition/validate.ts
rename to packages/ee/src/workflows/definition/validate.ts
diff --git a/packages/workflows/src/definition/variables.test.ts b/packages/ee/src/workflows/definition/variables.test.ts
similarity index 100%
rename from packages/workflows/src/definition/variables.test.ts
rename to packages/ee/src/workflows/definition/variables.test.ts
diff --git a/packages/workflows/src/definition/variables.ts b/packages/ee/src/workflows/definition/variables.ts
similarity index 100%
rename from packages/workflows/src/definition/variables.ts
rename to packages/ee/src/workflows/definition/variables.ts
diff --git a/packages/workflows/src/index.ts b/packages/ee/src/workflows/index.ts
similarity index 100%
rename from packages/workflows/src/index.ts
rename to packages/ee/src/workflows/index.ts
diff --git a/packages/ee/src/workflows/run-trigger.ts b/packages/ee/src/workflows/run-trigger.ts
new file mode 100644
index 0000000000..0e7124faf5
--- /dev/null
+++ b/packages/ee/src/workflows/run-trigger.ts
@@ -0,0 +1,5 @@
+// The run-trigger wire contract lives in the CE leaf `@carbon/workflows-core` so
+// community packages (`@carbon/lib`) can depend on it without pulling in this
+// commercial engine (which would form a `lib → ee → lib` cycle). Re-exported here
+// so `@carbon/ee/workflows`'s public surface is unchanged.
+export { type RunTrigger, runTriggerSchema } from "@carbon/workflows-core";
diff --git a/packages/workflows/src/runtime/action.test.ts b/packages/ee/src/workflows/runtime/action.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/action.test.ts
rename to packages/ee/src/workflows/runtime/action.test.ts
diff --git a/packages/workflows/src/runtime/action.ts b/packages/ee/src/workflows/runtime/action.ts
similarity index 100%
rename from packages/workflows/src/runtime/action.ts
rename to packages/ee/src/workflows/runtime/action.ts
diff --git a/packages/workflows/src/runtime/batch.test.ts b/packages/ee/src/workflows/runtime/batch.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/batch.test.ts
rename to packages/ee/src/workflows/runtime/batch.test.ts
diff --git a/packages/workflows/src/runtime/batch.ts b/packages/ee/src/workflows/runtime/batch.ts
similarity index 100%
rename from packages/workflows/src/runtime/batch.ts
rename to packages/ee/src/workflows/runtime/batch.ts
diff --git a/packages/workflows/src/runtime/compare.test.ts b/packages/ee/src/workflows/runtime/compare.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/compare.test.ts
rename to packages/ee/src/workflows/runtime/compare.test.ts
diff --git a/packages/workflows/src/runtime/compare.ts b/packages/ee/src/workflows/runtime/compare.ts
similarity index 100%
rename from packages/workflows/src/runtime/compare.ts
rename to packages/ee/src/workflows/runtime/compare.ts
diff --git a/packages/workflows/src/runtime/compute.test.ts b/packages/ee/src/workflows/runtime/compute.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/compute.test.ts
rename to packages/ee/src/workflows/runtime/compute.test.ts
diff --git a/packages/workflows/src/runtime/compute.ts b/packages/ee/src/workflows/runtime/compute.ts
similarity index 100%
rename from packages/workflows/src/runtime/compute.ts
rename to packages/ee/src/workflows/runtime/compute.ts
diff --git a/packages/workflows/src/runtime/condition.test.ts b/packages/ee/src/workflows/runtime/condition.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/condition.test.ts
rename to packages/ee/src/workflows/runtime/condition.test.ts
diff --git a/packages/workflows/src/runtime/condition.ts b/packages/ee/src/workflows/runtime/condition.ts
similarity index 100%
rename from packages/workflows/src/runtime/condition.ts
rename to packages/ee/src/workflows/runtime/condition.ts
diff --git a/packages/workflows/src/runtime/executors.test.ts b/packages/ee/src/workflows/runtime/executors.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/executors.test.ts
rename to packages/ee/src/workflows/runtime/executors.test.ts
diff --git a/packages/workflows/src/runtime/executors.ts b/packages/ee/src/workflows/runtime/executors.ts
similarity index 100%
rename from packages/workflows/src/runtime/executors.ts
rename to packages/ee/src/workflows/runtime/executors.ts
diff --git a/packages/workflows/src/runtime/filter.test.ts b/packages/ee/src/workflows/runtime/filter.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/filter.test.ts
rename to packages/ee/src/workflows/runtime/filter.test.ts
diff --git a/packages/workflows/src/runtime/filter.ts b/packages/ee/src/workflows/runtime/filter.ts
similarity index 100%
rename from packages/workflows/src/runtime/filter.ts
rename to packages/ee/src/workflows/runtime/filter.ts
diff --git a/packages/workflows/src/runtime/fixtures.ts b/packages/ee/src/workflows/runtime/fixtures.ts
similarity index 100%
rename from packages/workflows/src/runtime/fixtures.ts
rename to packages/ee/src/workflows/runtime/fixtures.ts
diff --git a/packages/workflows/src/runtime/index.ts b/packages/ee/src/workflows/runtime/index.ts
similarity index 100%
rename from packages/workflows/src/runtime/index.ts
rename to packages/ee/src/workflows/runtime/index.ts
diff --git a/packages/workflows/src/runtime/lookup.test.ts b/packages/ee/src/workflows/runtime/lookup.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/lookup.test.ts
rename to packages/ee/src/workflows/runtime/lookup.test.ts
diff --git a/packages/workflows/src/runtime/lookup.ts b/packages/ee/src/workflows/runtime/lookup.ts
similarity index 100%
rename from packages/workflows/src/runtime/lookup.ts
rename to packages/ee/src/workflows/runtime/lookup.ts
diff --git a/packages/workflows/src/runtime/resolve.test.ts b/packages/ee/src/workflows/runtime/resolve.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/resolve.test.ts
rename to packages/ee/src/workflows/runtime/resolve.test.ts
diff --git a/packages/workflows/src/runtime/resolve.ts b/packages/ee/src/workflows/runtime/resolve.ts
similarity index 100%
rename from packages/workflows/src/runtime/resolve.ts
rename to packages/ee/src/workflows/runtime/resolve.ts
diff --git a/packages/workflows/src/runtime/template.test.ts b/packages/ee/src/workflows/runtime/template.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/template.test.ts
rename to packages/ee/src/workflows/runtime/template.test.ts
diff --git a/packages/workflows/src/runtime/types.ts b/packages/ee/src/workflows/runtime/types.ts
similarity index 100%
rename from packages/workflows/src/runtime/types.ts
rename to packages/ee/src/workflows/runtime/types.ts
diff --git a/packages/workflows/src/runtime/values.test.ts b/packages/ee/src/workflows/runtime/values.test.ts
similarity index 100%
rename from packages/workflows/src/runtime/values.test.ts
rename to packages/ee/src/workflows/runtime/values.test.ts
diff --git a/packages/workflows/src/runtime/values.ts b/packages/ee/src/workflows/runtime/values.ts
similarity index 100%
rename from packages/workflows/src/runtime/values.ts
rename to packages/ee/src/workflows/runtime/values.ts
diff --git a/packages/workflows/src/seed-workflows.test.ts b/packages/ee/src/workflows/seed-workflows.test.ts
similarity index 100%
rename from packages/workflows/src/seed-workflows.test.ts
rename to packages/ee/src/workflows/seed-workflows.test.ts
diff --git a/packages/workflows/src/sync.test.ts b/packages/ee/src/workflows/sync.test.ts
similarity index 100%
rename from packages/workflows/src/sync.test.ts
rename to packages/ee/src/workflows/sync.test.ts
diff --git a/packages/workflows/src/sync.ts b/packages/ee/src/workflows/sync.ts
similarity index 100%
rename from packages/workflows/src/sync.ts
rename to packages/ee/src/workflows/sync.ts
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index 363e31a69e..021e3c326c 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -11,11 +11,11 @@
"@carbon/lib": "workspace:*",
"@carbon/logger": "workspace:*",
"@carbon/notifications": "workspace:*",
+ "@carbon/planning": "workspace:*",
"@carbon/printing": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
"@carbon/viewer": "workspace:*",
- "@carbon/workflows": "workspace:*",
"@internationalized/date": "catalog:",
"@react-email/components": "catalog:",
"@react-pdf/renderer": "catalog:",
diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.ts
index 4e435321f3..6968fc266c 100644
--- a/packages/jobs/src/inngest/functions/notifications/notify.ts
+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts
@@ -1,10 +1,10 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { resolveIntegrationSecrets } from "@carbon/ee";
+import { emailNotificationsEnabled } from "@carbon/ee/email-notifications.server";
import {
type CompanyIntegration,
notifyTaskAssigned
} from "@carbon/ee/notifications";
-import { companyHasFeature } from "@carbon/ee/plan.server";
import { getSlackUserIdByCarbonId } from "@carbon/ee/slack.server";
import { ERP_URL } from "@carbon/env";
import type { Events } from "@carbon/lib/events";
@@ -534,9 +534,7 @@ export const notifyFunction = inngest.createFunction(
const emailAllowed =
wantsEmail &&
(await step.run("check-email-plan", () =>
- companyHasFeature(client, payload.companyId, {
- feature: "EMAIL_NOTIFICATIONS"
- })
+ emailNotificationsEnabled(client, payload.companyId)
));
if (wantsEmail && !emailAllowed) {
diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp.ts b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
index 7b67f9a174..dc819c2ac5 100644
--- a/packages/jobs/src/inngest/functions/scheduled/mrp.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/mrp.ts
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { fetchAllFromTable } from "@carbon/database";
-import { runMrp } from "@carbon/ee/planning";
+import { runMrp } from "@carbon/planning";
import { Edition } from "@carbon/utils";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
diff --git a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts
index 0f75a95d69..888221cfae 100644
--- a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts
@@ -1,8 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { activeJobStatuses, fetchAllFromTable } from "@carbon/database";
-import { runLocationSchedule } from "@carbon/ee/planning";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
+import { runLocationSchedule } from "@carbon/planning";
import { NonRetriableError } from "inngest";
import { z } from "zod";
import { getJobDatabaseClient } from "../../../db";
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 34c795755a..d87e7f3c42 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { requireBackupsEntitlement } from "@carbon/ee/backups.server";
import { getCompanyPrivateBucket } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { NonRetriableError } from "inngest";
@@ -365,6 +366,8 @@ export const companyExportFunction = inngest.createFunction(
const { companyId, userId, label, includeStorage, skipCorrupted } =
event.data;
+ await requireBackupsEntitlement(companyId);
+
return await step.run("export-company", async () => {
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(TABLE_CONCURRENCY);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index 0dfff80c8b..e4f1e380a7 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { requireBackupsEntitlement } from "@carbon/ee/backups.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
import { applyTableRenames } from "../../../backups/renames";
@@ -63,6 +64,12 @@ export const companyImportFunction = inngest.createFunction(
const referencedTemplate =
typeof templateIndustryId === "string" && templateIndustryId.length > 0;
+ // A real (foreign) backup import is the gated BACKUPS feature; an onboarding
+ // demo-template import is not — keep templating available on every edition.
+ if (!referencedTemplate) {
+ await requireBackupsEntitlement(companyId);
+ }
+
return await step.run("import-company", async () => {
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(1);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index 04f1ac213a..3eb62c0cd4 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -1,4 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { requireBackupsEntitlement } from "@carbon/ee/backups.server";
import { chunkArray } from "@carbon/utils";
import { NonRetriableError } from "inngest";
import { sql } from "kysely";
@@ -392,6 +393,8 @@ export const companyRestoreFunction = inngest.createFunction(
const { companyId, userId, filePath, restoreRunId, label, includeStorage } =
event.data;
+ await requireBackupsEntitlement(companyId);
+
return await step.run("restore-company", async () => {
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(1);
@@ -622,6 +625,10 @@ export const companyRestoreFinalizeFunction = inngest.createFunction(
async ({ event, step, logger }) => {
const { companyId, restoreRunId } = event.data;
+ // No entitlement gate here: finalize only RESOLVES an already-started (and
+ // already-gated) restore. If BACKUPS lapsed while the restore sat "ready",
+ // gating this would strand it — marker stuck "ready", snapshot orphaned,
+ // with no recovery path (retries: 1). The lock is on companyRestoreFunction.
return await step.run("finalize-restore", async () => {
const client = getCarbonServiceRole();
const marker = await readRestoreMarker(client, companyId, restoreRunId);
@@ -655,6 +662,10 @@ export const companyRestoreRevertFunction = inngest.createFunction(
async ({ event, step, logger }) => {
const { companyId, restoreRunId } = event.data;
+ // No entitlement gate here (see finalize): revert must always be able to
+ // undo a pending restore and return the pre-restore snapshot, even if
+ // BACKUPS lapsed while it sat "ready" — blocking it would strand the company
+ // mid-restore. The lock is on companyRestoreFunction (the start).
return await step.run("revert-restore", async () => {
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(1);
diff --git a/packages/jobs/src/inngest/functions/tasks/recalculate.ts b/packages/jobs/src/inngest/functions/tasks/recalculate.ts
index 11dbe3bb66..ba8f8b3a4d 100644
--- a/packages/jobs/src/inngest/functions/tasks/recalculate.ts
+++ b/packages/jobs/src/inngest/functions/tasks/recalculate.ts
@@ -1,5 +1,5 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
-import { runLocationSchedule } from "@carbon/ee/planning";
+import { runLocationSchedule } from "@carbon/planning";
import type { FunctionsResponse } from "@supabase/functions-js";
import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
diff --git a/packages/jobs/src/inngest/functions/workflows/moment.ts b/packages/jobs/src/inngest/functions/workflows/moment.ts
index 7b635b0604..c5d92fb5cf 100644
--- a/packages/jobs/src/inngest/functions/workflows/moment.ts
+++ b/packages/jobs/src/inngest/functions/workflows/moment.ts
@@ -1,4 +1,4 @@
-import { WORKFLOW_EVENTS } from "@carbon/workflows";
+import { WORKFLOW_EVENTS } from "@carbon/ee/workflows";
import { z } from "zod";
import { getJobDatabaseClient } from "../../../db";
import { matchAndQueue } from "../../../workflows/matcher";
diff --git a/packages/jobs/src/inngest/functions/workflows/run.ts b/packages/jobs/src/inngest/functions/workflows/run.ts
index 9d5ba133cb..b2ab98c3f2 100644
--- a/packages/jobs/src/inngest/functions/workflows/run.ts
+++ b/packages/jobs/src/inngest/functions/workflows/run.ts
@@ -1,4 +1,4 @@
-import { runTriggerSchema } from "@carbon/workflows";
+import { runTriggerSchema } from "@carbon/ee/workflows";
import { z } from "zod";
import { getJobDatabaseClient } from "../../../db";
import {
diff --git a/packages/jobs/src/workflows/actions/create.test.ts b/packages/jobs/src/workflows/actions/create.test.ts
index 2d0aa50465..f202b9a059 100644
--- a/packages/jobs/src/workflows/actions/create.test.ts
+++ b/packages/jobs/src/workflows/actions/create.test.ts
@@ -1,4 +1,4 @@
-import { entityValue, primitiveValue } from "@carbon/workflows";
+import { entityValue, primitiveValue } from "@carbon/ee/workflows";
import { describe, expect, it, vi } from "vitest";
import { runCreateAction } from "./create";
import type { DispatchContext, DispatchResult } from "./dispatcher";
diff --git a/packages/jobs/src/workflows/actions/create.ts b/packages/jobs/src/workflows/actions/create.ts
index 2f2682c7d6..5dcd50945a 100644
--- a/packages/jobs/src/workflows/actions/create.ts
+++ b/packages/jobs/src/workflows/actions/create.ts
@@ -2,7 +2,7 @@ import {
type ActionOutcome,
entityValue,
type RuntimeValue
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { DispatchContext, WorkflowDispatch } from "./dispatcher";
import { toPlainValue } from "./values";
diff --git a/packages/jobs/src/workflows/actions/notify.test.ts b/packages/jobs/src/workflows/actions/notify.test.ts
index 22d955e714..c8cad2a7f8 100644
--- a/packages/jobs/src/workflows/actions/notify.test.ts
+++ b/packages/jobs/src/workflows/actions/notify.test.ts
@@ -1,9 +1,9 @@
+import type { RuntimeValue } from "@carbon/ee/workflows";
+import { entityValue, listValue, primitiveValue } from "@carbon/ee/workflows";
import {
NotificationDestination,
NotificationEvent
} from "@carbon/notifications";
-import type { RuntimeValue } from "@carbon/workflows";
-import { entityValue, listValue, primitiveValue } from "@carbon/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runNotifyAction } from "./notify";
diff --git a/packages/jobs/src/workflows/actions/notify.ts b/packages/jobs/src/workflows/actions/notify.ts
index 4ec1fc110a..ba884f76f1 100644
--- a/packages/jobs/src/workflows/actions/notify.ts
+++ b/packages/jobs/src/workflows/actions/notify.ts
@@ -1,10 +1,10 @@
import type { Database } from "@carbon/database";
+import type { ActionOutcome, RuntimeValue } from "@carbon/ee/workflows";
import { trigger } from "@carbon/lib/trigger";
import {
NotificationDestination,
NotificationEvent
} from "@carbon/notifications";
-import type { ActionOutcome, RuntimeValue } from "@carbon/workflows";
type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];
diff --git a/packages/jobs/src/workflows/actions/operations.test.ts b/packages/jobs/src/workflows/actions/operations.test.ts
index be962827e4..8ab6a1bf55 100644
--- a/packages/jobs/src/workflows/actions/operations.test.ts
+++ b/packages/jobs/src/workflows/actions/operations.test.ts
@@ -3,7 +3,7 @@ import {
entityValue,
type RuntimeValue,
WORKFLOW_OPERATIONS
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import { runOperation } from "./operations";
diff --git a/packages/jobs/src/workflows/actions/operations.ts b/packages/jobs/src/workflows/actions/operations.ts
index 2ae522e32a..33139dfadd 100644
--- a/packages/jobs/src/workflows/actions/operations.ts
+++ b/packages/jobs/src/workflows/actions/operations.ts
@@ -8,7 +8,7 @@ import {
type RuntimeValue,
t,
WORKFLOW_OPERATIONS
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
type Client = SupabaseClient<Database>;
diff --git a/packages/jobs/src/workflows/actions/search.test.ts b/packages/jobs/src/workflows/actions/search.test.ts
index ca87a667b2..7dff23eac8 100644
--- a/packages/jobs/src/workflows/actions/search.test.ts
+++ b/packages/jobs/src/workflows/actions/search.test.ts
@@ -7,7 +7,7 @@ import {
type RuntimeValue,
type SearchCriterion,
WORKFLOW_ENTITIES
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import { runSearch } from "./search";
diff --git a/packages/jobs/src/workflows/actions/search.ts b/packages/jobs/src/workflows/actions/search.ts
index 817222ae3b..dddaaaf8c6 100644
--- a/packages/jobs/src/workflows/actions/search.ts
+++ b/packages/jobs/src/workflows/actions/search.ts
@@ -10,7 +10,7 @@ import {
type SearchCriterion,
type SearchOutcome,
WORKFLOW_ENTITIES
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
/** The scalar a criterion filters by; a list has no single value to compare. */
diff --git a/packages/jobs/src/workflows/actions/services.test.ts b/packages/jobs/src/workflows/actions/services.test.ts
index 0cc539927e..ba207c786c 100644
--- a/packages/jobs/src/workflows/actions/services.test.ts
+++ b/packages/jobs/src/workflows/actions/services.test.ts
@@ -1,5 +1,5 @@
import type { Database } from "@carbon/database";
-import { createWorkflowCatalog, entityValue } from "@carbon/workflows";
+import { createWorkflowCatalog, entityValue } from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createWorkflowServices } from "./services";
diff --git a/packages/jobs/src/workflows/actions/services.ts b/packages/jobs/src/workflows/actions/services.ts
index 6bf47d7cb7..157e013eed 100644
--- a/packages/jobs/src/workflows/actions/services.ts
+++ b/packages/jobs/src/workflows/actions/services.ts
@@ -8,7 +8,7 @@ import {
type SearchOutcome,
type WorkflowCatalog,
type WorkflowServices
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { runCreateAction } from "./create";
import { getWorkflowDispatch } from "./dispatcher";
diff --git a/packages/jobs/src/workflows/actions/update.test.ts b/packages/jobs/src/workflows/actions/update.test.ts
index ac580ae81a..68e56007c4 100644
--- a/packages/jobs/src/workflows/actions/update.test.ts
+++ b/packages/jobs/src/workflows/actions/update.test.ts
@@ -4,7 +4,7 @@ import {
createWorkflowCatalog,
entityValue,
primitiveValue
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import { runUpdateAction } from "./update";
diff --git a/packages/jobs/src/workflows/actions/update.ts b/packages/jobs/src/workflows/actions/update.ts
index 3df94917c0..d198a16fad 100644
--- a/packages/jobs/src/workflows/actions/update.ts
+++ b/packages/jobs/src/workflows/actions/update.ts
@@ -1,5 +1,4 @@
import type { Database } from "@carbon/database";
-import { datetime } from "@carbon/utils";
import {
type ActionOutcome,
type CatalogAction,
@@ -7,7 +6,8 @@ import {
entityValue,
REGISTRY_ENTRIES,
type RuntimeValue
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { toPlainValue } from "./values";
diff --git a/packages/jobs/src/workflows/actions/values.ts b/packages/jobs/src/workflows/actions/values.ts
index d7188dff36..7ef5cd9676 100644
--- a/packages/jobs/src/workflows/actions/values.ts
+++ b/packages/jobs/src/workflows/actions/values.ts
@@ -1,4 +1,4 @@
-import type { RuntimeValue } from "@carbon/workflows";
+import type { RuntimeValue } from "@carbon/ee/workflows";
/** A RuntimeValue as the plain value a column or a service function expects.
* Shared so the create and update executors convert identically. */
diff --git a/packages/jobs/src/workflows/actions/webhook.test.ts b/packages/jobs/src/workflows/actions/webhook.test.ts
index 59b4d36f6b..b6728af54b 100644
--- a/packages/jobs/src/workflows/actions/webhook.test.ts
+++ b/packages/jobs/src/workflows/actions/webhook.test.ts
@@ -1,6 +1,6 @@
import dns from "node:dns";
import type { Database } from "@carbon/database";
-import { pairsValue, primitiveValue } from "@carbon/workflows";
+import { pairsValue, primitiveValue } from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { runWebhookAction } from "./webhook";
diff --git a/packages/jobs/src/workflows/actions/webhook.ts b/packages/jobs/src/workflows/actions/webhook.ts
index 11b48b910b..20b06dc7a7 100644
--- a/packages/jobs/src/workflows/actions/webhook.ts
+++ b/packages/jobs/src/workflows/actions/webhook.ts
@@ -4,7 +4,7 @@ import {
isNull,
primitiveValue,
type RuntimeValue
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
// undici's own fetch, not the global one: the global is whatever undici Node bundled,
// and a dispatcher from a different major is rejected at request time.
diff --git a/packages/jobs/src/workflows/engine/batch.test.ts b/packages/jobs/src/workflows/engine/batch.test.ts
index ddaa2eaa1f..5414c1e1c5 100644
--- a/packages/jobs/src/workflows/engine/batch.test.ts
+++ b/packages/jobs/src/workflows/engine/batch.test.ts
@@ -5,10 +5,13 @@ import {
type RuntimeValue,
type SearchOutcome,
SUCCESS_HANDLE
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EngineStep, RunPayload } from "./execute";
+vi.mock("@carbon/ee/workflows.server", () => ({
+ workflowsEnabledForCompany: vi.fn(async () => true)
+}));
vi.mock("../../db", () => ({ getJobDatabaseClient: () => ({}) }));
vi.mock("./log", () => ({
loadRunContext: vi.fn(),
diff --git a/packages/jobs/src/workflows/engine/end-to-end.test.ts b/packages/jobs/src/workflows/engine/end-to-end.test.ts
index 2b10450006..770f58df4b 100644
--- a/packages/jobs/src/workflows/engine/end-to-end.test.ts
+++ b/packages/jobs/src/workflows/engine/end-to-end.test.ts
@@ -8,10 +8,13 @@ import {
type RuntimeValue,
type SearchOutcome,
SUCCESS_HANDLE
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EngineStep, RunPayload } from "./execute";
+vi.mock("@carbon/ee/workflows.server", () => ({
+ workflowsEnabledForCompany: vi.fn(async () => true)
+}));
vi.mock("../../db", () => ({ getJobDatabaseClient: () => ({}) }));
vi.mock("./log", () => ({
loadRunContext: vi.fn(),
diff --git a/packages/jobs/src/workflows/engine/execute.test.ts b/packages/jobs/src/workflows/engine/execute.test.ts
index a7fc3f1af0..5ce9bca873 100644
--- a/packages/jobs/src/workflows/engine/execute.test.ts
+++ b/packages/jobs/src/workflows/engine/execute.test.ts
@@ -2,10 +2,13 @@ import {
DEFAULT_HANDLE,
entityValue,
type RuntimeValue
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EngineStep, RunPayload } from "./execute";
+vi.mock("@carbon/ee/workflows.server", () => ({
+ workflowsEnabledForCompany: vi.fn(async () => true)
+}));
vi.mock("../../db", () => ({ getJobDatabaseClient: () => ({}) }));
vi.mock("./log", () => ({
loadRunContext: vi.fn(),
diff --git a/packages/jobs/src/workflows/engine/execute.ts b/packages/jobs/src/workflows/engine/execute.ts
index d8d8644170..aba9b7519c 100644
--- a/packages/jobs/src/workflows/engine/execute.ts
+++ b/packages/jobs/src/workflows/engine/execute.ts
@@ -1,5 +1,3 @@
-import { NotificationEvent } from "@carbon/notifications";
-import { datetime } from "@carbon/utils";
import {
batchCandidates,
buildCatalogOverlay,
@@ -20,7 +18,10 @@ import {
type WorkflowCatalog,
type WorkflowDefinition,
type WorkflowNode
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { workflowsEnabledForCompany } from "@carbon/ee/workflows.server";
+import { NotificationEvent } from "@carbon/notifications";
+import { datetime } from "@carbon/utils";
import { NonRetriableError } from "inngest";
import { getJobDatabaseClient, type JobDatabase } from "../../db";
import { buildNotificationLink } from "../../inngest/functions/notifications/content";
@@ -70,6 +71,7 @@ export interface EngineLogger {
}
const UNPUBLISHED = "This workflow was unpublished before the run started.";
+const NOT_ENTITLED = "Workflows are not enabled for this company's plan.";
const NO_PERMISSIONS =
"The permissions for the owner of this workflow could not be read.";
const NOT_AVAILABLE = "This kind of step is not available yet.";
@@ -375,6 +377,20 @@ export async function executeWorkflowRun(params: {
const startedAt = datetime.timestamp();
+ // Commercial gate (DEGRADE, not throw): a run executes on a background event,
+ // bypassing the route-level `requireFeature`, so the lock is re-checked here.
+ // A queued run for a non-entitled company settles Skipped rather than firing.
+ if (!(await workflowsEnabledForCompany(payload.companyId))) {
+ await finishRun(db, {
+ runId: payload.runId,
+ companyId: payload.companyId,
+ status: "Skipped",
+ statusReason: NOT_ENTITLED,
+ startedAt
+ });
+ return { settled: "Skipped" as const };
+ }
+
if (!context.workflowPublished) {
await finishRun(db, {
runId: payload.runId,
diff --git a/packages/jobs/src/workflows/engine/loader.test.ts b/packages/jobs/src/workflows/engine/loader.test.ts
index ae0d3bef60..3b7cb6d41e 100644
--- a/packages/jobs/src/workflows/engine/loader.test.ts
+++ b/packages/jobs/src/workflows/engine/loader.test.ts
@@ -3,7 +3,7 @@ import {
type RuntimeContext,
type RuntimeValue,
resolveRef
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import { type EntityCache, triggerOutputs } from "./loader";
diff --git a/packages/jobs/src/workflows/engine/loader.ts b/packages/jobs/src/workflows/engine/loader.ts
index b4e54f26d1..5245466a41 100644
--- a/packages/jobs/src/workflows/engine/loader.ts
+++ b/packages/jobs/src/workflows/engine/loader.ts
@@ -6,7 +6,7 @@ import {
type RunTrigger,
type RuntimeValue,
type WorkflowCatalog
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
export type EntityCache = Map<string, Record<string, unknown> | null>;
diff --git a/packages/jobs/src/workflows/engine/manual.test.ts b/packages/jobs/src/workflows/engine/manual.test.ts
index 28f6992579..51da3011f0 100644
--- a/packages/jobs/src/workflows/engine/manual.test.ts
+++ b/packages/jobs/src/workflows/engine/manual.test.ts
@@ -3,7 +3,7 @@ import {
entityValue,
type RuntimeValue,
SUCCESS_HANDLE
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
/** Enough of Kysely's builder to record what a manual run writes. */
@@ -58,6 +58,9 @@ const getJobDatabaseClient = vi.fn(() => ({
// Only `failCrashedRun` reads, and only for the run's startedAt.
selectFrom: () => builder({ startedAt: null })
}));
+vi.mock("@carbon/ee/workflows.server", () => ({
+ workflowsEnabledForCompany: vi.fn(async () => true)
+}));
vi.mock("../../db", () => ({ getJobDatabaseClient }));
vi.mock("./owner", () => ({
// The engine reads the company custom fields through this client; a bare {} has no
diff --git a/packages/jobs/src/workflows/engine/manual.ts b/packages/jobs/src/workflows/engine/manual.ts
index 6f051705fd..c3c6970b50 100644
--- a/packages/jobs/src/workflows/engine/manual.ts
+++ b/packages/jobs/src/workflows/engine/manual.ts
@@ -1,9 +1,9 @@
-import { datetime } from "@carbon/utils";
import {
createWorkflowCatalog,
type RunTrigger,
type WorkflowDefinition
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
+import { datetime } from "@carbon/utils";
import { nanoid } from "nanoid";
import { getJobDatabaseClient } from "../../db";
import type { EngineLogger, EngineStep, RunPayload } from "./execute";
diff --git a/packages/jobs/src/workflows/engine/owner.ts b/packages/jobs/src/workflows/engine/owner.ts
index 1691e92b51..3c0e7073e2 100644
--- a/packages/jobs/src/workflows/engine/owner.ts
+++ b/packages/jobs/src/workflows/engine/owner.ts
@@ -5,8 +5,8 @@ import {
} from "@carbon/auth";
import { getUserScopedClient } from "@carbon/auth/client.server";
import type { Database, Json } from "@carbon/database";
+import type { PermissionAction } from "@carbon/ee/workflows";
import { getLogger } from "@carbon/logger";
-import type { PermissionAction } from "@carbon/workflows";
import type { SupabaseClient } from "@supabase/supabase-js";
const log = getLogger("workflows");
diff --git a/packages/jobs/src/workflows/engine/walk.test.ts b/packages/jobs/src/workflows/engine/walk.test.ts
index 0ba709652e..4f8416bfb6 100644
--- a/packages/jobs/src/workflows/engine/walk.test.ts
+++ b/packages/jobs/src/workflows/engine/walk.test.ts
@@ -4,7 +4,7 @@ import {
type WorkflowDefinition,
type WorkflowEdge,
type WorkflowNode
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { describe, expect, it } from "vitest";
import {
advance,
diff --git a/packages/jobs/src/workflows/engine/walk.ts b/packages/jobs/src/workflows/engine/walk.ts
index d7da00ce17..5d8593114f 100644
--- a/packages/jobs/src/workflows/engine/walk.ts
+++ b/packages/jobs/src/workflows/engine/walk.ts
@@ -2,7 +2,7 @@ import {
DEFAULT_HANDLE,
type TriggerNode,
type WorkflowDefinition
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
export const MAX_NODE_EXECUTIONS = 500;
diff --git a/packages/jobs/src/workflows/event-ids.ts b/packages/jobs/src/workflows/event-ids.ts
index 45ec20f377..6c3a903241 100644
--- a/packages/jobs/src/workflows/event-ids.ts
+++ b/packages/jobs/src/workflows/event-ids.ts
@@ -4,7 +4,7 @@ import {
customFieldEventId,
ENTITY_BY_TABLE,
WORKFLOW_EVENTS
-} from "@carbon/workflows";
+} from "@carbon/ee/workflows";
import { computeDiff } from "../inngest/functions/events/diff";
// A facade over module-load maps; building it once here keeps the hot path allocation-free.
diff --git a/packages/jobs/src/workflows/matcher.ts b/packages/jobs/src/workflows/matcher.ts
index 2fe6581211..1003e9c4f4 100644
--- a/packages/jobs/src/workflows/matcher.ts
+++ b/packages/jobs/src/workflows/matcher.ts
@@ -1,5 +1,5 @@
import type { KyselyDatabase } from "@carbon/database/client";
-import { MAX_CHAIN_DEPTH, type Origin } from "@carbon/workflows";
+import { MAX_CHAIN_DEPTH, type Origin } from "@carbon/ee/workflows";
import type { Kysely } from "kysely";
import type { CausingRun, MatchInput, RunTrace, Subscriber } from "./types";
diff --git a/packages/jobs/src/workflows/scheduler.ts b/packages/jobs/src/workflows/scheduler.ts
index b9667af439..cf851d2605 100644
--- a/packages/jobs/src/workflows/scheduler.ts
+++ b/packages/jobs/src/workflows/scheduler.ts
@@ -1,5 +1,5 @@
import type { KyselyDatabase } from "@carbon/database/client";
-import { findTriggerSchedule, nextRunAfter } from "@carbon/workflows";
+import { findTriggerSchedule, nextRunAfter } from "@carbon/ee/workflows";
import { type Kysely, sql } from "kysely";
import type { MatchResult } from "./matcher";
import { insertRunsAndBuildEvents, type PlannedRun } from "./matcher";
diff --git a/packages/jobs/src/workflows/types.ts b/packages/jobs/src/workflows/types.ts
index e62d19bf8c..5f4ac55641 100644
--- a/packages/jobs/src/workflows/types.ts
+++ b/packages/jobs/src/workflows/types.ts
@@ -1,4 +1,4 @@
-import type { Origin, RunTrigger } from "@carbon/workflows";
+import type { Origin, RunTrigger } from "@carbon/ee/workflows";
/** A workflowTriggerEvent row joined to its workflow's owner. */
export type Subscriber = {
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 2f301340ad..b8c14fdaec 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -8,7 +8,7 @@
"@carbon/logger": "workspace:*",
"@carbon/notifications": "workspace:*",
"@carbon/utils": "workspace:*",
- "@carbon/workflows": "workspace:*",
+ "@carbon/workflows-core": "workspace:*",
"@slack/web-api": "catalog:",
"@supabase/supabase-js": "catalog:",
"inngest": "3.54.0",
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 52add4dcf3..f6404da0f8 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -3,7 +3,7 @@ import type {
NotificationDestination,
NotificationEvent
} from "@carbon/notifications";
-import type { RunTrigger } from "@carbon/workflows";
+import type { RunTrigger } from "@carbon/workflows-core";
type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];
diff --git a/packages/lib/src/workflows/raise-moment.ts b/packages/lib/src/workflows/raise-moment.ts
index 63284da4e2..9c3f9a461d 100644
--- a/packages/lib/src/workflows/raise-moment.ts
+++ b/packages/lib/src/workflows/raise-moment.ts
@@ -1,5 +1,5 @@
import { getLogger } from "@carbon/logger";
-import type { MomentKey, MomentPayload } from "@carbon/workflows";
+import type { MomentKey, MomentPayload } from "@carbon/workflows-core";
import { nanoid } from "nanoid";
import { trigger } from "../trigger";
diff --git a/packages/planning/AGENTS.md b/packages/planning/AGENTS.md
new file mode 100644
index 0000000000..88501ebb3b
--- /dev/null
+++ b/packages/planning/AGENTS.md
@@ -0,0 +1,61 @@
+# @carbon/planning
+
+Community-licensed (AGPLv3) Material Planning engines: **MRP** (Material
+Requirements Planning) and **finite scheduling** (the job scheduler). Both run
+**in-process in Node**, relocated from the Supabase edge runtime. This package
+was carved out of `@carbon/ee` so that Material Planning (Purchasing + Production
+planning screens) and the scheduler are free — no free user runs Enterprise code
+to plan materials.
+
+## Always
+
+- MUST be **dependency-injected**: every entry point takes a caller-created
+ `Kysely` handle (and, for MRP, a service-role Supabase client). The caller
+ authenticates first; this package never constructs a DB client.
+- MUST be imported only from server contexts — route actions, `*.service.ts`,
+ `*.server.ts`, or `@carbon/jobs` handlers. **Server-only**: it pulls in
+ `pg`/Kysely, so it must never reach a browser bundle.
+- MUST reach shared edge-lib deps through `@carbon/database` subpath barrels
+ (types → `@carbon/database`, postgres → `@carbon/database/client`,
+ `explodeBom` → `@carbon/database/mrp-engine`).
+
+## Never
+
+- Never add an entitlement/plan gate here. This is CE — Material Planning is
+ ungated. (Gating lives at call sites if a feature ever needs it.)
+- Never construct a connection/pool inside this package.
+
+## Validation Commands
+
+```bash
+pnpm --filter @carbon/planning test
+pnpm --filter @carbon/planning typecheck
+```
+
+## Key Exports
+
+Single subpath `@carbon/planning` (`./src/index.ts`):
+
+| Export | Provides |
+|--------|----------|
+| `runMrp(client, db, payload)` | Material Requirements Planning (`src/mrp/mrp.ts`; formerly the `mrp` edge function) |
+| `runLocationSchedule` / `runExpediteWhatIf` | Finite scheduling — regenerate a whole location, or a simulate-only expedite what-if (`src/scheduling/run-schedule.ts`) |
+| `resolveLocationWindows` / `resolveWorkCenterWindows` / `subtractIntervals` | Machine/work-center availability window resolvers (`src/scheduling/`) |
+| types (`LadderShiftRow`, `MrpPayload`, `MrpResult`, `LocationScheduleResult`, `ExpediteWhatIfResult`, `NewlyLateJob`, …) | Engine type surface |
+
+## Consumers
+
+- `@carbon/jobs` — `scheduled/mrp.ts` (`runMrp`), `tasks/recalculate.ts` &
+ `scheduled/schedule-inputs-changed.ts` (`runLocationSchedule`).
+- `apps/erp` — `production.service.ts` (dynamic imports of `runMrp` /
+ `runLocationSchedule` / `runExpediteWhatIf`), `forecast.server.ts`,
+ `routes/api+/schedule.ts`, `routes/api+/kanban.$id.tsx`,
+ `routes/x+/job+/$jobId.status.tsx`.
+
+## Cross-References
+
+- `.claude/rules/mrp-system.md` — MRP run flow and engine internals.
+- `.claude/rules/scheduling-data-structures.md` — finite scheduling data model.
+- `.claude/rules/supersession-system.md` — supersession redirects MRP consumes.
+- `packages/database/AGENTS.md` — the `@carbon/database` subpath barrels this
+ engine depends on (`./mrp-engine`, `./client`, `./methods`, …).
diff --git a/packages/workflows/package.json b/packages/planning/package.json
similarity index 70%
rename from packages/workflows/package.json
rename to packages/planning/package.json
index 1d09d82f9b..97c2b6de79 100644
--- a/packages/workflows/package.json
+++ b/packages/planning/package.json
@@ -1,12 +1,11 @@
{
- "name": "@carbon/workflows",
+ "name": "@carbon/planning",
"private": true,
"version": "0.0.0",
+ "type": "module",
"sideEffects": false,
"exports": {
- ".": "./src/index.ts",
- "./help": "./src/catalog/help.generated.ts",
- "./labels": "./src/catalog/labels.generated.ts"
+ ".": "./src/index.ts"
},
"scripts": {
"clean": "rimraf .turbo node_modules",
@@ -15,16 +14,15 @@
"typecheck": "tsgo --noEmit"
},
"dependencies": {
+ "@carbon/database": "workspace:*",
"@carbon/utils": "workspace:*",
"@internationalized/date": "catalog:",
- "@lingui/core": "catalog:",
+ "@supabase/supabase-js": "catalog:",
+ "kysely": "catalog:",
"zod": "catalog:"
},
"devDependencies": {
"@carbon/config": "workspace:*",
- "@carbon/database": "workspace:*",
- "@carbon/glossary": "workspace:*",
- "kysely": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
diff --git a/packages/ee/src/planning/index.ts b/packages/planning/src/index.ts
similarity index 93%
rename from packages/ee/src/planning/index.ts
rename to packages/planning/src/index.ts
index 33e07476c1..3922031bee 100644
--- a/packages/ee/src/planning/index.ts
+++ b/packages/planning/src/index.ts
@@ -1,4 +1,4 @@
-// @carbon/ee/planning — the planning engines (MRP + finite scheduling),
+// @carbon/planning — the planning engines (MRP + finite scheduling),
// relocated from the Supabase edge runtime to run in-process in Node. Every
// entry point takes an injected Kysely handle (and, for MRP, a service-role
// Supabase client); callers authenticate first. Server-only — pulls in
diff --git a/packages/ee/src/planning/mrp/mrp.ts b/packages/planning/src/mrp/mrp.ts
similarity index 100%
rename from packages/ee/src/planning/mrp/mrp.ts
rename to packages/planning/src/mrp/mrp.ts
diff --git a/packages/ee/src/planning/scheduling/apply-work-center-selections.test.ts b/packages/planning/src/scheduling/apply-work-center-selections.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/apply-work-center-selections.test.ts
rename to packages/planning/src/scheduling/apply-work-center-selections.test.ts
diff --git a/packages/ee/src/planning/scheduling/apply-work-center-selections.ts b/packages/planning/src/scheduling/apply-work-center-selections.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/apply-work-center-selections.ts
rename to packages/planning/src/scheduling/apply-work-center-selections.ts
diff --git a/packages/ee/src/planning/scheduling/assembly-handler.ts b/packages/planning/src/scheduling/assembly-handler.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/assembly-handler.ts
rename to packages/planning/src/scheduling/assembly-handler.ts
diff --git a/packages/ee/src/planning/scheduling/batch-scheduler.test.ts b/packages/planning/src/scheduling/batch-scheduler.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/batch-scheduler.test.ts
rename to packages/planning/src/scheduling/batch-scheduler.test.ts
diff --git a/packages/ee/src/planning/scheduling/batch-scheduler.ts b/packages/planning/src/scheduling/batch-scheduler.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/batch-scheduler.ts
rename to packages/planning/src/scheduling/batch-scheduler.ts
diff --git a/packages/ee/src/planning/scheduling/calendar-utils.test.ts b/packages/planning/src/scheduling/calendar-utils.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/calendar-utils.test.ts
rename to packages/planning/src/scheduling/calendar-utils.test.ts
diff --git a/packages/ee/src/planning/scheduling/calendar-utils.ts b/packages/planning/src/scheduling/calendar-utils.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/calendar-utils.ts
rename to packages/planning/src/scheduling/calendar-utils.ts
diff --git a/packages/ee/src/planning/scheduling/conflict-messages.test.ts b/packages/planning/src/scheduling/conflict-messages.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/conflict-messages.test.ts
rename to packages/planning/src/scheduling/conflict-messages.test.ts
diff --git a/packages/ee/src/planning/scheduling/conflict-messages.ts b/packages/planning/src/scheduling/conflict-messages.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/conflict-messages.ts
rename to packages/planning/src/scheduling/conflict-messages.ts
diff --git a/packages/ee/src/planning/scheduling/date-calculator.ts b/packages/planning/src/scheduling/date-calculator.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/date-calculator.ts
rename to packages/planning/src/scheduling/date-calculator.ts
diff --git a/packages/ee/src/planning/scheduling/date-utils.test.ts b/packages/planning/src/scheduling/date-utils.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/date-utils.test.ts
rename to packages/planning/src/scheduling/date-utils.test.ts
diff --git a/packages/ee/src/planning/scheduling/date-utils.ts b/packages/planning/src/scheduling/date-utils.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/date-utils.ts
rename to packages/planning/src/scheduling/date-utils.ts
diff --git a/packages/ee/src/planning/scheduling/dependency-manager.ts b/packages/planning/src/scheduling/dependency-manager.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/dependency-manager.ts
rename to packages/planning/src/scheduling/dependency-manager.ts
diff --git a/packages/ee/src/planning/scheduling/determinism.test.ts b/packages/planning/src/scheduling/determinism.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/determinism.test.ts
rename to packages/planning/src/scheduling/determinism.test.ts
diff --git a/packages/ee/src/planning/scheduling/duration-calculator.test.ts b/packages/planning/src/scheduling/duration-calculator.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/duration-calculator.test.ts
rename to packages/planning/src/scheduling/duration-calculator.test.ts
diff --git a/packages/ee/src/planning/scheduling/duration-calculator.ts b/packages/planning/src/scheduling/duration-calculator.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/duration-calculator.ts
rename to packages/planning/src/scheduling/duration-calculator.ts
diff --git a/packages/ee/src/planning/scheduling/envelope.test.ts b/packages/planning/src/scheduling/envelope.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/envelope.test.ts
rename to packages/planning/src/scheduling/envelope.test.ts
diff --git a/packages/ee/src/planning/scheduling/machine-availability.test.ts b/packages/planning/src/scheduling/machine-availability.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/machine-availability.test.ts
rename to packages/planning/src/scheduling/machine-availability.test.ts
diff --git a/packages/ee/src/planning/scheduling/machine-availability.ts b/packages/planning/src/scheduling/machine-availability.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/machine-availability.ts
rename to packages/planning/src/scheduling/machine-availability.ts
diff --git a/packages/ee/src/planning/scheduling/master-data-provider.ts b/packages/planning/src/scheduling/master-data-provider.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/master-data-provider.ts
rename to packages/planning/src/scheduling/master-data-provider.ts
diff --git a/packages/ee/src/planning/scheduling/material-manager.ts b/packages/planning/src/scheduling/material-manager.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/material-manager.ts
rename to packages/planning/src/scheduling/material-manager.ts
diff --git a/packages/ee/src/planning/scheduling/need-by-calculator.test.ts b/packages/planning/src/scheduling/need-by-calculator.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/need-by-calculator.test.ts
rename to packages/planning/src/scheduling/need-by-calculator.test.ts
diff --git a/packages/ee/src/planning/scheduling/need-by-calculator.ts b/packages/planning/src/scheduling/need-by-calculator.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/need-by-calculator.ts
rename to packages/planning/src/scheduling/need-by-calculator.ts
diff --git a/packages/ee/src/planning/scheduling/operator-eligibility.test.ts b/packages/planning/src/scheduling/operator-eligibility.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/operator-eligibility.test.ts
rename to packages/planning/src/scheduling/operator-eligibility.test.ts
diff --git a/packages/ee/src/planning/scheduling/operator-eligibility.ts b/packages/planning/src/scheduling/operator-eligibility.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/operator-eligibility.ts
rename to packages/planning/src/scheduling/operator-eligibility.ts
diff --git a/packages/ee/src/planning/scheduling/people-utils.test.ts b/packages/planning/src/scheduling/people-utils.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/people-utils.test.ts
rename to packages/planning/src/scheduling/people-utils.test.ts
diff --git a/packages/ee/src/planning/scheduling/people-utils.ts b/packages/planning/src/scheduling/people-utils.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/people-utils.ts
rename to packages/planning/src/scheduling/people-utils.ts
diff --git a/packages/ee/src/planning/scheduling/priority-calculator.ts b/packages/planning/src/scheduling/priority-calculator.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/priority-calculator.ts
rename to packages/planning/src/scheduling/priority-calculator.ts
diff --git a/packages/ee/src/planning/scheduling/run-schedule.ts b/packages/planning/src/scheduling/run-schedule.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/run-schedule.ts
rename to packages/planning/src/scheduling/run-schedule.ts
diff --git a/packages/ee/src/planning/scheduling/scheduling-engine.ts b/packages/planning/src/scheduling/scheduling-engine.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/scheduling-engine.ts
rename to packages/planning/src/scheduling/scheduling-engine.ts
diff --git a/packages/ee/src/planning/scheduling/slot-allocator.test.ts b/packages/planning/src/scheduling/slot-allocator.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/slot-allocator.test.ts
rename to packages/planning/src/scheduling/slot-allocator.test.ts
diff --git a/packages/ee/src/planning/scheduling/slot-allocator.ts b/packages/planning/src/scheduling/slot-allocator.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/slot-allocator.ts
rename to packages/planning/src/scheduling/slot-allocator.ts
diff --git a/packages/ee/src/planning/scheduling/test-helpers.ts b/packages/planning/src/scheduling/test-helpers.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/test-helpers.ts
rename to packages/planning/src/scheduling/test-helpers.ts
diff --git a/packages/ee/src/planning/scheduling/types.ts b/packages/planning/src/scheduling/types.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/types.ts
rename to packages/planning/src/scheduling/types.ts
diff --git a/packages/ee/src/planning/scheduling/work-center-selector.test.ts b/packages/planning/src/scheduling/work-center-selector.test.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/work-center-selector.test.ts
rename to packages/planning/src/scheduling/work-center-selector.test.ts
diff --git a/packages/ee/src/planning/scheduling/work-center-selector.ts b/packages/planning/src/scheduling/work-center-selector.ts
similarity index 100%
rename from packages/ee/src/planning/scheduling/work-center-selector.ts
rename to packages/planning/src/scheduling/work-center-selector.ts
diff --git a/packages/workflows/tsconfig.json b/packages/planning/tsconfig.json
similarity index 100%
rename from packages/workflows/tsconfig.json
rename to packages/planning/tsconfig.json
diff --git a/packages/workflows/vitest.config.ts b/packages/planning/vitest.config.ts
similarity index 100%
rename from packages/workflows/vitest.config.ts
rename to packages/planning/vitest.config.ts
diff --git a/packages/workflows-core/package.json b/packages/workflows-core/package.json
new file mode 100644
index 0000000000..c443324c70
--- /dev/null
+++ b/packages/workflows-core/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@carbon/workflows-core",
+ "private": true,
+ "version": "0.0.0",
+ "type": "module",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "clean": "rimraf .turbo node_modules",
+ "lint": "biome lint --write ",
+ "test": "vitest run",
+ "typecheck": "tsgo --noEmit"
+ },
+ "dependencies": {
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@carbon/config": "workspace:*",
+ "typescript": "catalog:",
+ "vitest": "catalog:"
+ }
+}
diff --git a/packages/workflows-core/src/index.ts b/packages/workflows-core/src/index.ts
new file mode 100644
index 0000000000..4ea84d4f72
--- /dev/null
+++ b/packages/workflows-core/src/index.ts
@@ -0,0 +1,7 @@
+export {
+ MOMENT_OUTPUT_KEYS,
+ type MomentEntityRef,
+ type MomentKey,
+ type MomentPayload
+} from "./moments";
+export { type RunTrigger, runTriggerSchema } from "./run-trigger";
diff --git a/packages/workflows-core/src/moments.ts b/packages/workflows-core/src/moments.ts
new file mode 100644
index 0000000000..1044390794
--- /dev/null
+++ b/packages/workflows-core/src/moments.ts
@@ -0,0 +1,32 @@
+/**
+ * The CE-safe wire contract for workflow "moments" — business events a row
+ * change cannot express. `@carbon/lib` (`raise-moment.ts`) needs `MomentKey` /
+ * `MomentPayload` type-only, and importing them from the full workflow engine
+ * (now `@carbon/ee/workflows`) would create a `lib → ee → lib` package cycle.
+ *
+ * The FULL declarations (labels, permissions, `t.entity(...)` output types) stay
+ * the engine's source of truth in `catalog/moments.ts` (`WORKFLOW_MOMENTS`). This
+ * leaf carries ONLY each moment's output KEY NAMES — all `MomentPayload<K>`
+ * derives from — so it stays zod/dep-free. `scripts/check-workflow-catalog.ts`
+ * asserts the two never drift (same keys, same output-key names).
+ */
+export const MOMENT_OUTPUT_KEYS = {
+ "production.jobReleased": ["job", "releasedBy"],
+ "production.jobHeld": ["job", "heldBy"],
+ "production.jobOperationCompleted": ["job", "jobOperation", "completedBy"],
+ "sales.quoteSent": ["quote", "sentBy"],
+ "sales.quoteAccepted": ["quote", "salesOrder"],
+ "inventory.receiptPosted": ["receipt", "postedBy"],
+ "inventory.shipmentPosted": ["shipment", "postedBy"],
+ "invoicing.salesInvoicePosted": ["salesInvoice", "postedBy"],
+ "invoicing.purchaseInvoicePosted": ["purchaseInvoice", "postedBy"]
+} as const;
+
+export type MomentKey = keyof typeof MOMENT_OUTPUT_KEYS;
+
+/** Entity outputs are passed as an id, never a row snapshot. */
+export type MomentEntityRef = { id: string };
+
+export type MomentPayload<K extends MomentKey> = {
+ [O in (typeof MOMENT_OUTPUT_KEYS)[K][number]]: MomentEntityRef;
+};
diff --git a/packages/workflows/src/run-trigger.ts b/packages/workflows-core/src/run-trigger.ts
similarity index 100%
rename from packages/workflows/src/run-trigger.ts
rename to packages/workflows-core/src/run-trigger.ts
diff --git a/packages/workflows-core/tsconfig.json b/packages/workflows-core/tsconfig.json
new file mode 100644
index 0000000000..bb1e2564c8
--- /dev/null
+++ b/packages/workflows-core/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "extends": "@carbon/config/tsconfig/base.json",
+ "include": ["src"],
+ "exclude": ["dist", "build", "node_modules"]
+}
diff --git a/packages/workflows-core/vitest.config.ts b/packages/workflows-core/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/workflows-core/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ddca23a006..b04cf7bd76 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -699,6 +699,9 @@ importers:
'@carbon/onboarding':
specifier: workspace:*
version: link:../../packages/onboarding
+ '@carbon/planning':
+ specifier: workspace:*
+ version: link:../../packages/planning
'@carbon/printing':
specifier: workspace:*
version: link:../../packages/printing
@@ -714,9 +717,6 @@ importers:
'@carbon/viewer':
specifier: workspace:*
version: link:../../packages/viewer
- '@carbon/workflows':
- specifier: workspace:*
- version: link:../../packages/workflows
'@dagrejs/dagre':
specifier: ^1.1.4
version: 1.1.8
@@ -1995,9 +1995,9 @@ importers:
'@carbon/config':
specifier: workspace:*
version: link:../config
- '@carbon/workflows':
+ '@carbon/ee':
specifier: workspace:*
- version: link:../workflows
+ version: link:../ee
'@types/node':
specifier: ^22
version: 22.19.7
@@ -2359,9 +2359,18 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../utils
+ '@carbon/workflows-core':
+ specifier: workspace:*
+ version: link:../workflows-core
'@internationalized/date':
specifier: 'catalog:'
version: 3.12.0
+ '@lingui/core':
+ specifier: 'catalog:'
+ '@modelcontextprotocol/sdk':
+ specifier: 1.29.0
+ version: 1.29.0([email protected])
'@slack/bolt':
specifier: 4.4.0
version: 4.4.0(@types/[email protected])
@@ -2422,6 +2431,9 @@ importers:
tsup:
specifier: 'catalog:'
+ zbsearch:
+ specifier: 'catalog:'
+ version: 4.0.0
zod:
specifier: 'catalog:'
version: 4.5.4
@@ -2429,9 +2441,15 @@ importers:
specifier: 'catalog:'
version: 3.0.3([email protected])
devDependencies:
+ '@carbon/api':
+ specifier: workspace:*
+ version: link:../api
'@carbon/config':
specifier: workspace:*
version: link:../config
+ '@carbon/glossary':
+ specifier: workspace:*
+ version: link:../glossary
'@logtape/logtape':
specifier: 'catalog:'
version: 2.2.3
@@ -2703,6 +2721,9 @@ importers:
'@carbon/notifications':
specifier: workspace:*
version: link:../notifications
+ '@carbon/planning':
+ specifier: workspace:*
+ version: link:../planning
'@carbon/printing':
specifier: workspace:*
version: link:../printing
@@ -2715,9 +2736,6 @@ importers:
'@carbon/viewer':
specifier: workspace:*
version: link:../viewer
- '@carbon/workflows':
- specifier: workspace:*
- version: link:../workflows
'@internationalized/date':
specifier: 'catalog:'
version: 3.12.0
@@ -2876,9 +2894,9 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../utils
- '@carbon/workflows':
+ '@carbon/workflows-core':
specifier: workspace:*
- version: link:../workflows
+ version: link:../workflows-core
'@slack/web-api':
specifier: 'catalog:'
version: 7.10.0
@@ -3079,6 +3097,37 @@ importers:
specifier: 'catalog:'
+ packages/planning:
+ dependencies:
+ '@carbon/database':
+ specifier: workspace:*
+ version: link:../database
+ '@carbon/utils':
+ specifier: workspace:*
+ version: link:../utils
+ '@internationalized/date':
+ specifier: 'catalog:'
+ version: 3.12.0
+ '@supabase/supabase-js':
+ specifier: 'catalog:'
+ version: 2.80.0
+ kysely:
+ specifier: 'catalog:'
+ version: 0.28.17
+ zod:
+ specifier: 'catalog:'
+ version: 4.5.4
+ devDependencies:
+ '@carbon/config':
+ specifier: workspace:*
+ version: link:../config
+ typescript:
+ specifier: 'catalog:'
+ version: 5.8.3
+ vitest:
+ specifier: 'catalog:'
+
packages/printing:
dependencies:
'@carbon/kv':
@@ -3799,17 +3848,8 @@ importers:
specifier: 'catalog:'
- packages/workflows:
+ packages/workflows-core:
dependencies:
- '@carbon/utils':
- specifier: workspace:*
- version: link:../utils
- '@internationalized/date':
- specifier: 'catalog:'
- version: 3.12.0
- '@lingui/core':
- specifier: 'catalog:'
zod:
specifier: 'catalog:'
version: 4.5.4
@@ -3817,15 +3857,6 @@ importers:
'@carbon/config':
specifier: workspace:*
version: link:../config
- '@carbon/database':
- specifier: workspace:*
- version: link:../database
- '@carbon/glossary':
- specifier: workspace:*
- version: link:../glossary
- kysely:
- specifier: 'catalog:'
- version: 0.28.17
typescript:
specifier: 'catalog:'
version: 5.8.3
diff --git a/scripts/check-workflow-catalog.ts b/scripts/check-workflow-catalog.ts
index 6c5936b1b9..f7f09cdd19 100644
--- a/scripts/check-workflow-catalog.ts
+++ b/scripts/check-workflow-catalog.ts
@@ -8,26 +8,27 @@ import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import schema from "../packages/database/src/swagger-docs-schema";
-import { WORKFLOW_ACTIONS } from "../packages/workflows/src/catalog/actions";
+import { WORKFLOW_ACTIONS } from "../packages/ee/src/workflows/catalog/actions";
import {
WORKFLOW_ACTION_CATALOG,
WORKFLOW_OPERATION_CATALOG
-} from "../packages/workflows/src/catalog/actions.generated";
-import { buildCatalog, validateCatalogInputs } from "../packages/workflows/src/catalog/build";
-import { WORKFLOW_ENTITY_REGISTRY } from "../packages/workflows/src/catalog/entities";
+} from "../packages/ee/src/workflows/catalog/actions.generated";
+import { buildCatalog, validateCatalogInputs } from "../packages/ee/src/workflows/catalog/build";
+import { WORKFLOW_ENTITY_REGISTRY } from "../packages/ee/src/workflows/catalog/entities";
import {
WORKFLOW_ENTITIES,
WORKFLOW_EVENTS
-} from "../packages/workflows/src/catalog/events.generated";
+} from "../packages/ee/src/workflows/catalog/events.generated";
// Direct import, unlike labels: this file has no `msg` macro, so plain Node can read it.
-import { WORKFLOW_FIELD_HELP } from "../packages/workflows/src/catalog/help.generated";
-import { WORKFLOW_MOMENTS } from "../packages/workflows/src/catalog/moments";
-import { WORKFLOW_OPERATIONS } from "../packages/workflows/src/catalog/operations";
+import { WORKFLOW_FIELD_HELP } from "../packages/ee/src/workflows/catalog/help.generated";
+import { WORKFLOW_MOMENTS } from "../packages/ee/src/workflows/catalog/moments";
+import { WORKFLOW_OPERATIONS } from "../packages/ee/src/workflows/catalog/operations";
+import { MOMENT_OUTPUT_KEYS } from "../packages/workflows-core/src/moments";
const ROOT = process.cwd();
const LABELS_FILE = path.join(
ROOT,
- "packages/workflows/src/catalog/labels.generated.ts"
+ "packages/ee/src/workflows/catalog/labels.generated.ts"
);
const TOOL_METADATA_FILE = path.join(
ROOT,
@@ -74,7 +75,37 @@ for (const key of Object.keys(WORKFLOW_MOMENTS)) {
for (const key of raised.keys()) {
if (!(key in WORKFLOW_MOMENTS)) {
fail(
- `raiseMoment("${key}") names a moment that is not declared in packages/workflows/src/catalog/moments.ts.`
+ `raiseMoment("${key}") names a moment that is not declared in packages/ee/src/workflows/catalog/moments.ts.`
+ );
+ }
+}
+
+// The CE leaf `@carbon/workflows-core` mirrors each moment's output KEY NAMES —
+// `MomentPayload<K>` derives from `MOMENT_OUTPUT_KEYS`, and the engine re-exports
+// the leaf's `MomentKey`/`MomentPayload`, so a drift between the two is invisible
+// to the type checker. This is the invariant that keeps them honest.
+const leafMoments = MOMENT_OUTPUT_KEYS as Record<string, readonly string[]>;
+for (const key of Object.keys(WORKFLOW_MOMENTS)) {
+ const engineKeys = Object.keys(
+ WORKFLOW_MOMENTS[key as keyof typeof WORKFLOW_MOMENTS].outputs
+ ).sort();
+ const leafKeys = leafMoments[key];
+ if (!leafKeys) {
+ fail(
+ `Moment "${key}" is in WORKFLOW_MOMENTS but missing from MOMENT_OUTPUT_KEYS in @carbon/workflows-core — add it (with the same output keys) so MomentPayload stays correct.`
+ );
+ continue;
+ }
+ if (engineKeys.join(",") !== [...leafKeys].sort().join(",")) {
+ fail(
+ `Moment "${key}" output keys drifted: WORKFLOW_MOMENTS has [${engineKeys}] but @carbon/workflows-core MOMENT_OUTPUT_KEYS has [${[...leafKeys].sort()}]. Update packages/workflows-core/src/moments.ts to match.`
+ );
+ }
+}
+for (const key of Object.keys(leafMoments)) {
+ if (!(key in WORKFLOW_MOMENTS)) {
+ fail(
+ `Moment "${key}" is in @carbon/workflows-core MOMENT_OUTPUT_KEYS but not declared in WORKFLOW_MOMENTS — remove it from packages/workflows-core/src/moments.ts.`
);
}
}
diff --git a/scripts/generate-workflow-catalog.ts b/scripts/generate-workflow-catalog.ts
index 9ec6819264..ba6e5c5764 100644
--- a/scripts/generate-workflow-catalog.ts
+++ b/scripts/generate-workflow-catalog.ts
@@ -10,16 +10,16 @@
import fs from "node:fs";
import path from "node:path";
import schema from "../packages/database/src/swagger-docs-schema";
-import { WORKFLOW_ACTIONS } from "../packages/workflows/src/catalog/actions";
-import { buildCatalog } from "../packages/workflows/src/catalog/build";
-import { WORKFLOW_ENTITY_REGISTRY } from "../packages/workflows/src/catalog/entities";
-import { WORKFLOW_MOMENTS } from "../packages/workflows/src/catalog/moments";
-import { WORKFLOW_OPERATIONS } from "../packages/workflows/src/catalog/operations";
+import { WORKFLOW_ACTIONS } from "../packages/ee/src/workflows/catalog/actions";
+import { buildCatalog } from "../packages/ee/src/workflows/catalog/build";
+import { WORKFLOW_ENTITY_REGISTRY } from "../packages/ee/src/workflows/catalog/entities";
+import { WORKFLOW_MOMENTS } from "../packages/ee/src/workflows/catalog/moments";
+import { WORKFLOW_OPERATIONS } from "../packages/ee/src/workflows/catalog/operations";
// Resolved against the repo root; the script must be run from there.
const CATALOG_DIR = path.join(
process.cwd(),
- "packages/workflows/src/catalog"
+ "packages/ee/src/workflows/catalog"
);
const HEADER =
diff --git a/turbo.json b/turbo.json
index bff389fbe9..4d056623c3 100644
--- a/turbo.json
+++ b/turbo.json
@@ -23,7 +23,7 @@
"apps/erp/app/**",
"apps/mes/app/**",
"packages/react/src/**",
- "packages/workflows/src/**",
+ "packages/ee/src/workflows/**",
"packages/locale/locales/**/*.po"
],
"outputs": ["packages/locale/locales/**/*.mjs"]