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.
paths: - "apps/" - "packages/"
Coding Conventions (General)
Cross-cutting conventions for the whole repo. For deep dives, load the focused rules — this file does not repeat them:
| Topic | Rule |
|---|---|
| DB / migrations / RLS / multi-tenancy | conventions-database.md |
| ValidatedForm + zod validators + actions | conventions-forms.md |
Service functions ({module}.server.ts, {module}.service.ts) |
conventions-services.md, module-files.md |
| Components, animation, polish | conventions-ui.md |
Stack & Tooling
- Monorepo: pnpm workspaces. Workspaces are
apps/*andpackages/*(alsoci,examples/*). See rootpackage.json/pnpm-workspace.yaml. - Framework: React Router v7 (NOT Remix). Apps
apps/erpandapps/mesbuild withreact-router build. Routing usesremix-flat-routes. - Language: TypeScript everywhere. Never hand-edit generated DB types.
- License header: every source file opens with an SPDX header —
AGPL-3.0-only, orLicenseRef-Carbon-Commercialunderpackages/ee/and in.ee.files (spdx-license-headercheck). Write it withpnpm --filter @carbon/checks license-headers; moving a file across that boundary means swapping it (see commercial-licensing.md). - Backend data: Supabase client (
SupabaseClient<Database>) for most reads/ writes; Kysely for multi-row transactions (see services/database rules).
Imports
~/*→ app code, mapped to./app/*in each app'stsconfig.json(e.g.import { usePermissions } from "~/hooks").@carbon/*→ pnpm workspace packages underpackages/. Real packages include:@carbon/react,@carbon/form,@carbon/auth,@carbon/database,@carbon/utils,@carbon/documents,@carbon/jobs,@carbon/printing,@carbon/notifications,@carbon/stripe,@carbon/tiptap,@carbon/kv,@carbon/lib,@carbon/locale,@carbon/ee,@carbon/env,@carbon/config.react-routeris the framework import forLoaderFunctionArgs,ActionFunctionArgs,data,useNavigate, etc. — but NOTredirect.redirectcomes from@carbon/utils. It only goes to a path on this origin; anything else (an absolute URL,//host, an empty value) lands on the home page, so a destination read from a query string or a form needs no validation at the call site. Leaving the origin on purpose (OAuth provider, Stripe, ERP ↔ MES) isredirectExternal, with a URL the server built. Enforced by theno-raw-redirectcheck (@carbon/checks).- Server-only auth helpers come from subpaths:
@carbon/auth/auth.server(requirePermissions),@carbon/auth/session.server(flash), and@carbon/auth(error,success,assertIsPost).
import { Button, VStack } from "@carbon/react";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunctionArgs } from "react-router";
import { usePermissions } from "~/hooks";
App Module Layout
ERP feature code is organized by module under apps/erp/app/modules/{module}/:
modules/{module}/
├── {module}.server.ts # defineServiceFn operations: the module's API
├── {module}.service.ts # building blocks the operations call (server-only)
├── {module}.models.ts # zod validators + derived types
├── {module}.utils.ts # browser-safe helpers (optional)
├── types.ts # shared types (optional)
└── ui/ # feature components
There is no barrel. Import from the file that defines the thing
(~/modules/sales/sales.models, never ~/modules/sales). Full rules and the
checks that enforce them: module-files.md.
Folder names are kebab-case. Multi-word directories use hyphens, not
camelCase — packages/ee/src/paperless-parts, packages/ee/src/rules (not
paperlessParts). This applies to modules and package subdirs. The ui/
feature groupings inside a module are the exception: they are PascalCase and
match the feature (ui/StorageRules/, ui/SalesRules/, ui/WarehouseTransfers/),
as are the React component filenames inside them (StorageRuleForm.tsx). The
{module}.*.ts service/model file prefixes mirror their folder name.
A feature is not automatically a module. A module is a business domain, and
it owns exactly one {module}.server.ts / {module}.service.ts / {module}.models.ts set. Sub-features
live inside their domain module as a ui/{Feature}/ folder plus functions in
those files — e.g. storage rules live in ~/modules/inventory
and sales rules in ~/modules/sales, not in standalone modules/storage-rules /
modules/sales-rules directories. Create a new module only for a genuinely new
domain.
MES is lighter: services live under apps/mes/app/services/, components under
apps/mes/app/components/.
Routes
- File-based via
remix-flat-routes. Conventions seen inapps/*/app/routes/:_index.tsx,_layout.tsxand_public+/(pathless),x+/,api+/,file+/(folder groups),$param(dynamic segments),[.]pdf(escaped literals). - Loaders/actions destructure args typed by
react-router. The first thing an authenticated loader does isawait requirePermissions(request, { ... }), destructuring{ client, companyId, userId }(alsoemail,companyGroupId). - An action checks the request with
validator(schema).request(args, …)(@carbon/form), calls ONE service function throughcarbon(request)(@carbon/api/carbon.server) and returns its result, orrespond(request, result).redirect(...)for a navigating form. The service function holds the permission and the write. See conventions-forms.md and module-files.md. Older actions still runassertIsPost→requirePermissions→ a building block. - Loaders/actions return plain objects or
data(value, responseInit). Do NOT usejson(...)— that is the old Remix helper and is not the convention here. - A layout does NOT export
shouldRevalidateto skip its loader. Single fetch re-runs every matched loader on every navigation, and that is what keeps a page correct after a save, a redirect or another user's change. The skip was tried (2026-10-01 to 2026-10-06, 186 layouts) and removed: it depended on what React Router passes along, which is lost on a second redirect, and on realtime covering every table a layout reads. A slow layout loader is made faster (one query, the direct connection, work shared through middleware context), not skipped. The two exceptions are the root (same-pathname navigations) and the app shell (re-runs after five minutes), whose data does not change with the record on screen. Shell data that does not gate rendering is returned as a promise and read withuseResolved(~/hooks/useResolved) when a late value is harmless. Data that adds or removes something on first paint (a nav item, a card) is awaited instead: streamed in, it arrives after the page is drawn and pushes it around — the Implementation Hub's nav item and home card did exactly that. Await only the part that decides whether the thing exists (the hub row) and stream what fills it in (its progress), holding the layout until it lands.useResolvedkeeps the last value while a revalidation is pending, so a component that stays mounted across records passes the record id as its third argument (useResolved(promise, null, itemId)), or it shows the previous record's value until the new one arrives. - A route under
/xrenders<RecordOutlet />from@carbon/react, never a plain<Outlet />. React Router keeps a page mounted when only its params change, so a form's default values, an editor's content or auseStatecopy would stay the previous record's.RecordOutletremounts the page for another record and leaves it mounted when a drawer opens over it. Enforced byno-bare-outlet. - An index route that only redirects (
/x/issue/:id→…/details, a module root → its first page) also exportsmiddleware = [redirectBeforeLoaders(loader)]from@carbon/utils. The loaders of a matched branch run in parallel, so without it every parent loader runs for a request that is about to be redirected. Enforced by theindex-redirect-before-loaderscheck (@carbon/checks). - A legacy action throws its success redirect (
throw redirect(...)), notreturn. A cachedapi+loader exportsclientLoader = cachedClientLoader<typeof loader>(); no route exports aclientAction.
Errors: always log before you throw
- Never throw (or return) an error without logging it first. Declare a module
logger,
const logger = getLogger("erp", "<route-or-module>")from@carbon/logger, and calllogger.error("<what failed>", { companyId, ...context, error })beforethrow new Response(...)/throw new Error(...). - Why: a thrown
Responsefrom a loader/action goes straight to the client; React Router skipshandleErrorfor it, so an unlogged throw leaves no server trace. - Also log failures you deliberately swallow (best-effort cleanup, ignored
{ error }results,.catch(() => {})). - The body of a thrown 4xx
Responseis shown to the user on the route error screen (routeErrorCopy,@carbon/react), with its status. Write it for a person and say what was wrong ("The item could not be found…"); never pass a database or provider error as the body. A 5xx body is not shown. - Redirects (
throw redirect(...)) are control flow, not errors; no log needed.
Components & UI Library
- Reach for
@carbon/react(barrel export atpackages/react/src/index.tsx) and form fields from~/components/Form(re-exports@carbon/form+ domain selectors) before writing custom UI. Prefer built-in variants over ad-hocbg-*/text-*classes. - App-level shared components live in
apps/erp/app/components/and are re-exported from itsindex.ts. - A component or hook both ERP and MES need lives in a package (
@carbon/react,@carbon/auth,@carbon/utils), not as a copy in each app. An app file of the same name may only re-export it. Enforced by theno-duplicated-app-filecheck (@carbon/checks); the copies that predate it are baselined. - Functional components, props typed inline or via
type/z.infer<typeof validator>. - Do not seed
useStatefrom loader or route data: it is a copy that no reload updates. Compute a derived value during render; keep only the user's own input in state and combine it with the current data. Do not add an effect that copies the data in again. Enforced, for a hook result used in the same file, byno-state-copy-of-loader-data(@carbon/checks). - Styling is Tailwind. Theme colors are CSS variables — use
hsl(var(--primary))for theme-aware fills (e.g. Recharts), not hard-coded colors.
Validators
- zod, imported as
import { z } from "zod", withzfdfromzod-form-datafor FormData coercion:zfd.text(...),zfd.numeric(...),zfd.checkbox(). - Validate in route actions with
validator(schema).request(args, …)from@carbon/form(legacy actions:validator(schema).validate(formData)) — notschema.parse(). Full pattern in conventions-forms.md.
State
- Server state / route data: React Router loaders.
- Client cache of server data: TanStack Query through
@carbon/query. A cachedapi+loader iscachedClientLoader<typeof loader>(), keyed by its URL; components read withuseLoaderQuery(url); the root middleware invalidates after every mutation. No hand-written query keys (seeclientAction-patterns.md). - Realtime: private broadcast topics through
@carbon/query. A route declares its tables inhandle.realtime; the live lists (useItems,useCustomers,useSuppliers,usePeople) are queries kept current byLiveLists(seerealtime-system.md). - Global UI state: zustand (
apps/erp/app/stores/ui.ts). nanostores is gone from the repo.
Path Helpers
URLs are generated through the typed path helper at apps/erp/app/utils/path.ts
(import { path } from "~/utils/path"). Use path.to.* instead of hardcoded
URL strings in links, redirects, and form actions.
Theme System
Themes are defined in packages/utils/src/themes.ts (themes, the only list
of theme names) and selected via the useTheme() hook
(apps/erp/app/hooks/useTheme.tsx). Each theme supplies HSL values for CSS
variables (--primary, --background, --foreground, --card, --popover,
--secondary, --muted, --accent, --destructive) and its four mesh
colors per mode (the ERP's onboarding backdrop). Theme names: zinc
(the default, DEFAULT_THEME_NAME), neutral, red, orange, yellow,
green, blue, violet, plus seasonal ones.
The choice is a theme cookie per browser, never a database column. Each app's
getTheme (services/theme.server.ts) is the theme to RENDER: it resolves
through themeForRequest and resolveTheme, which return the default for a
name no longer in themes, so removing a theme needs no migration and breaks
no browser that still holds it. The pickers show getTheme as chosen. The
root Document renders the loader's name with themeByName, so the season is
decided once, on the server.
A seasonal theme (seasonalThemes, never in themes) shows only inside the
signed-in app (isAppPath, /x): every other page (sign-in, shared links,
onboarding) gets the stored everyday theme, so public pages always show the
brand, and the onboarding theme step lists only themes. Inside the app it is
on by default while in season: it replaces every theme for everyone who has not
picked another one, and when the season ends everyone is back on their own
cookie. While in season every picker inside the app (the ERP avatar menu and
mobile profile sheet, Account → Appearance) lists it first (pickableThemes),
and themeColorValidator accepts it. What a pick writes is
themeCookieWrites (@carbon/utils, as data; each app's setTheme
serializes it with its cookie domain): an everyday theme is stored, and when
picked inside the app (inApp) while a seasonal theme is on, a second cookie,
SEASONAL_OFF_COOKIE, holds the seasonal theme's name for 30 days, which
themeForRequest passes to resolveTheme as seasonalOff. Onboarding's pick
(inApp: false) only stores the theme. Picking the seasonal theme clears that
cookie and keeps the stored one. Its season is the available window on the
theme (ThemeWindow, month and day inside one calendar year; Halloween is
October 27 to 31), and that window is the only switch: no flag, no deploy on
the day. The server has no time zone for the user, so isInSeason is true
while it is the season anywhere on Earth (UTC+14 reaches from, UTC-12 has
not left to); a fixed UTC check turned it on hours late east of UTC. To
preview one locally, widen its window. A seasonal theme lives in its own file
(halloween-theme.ts) and declares everything about itself on the
SeasonalTheme object (its window, its colors and mesh), so no other code
names it: removing it is that file,
its seasonalThemes entry and its index.ts export. themes.test.ts tests
the window on a fixture and loops over seasonalThemes, so it survives the
removal unchanged.
The Halloween decorations (spider, bats, fog, witch on the loading bar, hat,
Oct 31 date marker, the "boo" ghost) live in packages/react/src/Halloween/,
exported as @carbon/react/Halloween and mounted once in each shell
(<HalloweenLayer /> in the ERP and MES x+/_layout.tsx). useHalloween
(season.ts) is the one check they sit behind — the root loader's theme is
halloween — so nothing renders, styles or listens for anyone else, and
HalloweenLayer.tsx is all the shells import: the decorations
(Decorations.tsx) are their own chunk, loaded only while it is on. The
folder's shared maths (seeded randomness, easing, whole-number helpers built
on Math.trunc because no-raw-rounding scans packages/react/src) is
Halloween/math.ts. The
stylesheet hangs off data-user-menu (ERP avatar trigger), data-date
(calendar cells) and data-app-card (MES page card); those attributes do
nothing on their own and may stay when the folder is deleted. The removal
checklist (theme plus decorations) is the header of
packages/react/src/Halloween/HalloweenLayer.tsx: the folder and its
export, two mounts, the theme file with its two registrations, the doc
lines that name them, then lingui:extract.