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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
@carbon/checks
Conformance checking, clobber detection, invariant queries, and module structure validation for the Carbon monorepo.
Always
- Run checks against real migrations and module directories —
collectFindings(root)scans both SQL migrations and app module structure - Use
newViolations()for CI — filters findings against the baseline so only new violations fail the build - Add new conformance rules to the array that matches the rule's SOURCE —
CONFORMANCE_CHECKS(SQL migrations),SERVER_CHECKS(server-only TS),TS_CHECKS(all app + shared-package TS, client and server),EDGE_FUNCTION_CHECKS(one source per edge function, all of its.tsfiles joined —sources/edge-functions.ts), orSTRUCTURE_CHECKS(module layout). Follow theConformanceCheck/StructureCheckinterface - Write invariants as
.sqlfiles — each returns rows that VIOLATE the rule (empty = healthy); loaded from directory byloadInvariants(dir)
Ask First
- Regenerating the baseline (
pnpm --filter @carbon/checks baseline) — this grandfathers all current violations - Adding new
OBJECT_PATTERNSto clobber detection (extends what qualifies as a DB object redefinition) - Modifying existing conformance checks (may affect CI gates)
Never
- Ignore clobber warnings — they indicate a view or function is redefined on both your branch and main since the merge-base; rebase first
- Suppress violations by removing checks — add to the baseline if grandfathering is appropriate
Validation Commands
pnpm --filter @carbon/checks test # vitest — unit tests
pnpm --filter @carbon/checks clobbers # check for migration clobber risks
pnpm --filter @carbon/checks invariants # run SQL invariants against DB
pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
Key Patterns
- Conformance checks:
noNumericPrecision,noLegacyRls,noDerivedPercentColumn,noRequiredColumnWithoutDefault,noViewWithoutInvoker— scan SQL migrations for anti-patterns (noDerivedPercentColumnflags a*Percent/*RatecolumnGENERATED ALWAYS ASan expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount;noViewWithoutInvokerfails aCREATE [OR REPLACE] VIEWthat does not statesecurity_invoker—CREATE OR REPLACEreplaces a view's options, so omitting the clause turns it into an owner-rights view that bypasses RLS for every PostgREST caller, andopenJobMaterialLinesleaked every company's rows that way.security_invoker = falsepasses, so an owner-rights view is a visible decision; materialized views are not matched. It reads one file's text, so anEXECUTE format(...)view or a laterALTER VIEW … RESETescapes it — the invariant below is the backstop);noLocalTimezone(inSERVER_CHECKS) scans server TS (sources/server-files.ts) forgetLocalTimeZone(), UTC day-slicing, local date-parts of now (new Date().getDay()etc.), andsetHours(0,0,0,0)midnights. Scanned files: MES services,packages/jobs, edge functions,packages/database/src, ERP module.service.ts/.server.ts, plus both apps' route trees — route modules are server AND client in one file, somaskClientCodeblanks the browser half (default export,clientLoader/clientAction, PascalCase/use*declarations) while keeping loaders, actions, and the module-level helpers they call. A region ends only on a line of closers alone (},};,});,)): a}: {or}) {line closes a multi-line props signature, and ending there made the rest of a component read as server code - Authz ownership (
CONFORMANCE_CHECKSviacollectFindings):noAuthzDdlInMigrations(functions)fails a migration newer than20260927000000that runsCREATE/ALTER POLICYon a public table (storage bucket policies stay allowed), or defines, alters or drops a managed function — policies live inpackages/database/src/authz/manifest.ts, RLS helpers inpackages/database/src/authz/helpers/<name>.sql, event-system functions inpackages/database/src/event-system/functions/<name>.sql(util.<name>.sqloutsidepublic; checked from20261002114954, the migration that took them over), andauthz syncapplies all of them after migrations. The function list is read from those directories (loadManagedFunctions, one cutoff per directory inMANAGED_FUNCTION_SETS), so it cannot drift from the files.DROP POLICYis allowed (dropping a column a policy uses). Files starting with theauthz migrationheader are exempt;@carbon/database'smigration.test.tsverifies their contents. Older migrations are history, so there are no baseline entries - Forwarded headers (own source,
REQUEST_HANDLING_ROOTS: every app + auth, ee, jobs, lib, utils, edge functions):noRawForwardedHeadersfails a raw read ofX-Forwarded-For/-Host/-ProtoorX-Real-IPoutsidepackages/utils/src/headers.ts— usegetClientIp/getRequestProtocol/getRequestHost/getRequestOrigin. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable firstX-Forwarded-Forentry. No baseline entries - Error log messages (same source as forwarded headers,
REQUEST_HANDLING_ROOTS):noInterpolatedErrorLogfailslogger.error(…${value})/.fatal— the message is exported as a span attribute and is what errors group by, so values are named ("Failed to upload {fileName}", { fileName }). One baseline entry: thepackages/auth/src/utils/result.tspass-through, whose message is its caller's - Numeric-precision checks (in
TS_CHECKS, oversources/typescript.ts):noRawRoundingflagsMath.round/ceil/floorand.toFixedon value-bearing numbers (useround/scrapAllowance/applyRate/deriveRatefrom@carbon/utils);noInlineFractionDigitsflagsminimum/maximumFractionDigitsat a call site (pick a named kind from@carbon/utilsformat.ts, andINPUT_FORMAT.*for anything editable);noUnroundedTrackedQuantityflags inline unrounded arithmetic inside a.updateTable("trackedEntity")statement'squantity:set, and a raw===/!==/<compare against a*[Ee]ntity*.quantityread (useround/settleQuantityat the write,isFullDrawat a split gate — see.claude/rules/traceability-model.md). It is scoped to what one file can prove: aquantity:set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has no baseline entries — the whole tree was fixed in the pass that added it, so any finding is new.sources/typescript.tswalksapps/erp/app/{components,hooks,modules,routes},apps/mes/app,packages/database/supabase/functions,packages/database/src,packages/{ee,jobs}/src,packages/documents/src/{pdf,utils}and the shared packagespackages/{utils,files,form,react,printing}/src— tests (*.test.ts(x),*.spec.ts(x)) and*-test-fixture.tslive-database fixtures excluded; a fixture is test support code, so it is held to the tests' rules, not shipped code's. The shared packages matter:@carbon/utilsis where the standard's own helpers live, andform/reactown the number inputs whoseformatOptionsare part of the storage round-trip. See.claude/rules/numeric-precision.md - Realtime (in
TS_CHECKS):noPostgresChangesfails apostgres_changessubscription — thesupabase_realtimepublication is empty, so it would never fire. Use a broadcast topic through@carbon/query(.claude/rules/realtime-system.md). - Missing audit columns (built in
collectFindings, notTS_CHECKS):noMissingAuditColumn(columns)fails a write that namescreatedBy/updatedByon a relation that has no such column — PostgREST rejects the whole statement (PGRST204 Could not find the 'createdBy' column of '<table>') and TypeScript does not flag it, because supabase-js widens the insert/upsert argument enough for the excess property to survive. That is how thecustomerPartToItemupsert insales-rfq.$rfqId.map-lines.tsshipped with an unchecked result, so every RFQ-line → customer-part mapping silently failed. Roughly a third of Carbon's tables have no audit columns (favourites, link tables, the lean material lookups,companySettings) while golden rule 3 says to include them, so it is an easy assumption to carry into the wrong table. It takes the column map as an ARGUMENT —loadDbTableColumns(root)(sources/db-columns.ts) reads the generatedpackages/database/src/types.tsRow:blocks, so the I/O stays insources/andscanstays pure, the same shape asnoAuthzDdlInMigrations(loadManagedFunctions(root)). Scope is the LITERAL argument of the write (.from/insertInto/updateTable+.insert/.upsert/.update/.values/.set); a payload object spread into the row is invisible here. No baseline entries — the one hit was fixed when it was added - Function redefinitions (built in
collectFindings, cross-file over the migrations):findDroppedFunctionChanges(function-redefinition-keeps-changes) fails a migration from20261016000000on whoseCREATE OR REPLACE FUNCTIONleaves out two or more lines the previous definition added over its own predecessor. A function is its schema, name and input argument types (OUT arguments, argument names, defaults and type modifiers left out;int/int4/integerand the other aliases read as one), so an overload and autil.*function each have their own history. A redefinition must start from the newest definition:20261014171619_receive-consumed-serial-unitsforkedcomplete_job_to_inventoryfrom an older migration and silently undid always-post job costing and the production-event lock (restored in20261015161847_job-receipt-takes-issued-serial-units). A deliberate removal is explained in the migration header and baselined. No baseline entries - Stamped identity fields (built in
collectFindings, cross-file):findStampColumnMismatches(stamp-matches-columns, sources fromloadModuleServerFiles) follows eachpayload(ctx, value)…for*()chain in a module's<m>.server.tsinto theservice.<fn>(…)it is passed to, and reads that function's writes in<m>.service.tswhose row is the parameter itself (insert([p]),...p,sanitize(p), or one local initialized from it). It fails a fieldpayloadadds that the table has no column for (PGRST204:createAccountstampedcompanyIdonto the group-scopedaccount), andcreatedByadded to a payload that only reaches.update((it rewrites the row's author:upsertItemCost). It followspayload's own rules: a list gets onlycreatedBy,forUpdatedropscreatedBy, a nested object is never added to. No baseline entries - Tenant-scoped Kysely writes (in
TS_CHECKS):noUnscopedKyselyWritefails any.updateTable(/.deleteFrom(underapps/erp/app/{modules,routes},apps/mes/apporpackages/jobs/srcwhose statement (up to.execute…(/.compile(/;/,at depth 0, comments blanked) has no.where("companyId", …)/.where("alias.companyId", …). Kysely is the superuser connection, and the public API hands a service'sdbparam that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (updateQuoteLineOrderand friends) were a reported cross-tenant write because they keyed onidalone.companyis exempt (itsidis the tenant); acompanyIdin.set()does not count; a link table with nocompanyIdcolumn passes by scoping through its parent in a subquery.packages/eeis out of scope (see the file header), and so are writes made through the@carbon/database/rowshelpers (updateRows/deleteRows): the check only reads Kysely's own builders. One baseline entry: thecompanyGroupdelete inpackages/jobs/.../scheduled/purge-company.ts(a group has nocompanyIdcolumn; itsidis the tenant-group key). Every other hit was fixed when it was added - Unguarded submit buttons (in
TS_CHECKS,.tsxonly):noUnguardedSubmitfails a<Button>/<button>/<IconButton>carryingtype="submit"whose own opening tag names no in-flight signal (isLoading,isSubmitting,isPending,isSaving,useIsSubmitting, or a*fetcher|navigation|transition*.stateread). A live submit button posts again on every click and each POST runs to completion server-side —fetcher.submitaborts the previous BROWSER request, but no route action readsrequest.signal— which is how one quote finalize emailed the customer the same PDF three times. It parses the real opening tag (brace- and quote-aware), so a guard written aftertype="submit"still counts and a>inside{a > b}does not end the tag early. The presence ofisDisabledis deliberately not enough: the incident's button wasisDisabled={loading}whereloadingwas the modal's data-fetch flag, so a check that accepted anyisDisabledwould have passed the exact line it exists to catch; word boundaries matter too (loadingmust not satisfyisLoading). Buttons inside a<ValidatedForm>are skipped —ValidatedForm.handleSubmitdrops a re-entrant submit, so a second click cannot produce a second POST however the button is written.packages/form/src/components/Submit.tsxis excluded; it IS the guard. The check cannot do dataflow, so a guard held in a differently-named local (disabled={busy}) is baselined rather than rewritten. 32 baseline entries, all reviewed: logout/company-switch/theme/console-toggle (idempotent), delete and rule-unassign (a second delete is a no-op), the two chat composers (guarded by aflushSyncclear plus an empty-message return), andConfiguratorForm(its submit is anonSubmitcallback — the in-flight state lives at the caller) - Module files (in
TS_CHECKS):serviceFnFile(service-fn-file) fails anything in an ERP<module>.server.ts(or.ee.server.ts) other than imports, types, plain constants and exporteddefineServiceFnconsts — a helper function, a class or an exported value is a building block and goes in<module>.service.ts.noServerCodeInClient(no-server-code-in-client) fails a value import of a.service,.serveror.pdffile from browser code:components/,hooks/,stores/, a module'sui/,*.models.ts,*.utils.tsandtypes.ts. Those files are server-only; a function the UI calls lives in<module>.utils.ts. Type-only imports pass. It also scans ERP routes: a route may import a service file for its loader and action, but fails when a name it imports from one is used in its browser half (whatmaskClientCodeblanks, comments removed; a local of the same name is skipped).LOCK_PERIOD_TASK_NAMEused in a close-period component put the accounting service, and its@carbon/auth/auth.serverimport, into the client build, which then failed. No baseline entries for either. See.claude/rules/module-files.md. - Side-effect imports (built in
collectFindings, cross-file,sources/side-effect-packages.ts):findUndeclaredSideEffectImports(side-effect-import-declared) fails a bare import (import "./x",import "~/x") of a file in its own package when that package'spackage.jsonsets"sideEffects": falseor does not list the file. The production bundler drops such an import: the ERP'simport "./modules/carbon.server"was dropped, so everycarbon()call threw in production, andzod.client(z.config({ jitless: true })) never ran in any app. The dev server does not tree-shake, so nothing else shows it. A bare import of another package is left to that package's ownsideEffects;.cssis ignored. No baseline entries - Route writes (in
SERVER_CHECKS, ERP routes masked bymaskClientCode):routeActionShape(route-action-shape) fails a write made in an ERP route — a.from("…")insert/upsert/update/delete, a KyselyinsertInto/updateTable/deleteFrom, or aninvokePosting(/invokePostingOrThrow(/invokeCreate(call (a posting body run outside its service function). The write belongs in adefineServiceFnthe route calls, so the API and MCP run the same logic (.ai/plans/2026-10-15-service-function-migration.md). It matches those literal patterns only:.rpc(is not matched (it reads as often as it writes), and a route that calls a write building block from a.service.ts(or two write functions) is not detected. 11 baseline entries, all auth routes (_oauth+/authorize,register,token,_public+/unlock,api+/account.security,api+/passkey.*.verify) - Edge-function auth (
EDGE_FUNCTION_CHECKS):edgeFunctionAuthorizesCallerfails any function underpackages/database/supabase/functions/that never callsrequireCaller/requireServiceRole— the gates each self-contained function defines for itself; a declaration alone does not count — becauseverify_jwtaccepts the published anon key - License headers (own source,
sources/license-files.ts: git-tracked.ts/.tsx/.js/.jsx/.mjs/.cjs/.rsunderapps,packages,crates,docs,ci,scriptsand the repo root):spdxLicenseHeaderfails a file whose first lines are not its SPDX header —AGPL-3.0-only, orLicenseRef-Carbon-Commercialunderpackages/ee/and for any.ee.file name. The header text, the classification, the exclusions (each with its reason: generated files a generator would clobber —generate:types,generate:swagger, the workflow catalog,sst-env.d.ts, the notification preview fixtures — and third-party copies) and the insertion rules live in ONE module,src/license-headers.ts, shared with the fixerpnpm --filter @carbon/checks license-headers(--check,--dry-run,--verbose, optional paths; root aliaspnpm license:headers), so the check fails exactly the files the fixer would change. The header goes after a shebang and above everything else ("use client",// @ts-nocheck,/// <reference>,biome-ignore-all,deno-lint-ignore-file, Rust//!/#![…]all stay valid after a comment), then one blank line; the other license's header is swapped, CRLF is kept. A file with a third-party notice (foreign SPDX id,@license, copyright) is flagged and never rewritten — add it toPATH_EXCLUSIONS. When the header wording changes, move the old lines toRETIRED_HEADER_LINES. No baseline entries - Document sequences (built in
collectFindings, cross-file):findUnsyncedDocumentSequences(document-sequence-synced, sources loaded bysources/document-sequences.ts) fails a counter inpackages/database/src/seed-data.tssequenceswhose table is not both attached tosync_advance_document_sequenceinattachments.tsand named in that interceptor'sCASE, unlessEXEMPT_COUNTERSlists it with the reason no caller ever supplies its number. It also fails a table that is attached but missing from theCASE, or the reverse. Without the interceptor, a number typed by hand or sent through MCP/the API leaves the counter behind and later inserts fail on the unique constraint.COUNTER_TABLESmaps counters named differently from their table (journalEntry→journal,creditMemo/debitMemo→memo). No baseline entries - Structure checks:
moduleShape(module-shape) — each ERP module hastypes.ts,ui/, one<name>.service.tsand one<name>.models.ts(or their.ee.variants), at most one<name>.server.ts(or.ee.server.ts) and no other.serverfile, and no barrel (index.ts/index.server.ts). Three baseline entries (an extrabackups.service.tsin settings;imports.models.tsand noui/in shared) - Clobber detection:
findClobbers(branch, main)— identifies DB objects redefined on both sides - Baseline:
src/baseline.ts— grandfathered violations keyed bycheckId + file + snippet(no line number, so edits above a baselined hit don't un-baseline it) - Invariants: SQL queries loaded from directory, injected
Queryfor testability view-without-security-invoker.sql: everypublicview runs as its caller (security_invokertrue inpg_class.reloptions), whatever put it there — the live-catalog backstop fornoViewWithoutInvoker.modulesandeventSystemTriggerare excluded by name (no tenant data). Like every invariant it needs a live connection and does not run in CItracked-entity-zero-available.sql: a lot whose quantity is gone must beConsumed, never a live status.Scrapped/Rejectedare excluded — both are quality markers kept as historical record and already excluded from on-hand. Enforcement of the drain rule is per-writer, so this is the net that catches husks from ANY source: rows predating the rule, and any writer that revives a drained lot (unconsume, shipment void, disposition Use As Is / Rework). Run it before deciding whether to promote the rule to a DB CHECK- Workflows: two DB-backed drift checks, answering different questions.
src/invariants/workflow-trigger-event-drift.sql(viapnpm --filter @carbon/checks invariants) compares each active workflow'sworkflowTriggerEventrows against its active version's trigger nodes — a dispatch row that is missing, orphaned, or pinned to a superseded version.src/scripts/check-workflow-events.ts(pnpm --filter @carbon/checks workflow-events) asks whether an event id a live workflow subscribes to still exists in the generated catalog — the shape a catalog rename leaves behind. Neither replaces the other. Neither runs in CI, and neither can as CI stands: both open a live Postgres connection (DATABASE_URL/SUPABASE_DB_URL), and no job in.github/workflows/has database credentials —check.ymlruns only the staticcheck:workflow-catalog, andsupabase.ymlapplies migrations through the Supabase CLI. Run them by hand against staging or production after a catalog change, or give the deploy workflow a connection string first.
Cross-References
packages/harness/src/gates.ts—FLOOR_GATESincludes@carbon/checks testandclobbersas CI gatespackages/database/supabase/migrations/— SQL files scanned by conformance checksapps/erp/app/modules/— module directories validated bymoduleShape