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 architecture doc (#1385)
Anshul sharma5057c66eb63d
diff --git a/apps/erp/app/modules/agent/kb/docs/index.md b/apps/erp/app/modules/agent/kb/docs/index.mdindex 6b5c5e165b..4a79aadd09 100644--- a/apps/erp/app/modules/agent/kb/docs/index.md+++ b/apps/erp/app/modules/agent/kb/docs/index.md@@ -6,7 +6,7 @@ Carbon is a manufacturing system: **ERP** for the office (orders, purchasing, pl**MES** for the floor (jobs, operations, tracking). One platform over one data model.These are the **technical docs**: exact behavior, fields, and operations. If you're new, start with the-narrated `guides/order`, which walks one order from the sales desk to a shipped, traceable robot.+narrated `guides/order`, which walks one order from the sales desk to a shipped, traceable satellite.Come here when you already know the noun you need and want the precise detail behind it.## How the docs are organizeddiff --git a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md b/apps/erp/app/modules/agent/kb/docs/platform/architecture.mdindex 762d3936f5..6d98436f48 100644--- a/apps/erp/app/modules/agent/kb/docs/platform/architecture.md+++ b/apps/erp/app/modules/agent/kb/docs/platform/architecture.md@@ -1,59 +1,944 @@# Architecture-> How Carbon is built: the apps, packages, database, event system, background jobs, and auth behind a deployment.+> One journey from a button click, through the server, into Postgres, out to background jobs, and back to the screen.-Carbon is a TypeScript monorepo: a handful of apps over a shared set of packages, backed by a single-Postgres database.+Carbon is software that runs a manufacturing business: what it buys, what it holds in stock, what it+builds, what it ships, and whether the quality held up. Two separate apps do that. The **ERP** is the+office app, where people quote, purchase, plan and invoice. The **MES** is the shop floor app, used on+tablets next to the machines to run and record the actual work.-## Apps+This page follows one journey. A user clicks a button, something is saved, other things happen because+of it, and the screen updates. Everything else hangs off that spine. [Part 1](#part-1-the-map) and+[Part 2](#part-2-follow-one-click-all-the-way-down) are the ones to read in order; the rest stands on+its own, so take it in any order you like.-| App | Stack | What it is |+Any term you might not know is marked with a number the first time it appears, like this:+Postgres [[17]](#g17). The number links to a one-line definition in the [Glossary](#glossary) at the+end. Nothing is assumed.++The file paths, line numbers and counts throughout are accurate as of August 2026. They will drift as+the repository moves; the ideas they illustrate outlast them.++---++## Part 1: The map++Carbon is a monorepo [[10]](#g10): one Git repository holding several applications and+about twenty-five shared libraries, built together by pnpm workspaces and+Turborepo [[25]](#g25). Two of those applications are the products people log into, the+ERP and the MES. Everything else exists to serve them.++The centre of gravity is a single Postgres [[17]](#g17) database. Almost every arrow in+this doc eventually points at it. Unusually for a web app, a lot of logic that you might+expect to live in application code lives _inside_ the database instead: permissions,+computed totals, and the "something changed" notifications. That is the single most+important thing to understand about Carbon, and [Part 3](#part-3-layer-by-layer) explains why.++Colour is used sparingly in these diagrams, and it means the same thing in all of them:+**blue** is our own apps, **pink** is stored state, **amber** is work that happens in the+background. Everything else is left plain on purpose.++**The five things worth taking from that picture:**++1. **The ERP app is the hub.** It serves pages, and it is also where background jobs+ execute. Inngest [[5]](#g5) does not run our code on its own machines; it calls back+ into the ERP container: it is a timer and a queue that POSTs to `/api/inngest` saying+ "run this job now", and our own code does the work. See+ [Part 4](#part-4-what-happens-after-the-write).+2. **Most database access is not raw SQL.** It goes through PostgREST [[18]](#g18), a+ service that turns `client.from("purchaseOrder").select(...)` into a SQL query. We use+ the `supabase-js` library to talk to it.+3. **The database enforces permissions itself.** Even if application code forgets a+ filter, Postgres will not return another company's rows. (Except on one specific+ escape hatch: see [Part 3](#part-3-layer-by-layer).)+4. **Writes on the right tables cause events automatically.** Around ninety tables opt+ in to a database trigger, and where a company has subscribed to one, search indexing,+ webhooks, audit logs and customer automations all happen without the code that did the+ write knowing about them.+5. **The Rust service is optional.** It turns uploaded CAD files into 3D models the+ browser can show, and works out the order parts come apart in for assembly+ instructions. Carbon runs fine without it.++---++## Part 2: Follow one click all the way down++Here is the whole system in one story: **a buyer creates a Purchase Order.**++Pick this one apart and you have seen every layer: a form, validation, a permission+check, a database write, logic living in Postgres, a background side effect, and the+screen updating. Every other feature in Carbon is a variation on it.++### The short version++Notice the shape: the user's request finishes as soon as the row is written. The search+indexing happens afterwards, on its own, and nobody waited for it.++### The same story, with real files++Every path below is real. Open them in your editor as you read.++**1. The button.** It is a link, not a submit button.++`apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx:502`++```tsx+primaryAction={+ permissions.can("create", "purchasing") && (+ <New label={t`Purchase Order`} to={path.to.newPurchaseOrder} />+ )+}+```++Two conventions in three lines. `permissions.can(...)` hides UI the user is not allowed+to use; this is _cosmetic only_, the real check happens on the server. And the URL comes+from `path.to.*`, a single registry of every URL in the app+(`apps/erp/app/utils/path.ts`, ~2,200 lines). **Never hardcode a URL string.**++**2. The form.** `apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsx:116`++```tsx+<ValidatedForm+ method="post"+ validator={purchaseOrderValidator}+ defaultValues={initialValues}+>+```++`ValidatedForm` is our wrapper around a plain HTML form. You hand it a schema; it blocks+submission and shows inline field errors if the data is wrong, and it re-displays server+errors in the same place. Fields (``, ``) come+from `~/components/Form`, which re-exports generic inputs plus about ninety+Carbon-specific pickers (Customer, Supplier, Item, Location, Currency…).++**3. The schema.** `apps/erp/app/modules/purchasing/purchasing.models.ts:127`++```ts+export const purchaseOrderValidator = z.object({+ id: zfd.text(z.string().optional()),+ purchaseOrderId: zfd.text(z.string().optional()),+ purchaseOrderType: z.enum(purchaseOrderTypeType, {+ /* ... */+ }),+ supplierId: z.string().min(1, { message: "Supplier is required" }),+ locationId: zfd.text(z.string().optional()),+});+```++zod [[28]](#g28) is a schema library: you describe the shape of the data once, and get+both runtime validation and a TypeScript type from it. `zfd` (`zod-form-data`) handles the+fact that HTML forms send everything as strings: `zfd.text()` turns an empty field into+`undefined` rather than `""`.++**One schema, used in three places:** the browser validates against it, the server+re-validates against it, and the service function's argument type is derived from it. That+is why the three can never drift apart.++**4. The route.** `apps/erp/app/routes/x+/purchase-order+/new.tsx:29`++```ts+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, {+ create: "purchasing",+ bypassRls: true,+ });++ const formData = await request.formData();+ const validation = await validator(newPurchaseOrderValidator).validate(+ formData+ );+ if (validation.error) return validationError(validation.error);++ const result = await insertPurchaseOrder(client, {+ ...validation.data,+ companyId,+ companyGroupId,+ createdBy: userId,+ customFields: setCustomFields(formData),+ });++ if (result.error || !result.data) {+ throw redirect(+ path.to.purchaseOrders,+ await flash(+ request,+ error(result.error, "Failed to insert purchase order")+ )+ );+ }+ throw redirect(path.to.purchaseOrder(result.data.id));+}+```++This is the shape of _every_ write in Carbon:++> **assert the method → check permissions → validate → call a service → redirect.**++A file under `apps/erp/app/routes/` can export up to three things that matter here:++| Export | Runs where | Job |+| ------------------- | -------------------------- | --------------------------- |+| `loader` [[8]](#g8) | server only | fetch the data a page needs |+| `action` [[1]](#g1) | server only | handle a form submission |+| `export default` | server first, then browser | the React component |++`loader` and `action` are stripped out of the JavaScript sent to the browser, so it is+safe to use secrets and database clients in them. This is the same idea as Next.js+server components or a traditional controller; the file just happens to hold both+halves.++**5. The service function.** `apps/erp/app/modules/purchasing/purchasing.service.ts:1393`++Routes never talk to the database directly. They call a _service function_: a plain+function whose first argument is a database client and which returns Supabase's raw+`{ data, error }` without throwing.++```ts+const seq = await client.rpc("get_next_sequence", {+ sequence_name: "purchaseOrder",+ company_id: input.companyId,+});++const order = await client+ .from("purchaseOrder")+ .insert({+ purchaseOrderId,+ supplierId: input.supplierId,+ status: "Draft",+ companyId: input.companyId,+ createdBy: input.createdBy /* ... */,+ })+ .select("id, purchaseOrderId")+ .single();++const [delivery, payment] = await Promise.all([+ client.from("purchaseOrderDelivery").insert({+ /* ... */+ }),+ client.from("purchaseOrderPayment").insert({+ /* ... */+ }),+]);++if (delivery.error || payment.error) {+ await deletePurchaseOrder(client, orderId); // manual undo+ return { data: null, error: delivery.error ?? payment.error };+}+```++That last block is the honest, ugly truth about `supabase-js`: **three `.insert()` calls+are three separate HTTP requests, so they are not a transaction.** If the second fails,+the first is already committed, and we have to undo it by hand. When you need a real+transaction, use Kysely [[6]](#g6) instead. See+[Part 3.3](#33-the-service-layer-four-doors-to-the-database).++**6. What Postgres does by itself.** Two things happened that no TypeScript asked for.++_The order number._ `client.rpc("get_next_sequence", ...)` calls an RPC [[21]](#g21), a+function that lives _inside_ the database+(`packages/database/supabase/migrations/20241115101526_rpc-get-next-sequence.sql`). It+reads and bumps a counter and formats the result (`PO` + zero-padding + optional date+tokens) in a single atomic step. Doing this in application code would hand two+simultaneous buyers the same number.++_The event._ Every insert into `purchaseOrder` fires a Postgres **trigger**, a function+the database runs automatically on a write. It drops a small JSON message onto a queue+that lives in a database table. Nothing in the route knows this is happening. [Part 4](#part-4-what-happens-after-the-write)+follows that message to the end.++**7. The screen updates.** The action ends with `throw redirect(...)`. React Router+follows the redirect and runs the destination's `loader`, which re-reads from the+database and renders the finished page. There is no client-side cache to invalidate and+no "add the new row to the list in state" code. **After any non-GET submission, React+Router automatically re-runs the loaders for the current page.** That is the whole+refresh mechanism.++---++## Part 3: Layer by layer++### 3.1 The browser and the route file++The apps are **React Router v7** in framework mode: server-rendered React, where a+single file owns both a URL's data-loading and its UI. (It is not Remix and not Next.js,+though it is the direct descendant of Remix.) Vite [[27]](#g27) builds it; Tailwind v4+styles it.++**Routes are files on disk.** `apps/erp/app/routes/` has about 1,400 of them, and the+folder structure _is_ the URL structure, with a few conventions:++| In a filename | Means |+| --------------- | ---------------------------------------------------------------------------------- |+| `x+/` | a URL segment and a folder: `x+/purchase-order+/new.tsx` → `/x/purchase-order/new` |+| `_public+/` | a folder for grouping that adds **no** URL segment |+| `_layout.tsx` | a wrapper shared by every route in the folder |+| `$orderId` | a URL parameter: `$orderId.tsx` → `/:orderId` |+| `.` in the name | a `/` in the URL: `dimensions.new.tsx` → `dimensions/new` |+| `_index.tsx` | the page for the folder's own URL |+| `*.server.ts` | ignored by the router; a helper file that never reaches the browser |++Top-level namespaces: `x+` is the logged-in app (66 module folders), `api+` holds JSON+endpoints with no UI, `_public+` is login/logout, and `share+` is the _unauthenticated_+surface: links you email to a customer to view a quote.++**Getting data in.** A `loader` runs on the server, calls service functions, and returns+plain JSON; the component reads it with `useLoaderData<typeof loader>()`. Data shared by+the whole app (the current user, their company, their permissions, feature flags) is+loaded once in `apps/erp/app/routes/x+/_layout.tsx` (about eighteen parallel queries) and+read anywhere via hooks like `useUser()`, `usePermissions()`, `useCompanySettings()`.+Those hooks read the layout route's loader data, not a React context.++**Getting data out.** Forms post to an `action`, as in [Part 2](#part-2-follow-one-click-all-the-way-down). For writes that should+_not_ navigate (reordering rows, an inline edit, a delete button), use `useFetcher()`,+which posts in the background and still triggers the automatic revalidation.++**Shared UI.** Look in two places before writing a component:++- `packages/react/`: the design system (`@carbon/react`). Buttons, modals, comboboxes,+ menus, layout primitives. Built on Radix UI [[19]](#g19) and Tailwind.+- `apps/erp/app/components/`: app-level pieces. The big one is+ `components/Table/Table.tsx`, a single generic table (~1,500 lines, built on TanStack+ Table) that every list screen uses. It handles sorting, filtering, pagination, saved+ views, CSV import/export, column visibility and inline editing. You pass `data`,+ `columns` and `count`; the server does the paging via URL search params.++**Client state** is deliberately small. Reference lists that everything needs (items,+customers, suppliers, people) live in nanostores [[13]](#g13) and are kept fresh by+`RealtimeDataProvider`. Ephemeral UI state (is the search modal open) uses+zustand [[29]](#g29). User and permission data lives in _neither_; it comes from the+route loader.++**Translations** use Lingui [[7]](#g7): wrap a string in `` t`...` `` or ``, run+`pnpm lingui:extract`, and translators fill in thirteen locale files.++**MES is the same stack, simpler.** No `modules/` folder: services sit flat in+`apps/mes/app/services/`, all validators in one `models.ts`, routes are one flat level,+and the UI is built for gloved hands on a tablet.++### 3.2 The gate: who is allowed to do what++Every server-side entry point in Carbon starts with the same call. There are about 1,600+of them.++```ts+const { client, companyId, userId } = await requirePermissions(request, {+ create: "purchasing",+});+```++Defined at `packages/auth/src/services/auth.server.ts:195`. It does four jobs at once:++1. **Identifies the caller.** Either from the session cookie (a browser) or from a+ `carbon-key` header (our public API, which additionally gets rate-limited and scope-checked).+2. **Loads their permissions.** Permissions are stored as `<module>_<action>` keys such+ as `purchasing_create` or `sales_view`, each mapping to the list of companies where the+ user holds it. They are fetched by a Postgres function called `get_claims` and cached+ in Redis for an hour. They are _not_ in the JWT.+3. **Refuses if they lack it.** Redirect to login if not signed in at all, or an "Access+ Denied" toast otherwise.+4. **Hands back a database client already scoped to this user**, plus their `companyId`+ and `userId`.++**Multi-tenancy** [[12]](#g12) is the reason for a lot of what follows: Carbon is one+database serving many customer companies. Nearly every table has a `companyId` column and+a composite primary key `("id", "companyId")`. Which company you are acting as is read+from your session cookie, never from the URL.++**RLS (Row Level Security)** [[20]](#g20) is the part worth understanding even if you+never write SQL. It is a Postgres feature where each table carries a rule that is silently+`AND`ed onto every query the database receives. Ours look like this:++```sql+CREATE POLICY "SELECT" ON "public"."reportPin"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);+```++So if a query for another company's purchase orders reaches Postgres, it returns zero+rows. The tenant boundary is enforced by the database, not by us remembering a `.eq()`.+Service functions still filter by `companyId` anyway, as a second line of defence.++**The escape hatch.** Notice `bypassRls: true` in the Purchase Order action. RLS costs+real query time on hot paths, so for trusted employee requests we hand back a service-role+[[22]](#g22) client that skips it entirely. That is a deliberate trade, and it moves the+responsibility back to us: any loader using `bypassRls` must re-check the tenant by hand,+as the PO detail route does:++```ts+if (purchaseOrder.data?.companyId !== companyId)+ throw redirect(path.to.purchaseOrders);+```++**Three kinds of user** share one login system, distinguished by a `role` on their+company membership: `employee`, `customer`, `supplier`. Portal users get much narrower+permission sets, and routes can demand `{ role: "employee" }`. Separately, `share+/`+routes are fully unauthenticated; a long unguessable token in the URL is the credential.++### 3.3 The service layer: four doors to the database++A service function's first argument is always a client, and there is more than one kind.+Picking the wrong one is the most common mistake made here.++**1. The user-scoped client.** What `requirePermissions` normally returns. Every query+runs as that user with RLS applied. Use it unless you have a reason not to.++**2. The service-role client** (`getCarbonServiceRole()`) ignores RLS entirely. Needed+by background jobs (which have no logged-in user), by `share+/` routes, and by+`bypassRls: true` requests. **You are now the only thing standing between a bug and a+cross-tenant data leak.**++**3. Kysely** is a TypeScript SQL query builder that holds a real connection to Postgres,+so it can open a real transaction. This is the answer to the "three inserts aren't+atomic" problem from [Part 2](#part-2-follow-one-click-all-the-way-down):++```ts+return db.transaction().execute(async (trx) => {+ for (const { id, sortOrder, updatedBy } of updates) {+ await trx+ .updateTable("quoteLine")+ .set({ sortOrder, updatedBy })+ .where("id", "=", id)+ .execute();+ }+});+```++Three warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it+in `try/catch`. It applies **no** RLS, so authorise before you call it. And the pool it+draws from is small (edge functions ask for exactly one connection,+`getConnectionPool(1)`): if code inside a transaction reaches for a second connection from+the same pool, that second request queues behind a transaction that cannot finish until it+is served, and the whole thing hangs until the timeout. Do all the work of a transaction+on the `trx` handle you were given, never on `db`.++**4. Edge functions** are small programs written for Deno [[2]](#g2), deployed next to the+database and called over HTTP [[4]](#g4). There are about forty in+`packages/database/supabase/functions/`, and they own the genuinely heavy work:+MRP [[11]](#g11), production scheduling, posting a shipment or an invoice to the general+ledger, CSV import, exporting a whole company. Call one and wait for its answer:++```ts+const { data, error } = await client.functions.invoke("post-shipment", {+ body: { type: "post", shipmentId, userId, companyId },+});+```++They exist for two reasons: they can hold a database connection and run a big+multi-thousand-row transaction properly, and they are callable from anywhere (the ERP,+the MES, a background job, the public API), not just from a route handler.++"Heavy" here means heavy in SQL, not heavy in the function. Supabase caps an edge function+tightly, a couple of hundred megabytes of memory and a short processor-time budget, far+below a normal server or an ordinary Lambda, so the useful pattern is to let Postgres do+the lifting and keep the function itself thin. Work that is heavy in JavaScript, or that+runs for minutes, belongs in an Inngest job instead; work that needs real computing power,+like CAD geometry, belongs in the Rust service.++There is also a fifth, narrower door: **RPCs**, plain Postgres functions called with+`client.rpc("name", args)`. About 85 call sites. `get_next_sequence` from [Part 2](#part-2-follow-one-click-all-the-way-down) is one.++### 3.4 The database++Postgres 15, wrapped by Supabase [[24]](#g24), an open-source bundle that adds an+auto-generated REST API (PostgREST), user authentication, file storage, a realtime change+feed, and the edge function runtime, all on top of one ordinary Postgres database.++Rough size, for a sense of scale: **923 migration files**, 362 tables,+101 views, 238 database functions, 154 enum types.++**Migrations** [[9]](#g9). Every schema change is a timestamped SQL file in+`packages/database/supabase/migrations/`, named `YYYYMMDDHHMMSS_kebab-name.sql`. Create+one with `pnpm db:migrate:new <name>`, apply with `pnpm db:migrate`. They are applied in+filename order and never edited after merge.++A typical table shows every convention at once:++```sql+CREATE TABLE "itarCertification" (+ "id" TEXT NOT NULL DEFAULT id('itc'),+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);+ALTER TABLE "public"."itarCertification" ENABLE ROW LEVEL SECURITY;+```++`id('itc')` generates a prefixed, sortable, URL-safe id such as `itc_3xK9...`. The prefix tells+you what an id refers to at a glance.++**Views** [[26]](#g26) **are the read path.** This is the second-most-important idea in+Carbon after RLS.++We **write to tables** but **read from views**. A view is a saved query that behaves like+a table. `purchaseOrders` (plural, that is the naming convention) joins in the supplier+name, sums the line amounts into `orderTotal`, converts currency, counts received+quantities, and fetches a thumbnail. So the create path never calculates a total: it+inserts a header, and the view derives everything else on read.++When a list screen shows a number you cannot find in any table, look for the view. They+are defined in migrations, always with `WITH (security_invoker = true)` so the caller's+RLS still applies.++**Types are generated, never written.** `pnpm run generate:types` points the Supabase CLI+at your local database and writes `packages/database/src/types.ts`, about 80,000 lines+describing every table, view, function and enum. App code imports from it:++```ts+import type { Database } from "@carbon/database";+type PurchaseOrderRow =+ Database["public"]["Tables"]["purchaseOrder"]["Row"];+```++**Run `pnpm run generate:types` after pulling migrations or writing one, before you+typecheck.** Half of all "this property doesn't exist" errors are a stale types file.++**Logic that lives in Postgres.** We push logic into the database when it must hold true+for _every_ writer: the ERP, the MES, an edge function, a background job, the public+API, or someone running SQL by hand. Two examples:++- `update_picking_list_status()` is a trigger that recomputes a picking list's header+ status whenever one of its lines changes. Written from four different places;+ recomputing it in each caller would drift.+- `dispatch_event_batch()` is the event trigger from [Part 4](#part-4-what-happens-after-the-write). It must enqueue in the _same+ transaction_ as the write that caused it, so a rolled-back write never emits a+ phantom event.++**Files** live in Supabase Storage buckets: `private` is the workhorse (attachments,+drawings, quality records), `public` and `avatars` are self-explanatory, plus one bucket+per company and `temp-staging` for large CAD uploads.++---++## Part 4: What happens after the write++Back to that queued event. This chain is the piece most likely to surprise you, because+none of it is visible from the code that did the write.++It is not every write, though. A table only emits events once a migration has opted it in+with `attach_event_trigger('tableName')` — about ninety have — and even then the trigger+enqueues nothing unless that company has an **active subscription** matching the table and+the operation. So the same `UPDATE` can fan out to six handlers for one company and do+absolutely nothing for another.++Three unfamiliar pieces in that chain: PGMQ [[16]](#g16) is the queue, which lives in+ordinary Postgres tables so a trigger can write to it inside the same transaction;+pg_net [[15]](#g15) is what lets the database make the outbound HTTP ping after that+transaction commits; and Inngest [[5]](#g5) is the background job runner.++In plain terms, Inngest works like this: you send it a named event, it calls one of your+registered functions over HTTP, and it remembers how far that function got. Each+`step.run("id", fn)` inside a function is a checkpoint: if step four fails and retries,+steps one to three are not re-executed; their saved results are handed back. That is why+it is used for anything that must survive a crash.++The wiring is three files:++| What | Where |+| -------------------------------- | ------------------------------------- |+| The client | `packages/lib/src/inngest/client.ts` |+| The list of all 55 job functions | `packages/jobs/src/inngest/index.ts` |+| The HTTP endpoint Inngest calls | `apps/erp/app/routes/api+/inngest.ts` |++That last row is the surprising one: **background jobs run inside the ERP container.**+Inngest is a scheduler and a memory, not a compute host.++**Firing a job on purpose.** The automatic trigger path above is for row changes. When+code wants to _deliberately_ kick something off, it calls the typed helper `trigger()`+(about 108 call sites):++```ts+await trigger("notify", {+ event: NotificationEvent.JobAssignment /* ... */,+});+```++Event names are always `carbon/<something>`.++**Scheduled work** comes from two places. Inngest crons handle app-level jobs: MRP every+three hours, notification digests every fifteen minutes, exchange rates and audit+archiving nightly, workflow-run cleanup at 04:00. All of them are UTC, and any job that+needs a company's local day computes it inside the run. Database-level maintenance uses+pg_cron [[14]](#g14) instead, for refreshing cached aggregate tables and sweeping the event+queue.++**Notifications** fan out from one job (`packages/jobs/.../notifications/notify.ts`) to+three destinations: in-app rows (which the topbar picks up live over Realtime), email via+Resend, and Slack. `packages/notifications` itself is only the list of event types; it+sends nothing.++---++## Part 5: The other engines++### Workflows: the customer's own automations++Carbon ships a drag-and-drop canvas where a _customer_ builds "when a quote is accepted,+notify the account manager and create a job". Confusingly these are also called+workflows, and they are a completely different thing from Inngest jobs:++| | Inngest jobs | Workflows |+| ---------- | ----------------------------- | ---------------------------------------- |+| Written by | us, in TypeScript | customers, on a canvas |+| Stored as | code | JSON rows in `workflowVersion` |+| Runs as | service role, sees everything | **the workflow's owner**, with their RLS |+| Changed by | a deploy | the customer, at any moment |++They reuse the event pipeline from [Part 4](#part-4-what-happens-after-the-write), the `WORKFLOW` branch. A matcher takes the+row change, works out which catalog events it corresponds to, finds subscribed workflows,+and queues one run each. `packages/workflows` holds the pure definition/validation logic+and touches nothing; `packages/jobs/src/workflows/` holds the runtime that actually does+things. Every run and every step is recorded, so a customer can open a run and see what+happened.++### The Assembler: the Rust service++`apps/assembler` plus `crates/` is a Rust HTTP service that converts CAD files (STEP) into+web-renderable 3D (GLB) and plans a collision-free disassembly sequence for assembly+instructions. It wraps two C++ libraries (OpenCASCADE for geometry, FCL for collision).+`packages/viewer` renders its output in the browser.+It is entirely optional; everything else boots without it.++It is not a call-and-wait service. A job is submitted and answered later: the caller posts+the work and gets a job id back, then waits for a callback, with polling as a fallback.+Files never travel through the ERP. The caller hands over signed URLs, one to read the CAD+file from and one to write the result to, and the Rust service streams straight to and+from the storage bucket itself; it holds no database credentials and can see nothing else.+Redis is where job state and finished-result pointers live, which is why the service+refuses to start without it.++---++## Part 6: The repo map++**Applications** (`apps/`, plus `docs/` at the root):++| App | What it is | Dev port |+| ----------- | --------------------------------------------------------------------------- | -------- |+| `erp` | The main product, and the host for all background jobs. By far the largest. | 3000 |+| `mes` | Shop floor: job operations, work centres, scheduling. Touch-first. | 3001 |+| `academy` | Training app for new Carbon users. | 4111 |+| `starter` | A minimal example app showing auth + database + forms. | 4000 |+| `assembler` | The Rust CAD/3D service. | varies |+| `docs` | Public documentation site. The only Next.js app here. | 3002 |++**Libraries** (`packages/`). The ones you will actually touch are near the top:++| Package | What it does |+| --------------- | ----------------------------------------------------------------------- |+| `react` | The design system. **Check here before writing any UI.** |+| `database` | Generated types, migrations, edge functions, database clients. |+| `auth` | Login, sessions, `requirePermissions`, API keys, permission caching. |+| `form` | `ValidatedForm`, field components, zod helpers. |+| `jobs` | Every Inngest background function, plus the workflow runtime. |+| `lib` | Shared server utilities: the Inngest client, `trigger()`, email, Slack. |+| `utils` | Pure helpers: dates, money, arrays, strings, BOM maths. |+| `workflows` | Customer workflow schema, validation and pure runtime. No I/O. |+| `documents` | PDF generation, email templates, barcode and label rendering. |+| `locale` | Lingui setup and language switching. |+| `env` | The one place `docs/platform/self-hosting/environment-variables` are read and validated. |+| `logger` | Structured logging, with request-id correlation. |+| `notifications` | The notification event taxonomy (enums only). |+| `printing` | Printer registry, label queue, physical print delivery. |+| `onboarding` | New-company setup, the "Implementation Hub". |+| `kv` | Redis client plus rate limiting. |+| `stripe` | Billing. Cloud edition only. |+| `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |+| `viewer` | 3D model and assembly-instruction rendering. |+| `tiptap` | Rich text editor. |+| `dev` | The `crbn` CLI that runs your local stack. |+| `checks` | Repo conformance rules enforced in CI. |+| `config` | Shared tsconfig, Tailwind theme, vitest preset. No runtime code. |+| `glossary` | Canonical manufacturing term definitions used in field help. |+| `harness` | Internal AI-agent tooling. Not shipped. |++**Inside an ERP module** (there are eighteen, under `apps/erp/app/modules/{module}/`):++```+purchasing/+├── purchasing.models.ts zod schemas and the types derived from them+├── purchasing.service.ts every database operation for this module+├── purchasing.server.ts server-only helpers (optional)+├── types.ts shared types+├── index.ts barrel, import from "~/modules/purchasing"+└── ui/ React components, grouped by feature+```++---++## Part 7: Where it all runs++The same code base runs in three shapes: on a laptop, on the cloud Carbon operates for+customers, and on a server a customer owns. Nothing in the application knows which one it+is in; the difference is entirely in configuration.++### 7.1 On a laptop++`pnpm dev` runs `crbn up`, a custom CLI that boots an eleven-container Docker stack, waits+for Postgres, applies migrations, regenerates the database types, seeds a test user, and+starts the apps. The apps themselves run as ordinary Node processes on the host, not in+containers, which is what makes hot reload fast.++Each Git worktree (a second checkout of the same repository) gets its own ports, its own+database and its own freshly minted keys, so several branches can run at once. Redis is+the one exception: a single shared container, with each worktree given its own numbered+slot inside it.++### 7.2 The cloud Carbon runs++The ERP and MES are packaged as Docker images and run on ECS Fargate [[3]](#g3), which is+Amazon running your container for you without any server to look after. Each service sits+behind its own load balancer on port 3000, is checked for life at `/health`, and scales+between one and ten copies on processor and memory pressure. All of that is described in+`sst.config.ts` (SST [[23]](#g23) is infrastructure-as-code, where you write cloud+resources in TypeScript instead of clicking in a console). The+`docs/platform/self-hosting/aws-sst` recipe is the same stack, run by you.++The part that surprises people: **this is not one big shared installation.** There is a+`workspaces` table, and on every deploy `ci/src/deploy.ts` walks it and runs+`sst deploy --stage prod` once per row, each with that customer's own AWS account, region,+domain, certificates, Supabase project and Redis. So Carbon separates customers twice+over: by `companyId` on every row inside one installation ([Part 3](#part-3-layer-by-layer)), and by giving a+customer their own installation entirely. Adding a customer means adding a workspace row.+A row missing a required field is skipped with a log line rather than failing the deploy,+so a tenant can silently not deploy.++Postgres is managed Supabase. There is nothing on Vercel despite some leftover Vercel+packages. There is one Lambda: the Assembler ships as a single image that runs either as a+Lambda function behind an API gateway (the default) or as a container, which is why 3D+conversion can be turned on per customer without changing the main stack.++### 7.3 On a customer's own server++`contrib/deploying/simple-docker-caddy/` holds a complete `docs/platform/self-hosting/docker-caddy`: a Docker+Swarm file that brings up Postgres, the Supabase services, Redis, Inngest and both apps on+one machine, with Caddy in front as the only thing exposed to the internet. Secrets are+Swarm secrets rather than environment variables in a file. Migrations run as a throwaway+one-shot container before the apps roll. `scripts/backup.sh` takes a database dump plus+the uploaded files (see `docs/platform/backups`), and `scripts/harden.sh` does the+basic firewall setup.++Which features exist is decided by one variable, `CARBON_EDITION`: `community`,+`cloud`, `enterprise` or `test`. What each of those buys you is the+`docs/platform/licensing`. Self-hosting defaults to `community`; the cloud fan-out+sets `enterprise`.++### 7.4 How a merge becomes production++Four GitHub Actions workflows, and they are deliberately independent of each other rather+than one pipeline:++| Workflow | Fires when | What it does || --- | --- | --- |-| `erp` | React Router 7 + Vite | The ERP: orders, purchasing, planning, accounting. Also hosts the API, the MCP server, and the OAuth endpoints. |-| `mes` | React Router 7 + Vite | The Manufacturing Execution System: shop-floor job execution. |-| `academy` | React Router 7 + Vite | Hosts training video lessons. |-| `docs` | Next.js (Fumadocs) | This documentation site. |+| `check.yml` | every pull request | Biome, typecheck, tests, translation and workflow-catalog checks |+| `deploy.yml` | merge to `main` touching `apps/erp`, `apps/mes` or `packages` | builds both images from the one root `Dockerfile`, pushes them to Amazon's image registry tagged with the commit, then fans out `sst deploy` per workspace |+| `supabase.yml` | merge touching `packages/database/supabase` | applies migrations and deploys edge functions, per workspace |+| `inngest.yml` | after `deploy.yml` succeeds | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs |++Two consequences worth knowing. First, `check.yml` never builds the apps, so a pull+request can go green and still break the image build on merge. Second, migrations and app+code deploy in parallel with no ordering between them, so a migration and the code that+depends on it can land seconds apart in either order; write migrations that are safe+against the previous version of the code.++There is no version tagging and no rollback button. An image is identified by its commit,+so rolling back means redeploying an older commit. Configuration is not held in a secrets+manager: values are read from the `workspaces` table at deploy time and set as plain+environment variables on the container.++### 7.5 Knowing what is happening++Observability is deliberately thin. Logs go through LogTape: colour on a laptop, one JSON+line per entry in production, with sensitive field names blanked out and a request id+threaded through everything so one page load can be followed end to end. There is no log+shipping of its own, so logs are whatever the platform collects: CloudWatch on AWS,+`docker service logs` when self-hosted. PostHog covers product analytics and is switched+off entirely in controlled (ITAR) environments. There is no Sentry and no distributed+tracing.++---++## Part 8: There's a bug, where do I look?++Start from what the user saw and walk inwards. This mirrors the order things happen.++**A few specific traps, each of which has caught someone out:**++- _TypeScript says a column doesn't exist._ Run `pnpm run generate:types`. Your generated+ types are behind your migrations.+- _A query returns nothing but the row is definitely there._ RLS. Either the `companyId`+ is wrong or you are using a user-scoped client where you needed service role.+- _A write half-succeeded._ Chained `supabase-js` calls are not a transaction. Look for a+ manual rollback that didn't cover the failure.+- _You see another company's data._ Something is using `bypassRls: true` or the+ service-role client without re-checking the tenant. **Treat this as urgent.**+- _A number on a list screen is wrong._ It is almost certainly computed in a view.++---++## Part 9: House rules++The full list is in `AGENTS.md` at the repo root. The ones that cause+the most damage when broken:++- **`pnpm`, never `npm`.**+- **Never use JavaScript `Date`** for parsing, formatting or arithmetic. Use+ `@internationalized/date` and `@carbon/utils`. A build check enforces this. Timezones in+ a manufacturing schedule are not cosmetic.+- **Never hand-edit the generated database types.** Regenerate them.+- **Never skip `companyId` scoping**, even though RLS would probably catch it.+- **Never chain `supabase-js` writes and call it a transaction.** Use Kysely, or an RPC.+- **Never query inside a loop.** Collect the ids and make one `.in()` call.+- **One `{module}.service.ts` and one `{module}.models.ts` per module.** Don't scatter them.+- **Run `pnpm run generate:types` after any migration, before typechecking.**++Useful commands:++```bash+pnpm dev # boot everything+pnpm db:migrate:new <name> # create a migration+pnpm db:migrate # apply migrations+pnpm run generate:types # regenerate database types+pnpm exec turbo run typecheck --filter=erp # typecheck one package+pnpm run lint # Biome+pnpm run test # unit tests+```++Typechecking the whole repo at once runs out of memory, so always use `--filter`.++---++## Glossary++Numbered so the body can point at them. Alphabetical.++<a id="g1"></a>+**1. Action:** the function a route file exports to handle a form submission. Runs on the+server only, never shipped to the browser.++<a id="g2"></a>+**2. Deno:** an alternative JavaScript runtime to Node.js. Our edge functions are written+for it, which is why they use `https://` imports instead of `node_modules`.++<a id="g3"></a>+**3. ECS Fargate:** Amazon's service for running Docker containers without managing the+servers underneath. The ERP and MES run here in production.++<a id="g4"></a>+**4. Edge function:** a small server-side program deployed next to the database, called+over HTTP and awaited like a normal function. Ours are written for Deno.++<a id="g5"></a>+**5. Inngest:** the background job runner. Send it an event; it calls your function over+HTTP and remembers each completed step, so a retry resumes rather than restarts.++<a id="g6"></a>+**6. Kysely:** a TypeScript SQL query builder. Unlike `supabase-js` it holds a real+database connection, so it can run real transactions. It also bypasses RLS.++<a id="g7"></a>+**7. Lingui:** the translation library. You mark strings in code; it extracts them into+per-language files for translators.++<a id="g8"></a>+**8. Loader:** the function a route file exports to fetch the data its page needs. Runs+on the server only.++<a id="g9"></a>+**9. Migration:** one timestamped SQL file describing a schema change. The full ordered+set of them _is_ the schema; there is no separate schema file.++<a id="g10"></a>+**10. Monorepo:** one Git repository holding several applications and shared libraries+that are versioned and released together.++<a id="g11"></a>+**11. MRP:** Material Requirements Planning. Works out what to buy and make, and when,+given demand and current stock. Runs as an edge function.++<a id="g12"></a>+**12. Multi-tenancy:** one database and one running application serving many separate+customer companies, with each company's data invisible to the others.++<a id="g13"></a>+**13. nanostores:** a very small state library. We use it for reference lists (items,+customers, suppliers) that many screens read and Realtime keeps fresh.++<a id="g14"></a>+**14. pg_cron:** a Postgres extension that runs SQL on a schedule, inside the database.+Used for cache refreshes and queue sweeping.++<a id="g15"></a>+**15. pg_net:** a Postgres extension that lets the database make outbound HTTP calls. We+use it for exactly one thing: pinging the event queue awake after a commit.++<a id="g16"></a>+**16. PGMQ:** a message queue implemented in ordinary Postgres tables. Lets a database+trigger enqueue work inside the same transaction as the write that caused it.++<a id="g17"></a>+**17. Postgres:** the relational database everything in Carbon is built on. Version 15.++<a id="g18"></a>+**18. PostgREST:** a service that exposes Postgres tables and views as a REST API. Every+`client.from(...).select(...)` is a PostgREST call, not raw SQL.-## Packages+<a id="g19"></a>+**19. Radix UI:** an unstyled, accessible React component library. Our design system adds+Tailwind styling on top of it.-Shared libraries live in `packages/`, including `database` (Supabase schema + generated types), `react`-(the UI component library), `jobs` (background jobs), `auth`, `ee` (enterprise edition + integrations),-`stripe`, `kv` (Redis), `documents`, `printing`, `locale`, and `dev` (the `crbn` CLI).+<a id="g20"></a>+**20. RLS (Row Level Security):** a Postgres feature where a per-table rule is+automatically added to every query. It is what keeps one company's data invisible to+another.-## The stack+<a id="g21"></a>+**21. RPC:** here, calling a function defined inside Postgres from application code, via+`client.rpc("name", args)`.-- **Framework:** React Router 7 for the apps; Next.js for these docs.-- **Monorepo:** pnpm workspaces + Turborepo.-- **Tooling:** Vite, Biome (lint + format), tsup, strict TypeScript.+<a id="g22"></a>+**22. Service role:** a database credential that bypasses all RLS. Powerful; use+carefully.-## Database+<a id="g23"></a>+**23. SST:** infrastructure-as-code for AWS, written in TypeScript. `sst.config.ts`+defines our production cluster.-Carbon runs on **Supabase / PostgreSQL**. Multi-tenancy is enforced in the database: every row is scoped-to a company, and **Row Level Security** policies gate access. Types are generated from the schema. Local-development runs Supabase in Docker.+<a id="g24"></a>+**24. Supabase:** an open-source bundle around Postgres: REST API, auth, storage,+realtime and edge functions. We run its containers locally and use the managed version in+production.-Carbon is multi-company. One deployment can host many companies; isolation is enforced by RLS, not by-application code.+<a id="g25"></a>+**25. Turborepo:** the build orchestrator that knows which packages depend on which, so+`pnpm build` only rebuilds what changed.-## Events & background jobs+<a id="g26"></a>+**26. View:** a saved query that behaves like a read-only table. Carbon writes to tables+and reads from views; computed values like order totals live in the view.-- **Event system:** Postgres triggers enqueue change events into a PGMQ queue; an **Inngest** cron drains- the queue and routes each event to its handlers (webhook, workflow, sync, search).-- **Background jobs:** run on **Inngest** (`packages/jobs`): MRP, scheduling, exchange-rate updates,- integration syncs, and notifications. App code fires jobs with `trigger()` / `batchTrigger()`.-- **Edge functions:** transactional work runs as **Supabase edge functions** (Deno): posting receipts,- shipments, and invoices; running MRP; importing CSV; issuing and picking material.+<a id="g27"></a>+**27. Vite:** the build tool and dev server behind all our React apps.-Older notes attribute jobs and events to Trigger.dev. That migration is done. Jobs and the event queue-run on **Inngest**; edge functions run on **Supabase / Deno**.+<a id="g28"></a>+**28. zod:** a schema library. Describe data once, get validation and a TypeScript type+from the same definition.-## Authentication+<a id="g29"></a>+**29. zustand:** a small React state library. We use it only for throwaway UI state, like+whether a modal is open.-Carbon uses **Supabase Auth** with HTTP-only cookie sessions and Redis-cached permissions (role- and-attribute-based). Sign-in is by magic link, Google, or Outlook. Programmatic access uses **API keys** (a `carbon-key`-header), and a full **OAuth 2.0 server** backs the Claude remote connector.+---## Related- Self-hosting Run the apps on your own infrastructure: Docker on a VPS, or AWS with SST.- Environment variables The full configuration surface.+ - Licensing What Community, Enterprise and Cloud each include.+ - Backups Dumping the database and the uploaded files.diff --git a/apps/erp/app/modules/agent/kb/docs/reference/import-export.md b/apps/erp/app/modules/agent/kb/docs/reference/import-export.mdindex a3a21bb2a4..5ec504c41b 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/import-export.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/import-export.md@@ -6,7 +6,7 @@ Carbon moves data both ways through CSV. Every data table can **export** its cur## Exporting a table to CSV-Open any data table (a parts list, a sales order dashboard, an inventory grid) and look for the dashed **Download CSV** button in the header. There is no setting to turn it on: every table built on Carbon's shared data grid gets the button automatically.+Open any data table (a parts list, a sales order dashboard, an inventory grid) and look for the small download icon in the table header — hover it and its **Download CSV** tooltip appears. There is no setting to turn it on: every table built on Carbon's shared data grid gets the button automatically.The download reflects **what you are currently looking at**, not a full server dump:diff --git a/apps/erp/app/modules/agent/kb/docs/reference/methods.md b/apps/erp/app/modules/agent/kb/docs/reference/methods.mdindex 90c63338c4..fdeb087156 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/methods.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/methods.md@@ -52,7 +52,7 @@ is frozen so jobs already running against it don't shift mid-build.## Related- - Inside the build See method types, kits, and Get Method in the story of a robot build.+ - Inside the build See method types, kits, and Get Method in the story of a satellite build.- Reordering policy How the replenishment system pairs with a part's reordering policy.## Troubleshootingdiff --git a/apps/erp/app/modules/agent/kb/docs/reference/planning.md b/apps/erp/app/modules/agent/kb/docs/reference/planning.mdindex 94afaf6bb7..3f23597940 100644--- a/apps/erp/app/modules/agent/kb/docs/reference/planning.md+++ b/apps/erp/app/modules/agent/kb/docs/reference/planning.md@@ -4,7 +4,7 @@Planning answers one question: *what should we make or buy, and how much?* Carbon's MRP looks at everything you owe and everything you have coming, and turns the gap into suggested orders that you choose to act on.-Without planning you'd reorder by hand. MRP nets demand against supply across the whole bill of materials, so a shortfall on a top-level robot surfaces as the right quantity of every component, offset for its lead time — before you're caught short.+Without planning you'd reorder by hand. MRP nets demand against supply across the whole bill of materials, so a shortfall on a top-level satellite surfaces as the right quantity of every component, offset for its lead time — before you're caught short.## Two stagesdiff --git a/apps/erp/app/modules/agent/kb/guides/build.md b/apps/erp/app/modules/agent/kb/guides/build.mdindex c872383597..cbc1f0d663 100644--- a/apps/erp/app/modules/agent/kb/guides/build.md+++ b/apps/erp/app/modules/agent/kb/guides/build.md@@ -1,21 +1,21 @@# Inside the build-> How each robot part is made or bought.+> How each satellite part is made or bought.-Open the job you just released and look at what it actually takes to build a robot. This is where the product structure you set up in PLM meets the reality of the floor.+Open the job you just released and look at what it actually takes to build a satellite bus. This is where the product structure you set up in PLM meets the reality of the floor.> PLM specifies the parts. The method adds the clarity: how each part is obtained, and whether it's built, bought, or pulled from the shelf.## The bill of materials-A robot's bill of materials (BoM) is a tree. The robot is built from an arm and a leg; each of those is built from a machined part and a motor. Carbon shows the whole structure at a glance, with every node carrying an icon for how it's obtained.+A satellite bus's bill of materials (BoM) is a tree. SAT-1000 is built from subassemblies — the BUS-STR-001 structural frame, the EPS-001 electrical power subsystem, ADCS-001, COMMS-001 and the rest — and each of those is built from parts of its own: the power subsystem from solar array wings and a battery pack, the frame from aluminium plate and fasteners. Carbon shows the whole structure at a glance, with every node carrying an icon for how it's obtained.## Method typesEvery item in that tree carries a method type, and it's the single most load-bearing field in your whole catalog. There are three values, and each one routes the item down a completely different path:-- Make to Order: you manufacture it. The arm part and leg part are machined in-house, so each becomes its own job with its own operations.-- Purchase to Order: you purchase it. The motors come from a supplier, so they flow through `guides/rfq-to-po` as a purchase order, never touching the floor.+- Make to Order: you manufacture it. The structural frame and the solar array wings are built in-house, so each becomes its own job with its own operations.+- Purchase to Order: you purchase it. The battery packs come from a supplier, so they flow through `guides/rfq-to-po` as a purchase order, never touching the floor.- Pull from Inventory: you pull it from stock when the parent is built, whether you originally made it or bought it.You don't tag this on each BoM line by hand. The method type lives on `docs/reference/items`, and every BoM that uses that item mirrors it. Switch a part's method type once, and it cascades everywhere the part appears.@@ -24,16 +24,16 @@ Method type answers "how does this part get into its parent?": Make to Order, Pu## Kits & subassemblies-Because the arm and leg are Make to Order parts, they aren't just line items — they're built things. But Carbon gives a made item in a BoM two flavors, and the choice changes how the floor handles it:+Because the structural frame and the power subsystem are Make to Order parts, they aren't just line items — they're built things. But Carbon gives a made item in a BoM two flavors, and the choice changes how the floor handles it:-- Subassembly: built as its own job, with its own routing and its own completion. You can release the left arm independently of the final robot, and Carbon keeps the hierarchy in sync.+- Subassembly: built as its own job, with its own routing and its own completion. You can release the structural frame independently of the final satellite, and Carbon keeps the hierarchy in sync.- Kit: not built separately at all. Its components are issued together straight into the parent job, as a set. There's no kit job and no kit operation — just the parts, grouped.Reach for a subassembly when the thing is genuinely manufactured and worth tracking on its own. Reach for a kit when a cluster of parts always goes in together and a separate build would just be ceremony.## Methods on the job-Back on the job, you're looking at that working copy of the method from the last chapter, and you can drill the whole way down. The robot's method lists the arm and leg; open the arm and you're in the arm's method, its machined part set to Make to Order and its motor set to Purchase to Order. The tree is as deep as the product.+Back on the job, you're looking at that working copy of the method from the last chapter, and you can drill the whole way down. The bus's method lists the structural frame, the power subsystem, and their siblings; open the power subsystem and you're in its method, its solar array wings set to Make to Order and its battery pack set to Purchase to Order. The tree is as deep as the product.Methods are versioned, which is what keeps a busy shop sane. A method is Draft, Active, or Archived, and only a Draft can be edited. An Active method is frozen, the jobs running against it won't shift under anyone's feet, so you revise by publishing a new version, not by editing a live one.diff --git a/apps/erp/app/modules/agent/kb/guides/change-order.md b/apps/erp/app/modules/agent/kb/guides/change-order.mdindex e87a9ec4c5..ca3f514179 100644--- a/apps/erp/app/modules/agent/kb/guides/change-order.md+++ b/apps/erp/app/modules/agent/kb/guides/change-order.md@@ -2,7 +2,7 @@> An engineering change, drafted against the real method, reviewed as a diff, and released so planning phases over on its own.-The robot's arm bracket needs a thicker wall and one fewer fastener. In a lot of systems that means editing+The satellite bus's antenna pointing bracket needs a thicker wall and one fewer fastener. In a lot of systems that means editingthe live part and hoping nothing in flight notices. Carbon makes you do it deliberately: you open achange notice, edit a hidden draft of the part's method, review exactly what changed, and releasewhen it's ready. Until that moment, every job, plan, and cost calculation still sees the old bracket.diff --git a/apps/erp/app/modules/agent/kb/guides/floor.md b/apps/erp/app/modules/agent/kb/guides/floor.mdindex 9fc644b003..b1baf7ed45 100644--- a/apps/erp/app/modules/agent/kb/guides/floor.md+++ b/apps/erp/app/modules/agent/kb/guides/floor.md@@ -2,7 +2,7 @@> Work hits the floor; the floor reports back.-Time to build. You release the first production job, the first 30 robots, to the shop floor, along with the subassembly jobs for the parts that feed it. This is the handoff most shops fumble; in Carbon it's a single, traceable step.+Time to build. You release the first production job to the shop floor, along with the subassembly jobs for the parts that feed it. This is the handoff most shops fumble; in Carbon it's a single, traceable step.## The schedule@@ -12,24 +12,24 @@ The MES board is a live read of the schedule, so operators can filter and focus## Operations & work centers-Open a job and its routing is an ordered list of operations. Each operation names a process (Mill, Deburr, Anodize, Assemble) and the work center that runs it, with separate setup, labor, and machine time so estimates and costs are honest about where the hours go.+Open a job and its routing is an ordered list of operations. Each operation names a process (Mill, Weld, Anodize, Assemble) and the work center that runs it, with separate setup, labor, and machine time so estimates and costs are honest about where the hours go.Most operations run on your floor. But some don't, and Carbon plans for that explicitly:- Inside operation: runs at one of your work centers, by your people.-- Outside operation: performed by a supplier. Anodizing the arm part, say: the step leaves your floor, goes out, and comes back to finish its routing.+- Outside operation: performed by a supplier. Hard-anodizing the structural panels, say: the step leaves your floor, goes out, and comes back to finish its routing.-Tie a process to a supplier and mark the operation Outside. Releasing the job raises an Outside Processing PO for that step, priced at the supplier's rate, and its lead time takes its place in the routing, so the schedule knows the arm is away being anodized.+Tie a process to a supplier and mark the operation Outside. Releasing the job raises an Outside Processing PO for that step, priced at the supplier's rate, and its lead time takes its place in the routing, so the schedule knows the frame is away being anodized.## Work instructions-On the shop-floor view, an operator doesn't see a spreadsheet — they see rich work instructions: ordered steps, with images, for the exact operation in front of them. It reads like a great minimal manual, and it's always the current revision.+On the shop-floor view, an operator doesn't see a spreadsheet — they see rich work instructions: an ordered checklist of steps, each with its description and the measurement tolerance it has to meet, for the exact operation in front of them. It reads like a great minimal manual, and it's always the current revision.## At the stationWhen the operator opens their operation on the MES, the controls feel physical, closer to a machine panel than a form. A big Play button reads "Start"; press it and it becomes "Pause". Everything they do here flows straight back to the job:-- Clock time with the "Setup", "Labor", and "Machine" toggles, each of which starts and stops a production event, so the operation's estimated hours meet the actual ones.+- Clock time against the operation's work type: the button beside the Play control reads "Labor", and starting and stopping it opens and closes a production event, so the operation's estimated hours meet the actual ones. An operation that also carries setup or machine time offers those work types in the same control.- "Issue Material" to issue the operation's components onto the job as they're consumed.- "Log Completed" for good units, "Log Scrap" with a scrap reason, or "Log Rework" as pieces come off the operation. "Complete All" reports the whole remaining quantity in one tap.- "Finish" to close the operation. It ends every active production event in one move and flips the operation to "Done".@@ -42,7 +42,7 @@ Logged hours multiply by the work center's labor and machine rates; issued materMaterial leaves inventory two ways in Carbon, and the BoM decides which one applies to each component, so stock stays accurate without busywork:-- Issued: tracked material, like the serialized or batch-tracked motors, is issued to the operation (or picked to the line) so every unit is accounted for by its lot.+- Issued: tracked material, like the serialized frames or the batch-tracked battery packs, is issued to the operation (or picked to the line) so every unit is accounted for by its lot.- Backflushed: non-tracked material is pulled from stock automatically the moment the operation or job reports complete. No transactions, no keystrokes.Flag a material to backflush and you never reconcile it by hand. The moment an operation reports complete, what it consumed is gone from stock and `guides/job-costing` — while the parts that truly need tracing stay explicitly issued.@@ -51,4 +51,4 @@ Flag a material to backflush and you never reconcile it by hand. The moment an oFor parts that demand a paper trail, operators scan as they build. Under the hood, every physical thing (a serial, a batch, a lot) is a tracked entity. Scanning a child into the unit you're building records a `docs/reference/traceability`: the child is marked consumed, the unit is marked produced, and the link between them is permanent.-Serialize what you track one-by-one: the finished robot, its arm, its leg. Batch-track what moves in lots: motors, fasteners, raw stock. Scan a serial into a batch and Carbon records the link, so the robot's record knows exactly which motor lot it carries.+Serialize what you track one-by-one: the finished satellite, its structural frame, its solar array wings. Batch-track what moves in lots: battery packs, fasteners, aluminium plate. Scan a serial into a batch and Carbon records the link, so the satellite's record knows exactly which battery lot it carries.diff --git a/apps/erp/app/modules/agent/kb/guides/job-costing.md b/apps/erp/app/modules/agent/kb/guides/job-costing.mdindex 58dae129d3..6d378eed71 100644--- a/apps/erp/app/modules/agent/kb/guides/job-costing.md+++ b/apps/erp/app/modules/agent/kb/guides/job-costing.md@@ -2,7 +2,7 @@> Where a job's cost comes from, and how it piles up in work-in-process.-The `guides/order` built robots. This flow follows the money those jobs spend. As a job is worked, Carbon accumulates its cost (materials consumed, plus labor, machine, and overhead time) into work-in-process, then releases that cost into finished-goods inventory when the job completes. Every figure here is grounded in real ledger postings, so it's worth being precise about what posts, when, and to which account.+The `guides/order` built satellites. This flow follows the money those jobs spend. As a job is worked, Carbon accumulates its cost (materials consumed, plus labor, machine, and overhead time) into work-in-process, then releases that cost into finished-goods inventory when the job completes. Every figure here is grounded in real ledger postings, so it's worth being precise about what posts, when, and to which account.## Accounting is a switchdiff --git a/apps/erp/app/modules/agent/kb/guides/job-finish-close.md b/apps/erp/app/modules/agent/kb/guides/job-finish-close.mdindex 0f4f6a1a2e..5f3ba7eba0 100644--- a/apps/erp/app/modules/agent/kb/guides/job-finish-close.md+++ b/apps/erp/app/modules/agent/kb/guides/job-finish-close.md@@ -6,7 +6,7 @@ A job has been collecting cost in work-in-process. Three events turn that runnin## Finish into inventory-When the last operation is done, Carbon completes the job. It backflushes any material still owed, catches up any labor that hasn't posted yet, and then **receives the finished goods into inventory**: a debit to inventory, a credit to work-in-process, tagged *Job Receipt*. The job moves to **"Completed"**.+When the last operation is done, you complete the job. The **"Complete Job"** dialog confirms the move — it shows the **"Quantity Completed"**, derived from the serials and batches completed in MES rather than typed in, and warns that the job will no longer be available on the shop floor. Carbon then backflushes any untracked material still owed — serial- and batch-tracked material has to be scanned in on the floor, so it is never backflushed — catches up any labor that hasn't posted yet, and **receives the finished goods into inventory**: a debit to inventory, a credit to work-in-process, tagged *Job Receipt*. The job moves to **"Completed"**.The receipt is valued at the job's **actual accumulated WIP cost** — whatever really went in. Carbon does not receive finished goods at standard and book a variance; the finished unit's cost is simply the sum of what the job spent.diff --git a/apps/erp/app/modules/agent/kb/guides/order.md b/apps/erp/app/modules/agent/kb/guides/order.mdindex a2d0723f2c..d344e97648 100644--- a/apps/erp/app/modules/agent/kb/guides/order.md+++ b/apps/erp/app/modules/agent/kb/guides/order.md@@ -1,24 +1,24 @@# Start with the order-> A 90-unit robot order becomes real work.+> A 90-unit solar array wing order becomes real work.-Meet the shop we'll follow through this guide: an OEM that builds humanoid robots. One customer just placed an order for 90 units. By the end, you'll have followed that order all the way from the sales desk to 90 finished robots on the shipping dock — and seen most of Carbon along the way.+Meet the shop we'll follow through this guide: Nebula Aerospace, an OEM that builds satellites. One customer, NovaSat Networks, just placed an order for 90 solar array wings. By the end, you'll have followed that order all the way from the sales desk to 90 finished wings on the shipping dock — and seen most of Carbon along the way.Carbon spans the office and the floor: ERP for orders, purchasing, and planning; MES for the people actually building. The thread that ties them together is a single order, so that's where we start.## The sales order-Open the sales order dashboard. There's already an order on the books: 90 robots. But the customer doesn't want all 90 at once. They want 30 this week, 30 next week, and 30 the week after. That delivery schedule is going to shape everything downstream.+Open the sales order dashboard. There's already an order on the books: SO000009, 90 SAW-001 Solar Array Wings at $35,000 each. But the customer doesn't want all 90 at once, so the order carries three lines of 30 — one this week, one next week, one the week after. That delivery schedule is going to shape everything downstream.-Shipping part of an order doesn't close it. While any unit still has to ship, the order's status reads **"To Ship and Invoice"**. Once every unit has shipped but you haven't billed yet, it moves to **"To Invoice"**. The order closes only when everything has both shipped and been invoiced. That's what lets one order be fulfilled in batches without losing track of what's left.+Shipping part of an order doesn't close it. The badge on the header reads **"In Progress"**, the display status Carbon shows while the order's make-to-order lines still have production to finish; the stored status underneath is **"To Ship and Invoice"** while any unit has yet to ship. Once every unit has shipped but you haven't billed yet, it moves to **"To Invoice"**. The order closes only when everything has both shipped and been invoiced. That's what lets one order be fulfilled in batches without losing track of what's left.Carbon has a full Quote module with quantity-break pricing, so the 90-unit price could have been negotiated in quote to cash first. We'll pick the story up at the confirmed sales order, where the build truly begins.## Batch it into jobs-You don't build 90 robots as one monolithic job. To match the three-week delivery schedule, you split the order into three jobs of 30, one per delivery, each scheduled, released, and shipped on its own timeline.+You don't build 90 wings as one monolithic job. To match the three-week delivery schedule, the order's three lines of 30 become three jobs of 30, one per delivery, each scheduled, released, and shipped on its own timeline.-You create those jobs from the sales order itself. On the line's **Jobs** card, click **"Make to Order"**; in the **"Convert Line to Job"** dialog, set the **Quantity** to 30 and create the first job. Repeat for the second and third. Carbon counts down the units still waiting on a job (90 → 60 → 30), so you always know how much of the order is left to batch. To build all 90 at once instead, you'd leave the **Quantity** at the full 90 and create a single job.+You create those jobs from the sales order itself. The **"Jobs Required"** banner at the top of the order is the prompt; its **"Create Jobs"** button covers the whole order at once. To do it line by line, use the line's **Jobs** card: click **"Make to Order"** and the **"Convert Line to Job"** dialog opens with the **Quantity** already prefilled at the line's 30. Create the first job, then repeat for the second and third lines. Carbon counts down the units still waiting on a job (90 → 60 → 30), so you always know how much of the order is left to batch. To build only part of a line, lower the prefilled **Quantity** and convert the remainder later.Three jobs of 30 let you release week one now, keep weeks two and three in planning, and ship each batch the moment it's done — instead of waiting on all 90.@@ -26,7 +26,7 @@ Three jobs of 30 let you release week one now, keep weeks two and three in plannFrom the sales order, create the job. Carbon carries the part, quantity, and due date across automatically. The job inherits exactly what was sold. That way, the shop floor always has the up-to-date specifications and requirements for the job.-Carbon carries one more thing across, and it's the most important: the robot's manufacturing method, its full recipe of materials and operations. The job doesn't point at the part's master recipe, though. It gets its own copy.+Carbon carries one more thing across, and it's the most important: the part's manufacturing method, its full recipe of materials and operations. The job doesn't point at the part's master recipe, though. It gets its own copy.## Get the methoddiff --git a/apps/erp/app/modules/agent/kb/guides/plan.md b/apps/erp/app/modules/agent/kb/guides/plan.mdindex 7322ae3e64..ee29d89fb2 100644--- a/apps/erp/app/modules/agent/kb/guides/plan.md+++ b/apps/erp/app/modules/agent/kb/guides/plan.md@@ -2,13 +2,13 @@> Orders and forecast become jobs and POs.-Creating that first job created demand. Carbon now knows it needs arm parts, motors, and machine time. But your sales orders only show part of the picture. The pipeline says more robots are coming, even though no order exists yet.+Creating that first job created demand. Carbon now knows it needs structural frames, battery packs, and machine time. But your sales orders only show part of the picture. The pipeline says more satellite buses are coming, even though no order exists yet.Planning on confirmed orders alone means you're always reacting. Carbon lets you plan on what you expect, too — and lets each part decide for itself how aggressively to replenish.## Demand forecasting-Under Production, open Projections and enter what you expect to need in the coming weeks. Here, the pipeline points to 50 robots in week four and 70 in week five, real demand with no order behind it yet. Forecasting puts it into the plan anyway.+Under Production, open Projections and enter what you expect to need in the coming weeks. Here, the pipeline points to two SAT-1000 satellite buses a week for the next fortnight, climbing to four a week by week six, and to the subsystems that ride with them: ADCS-001 and EPS-001. That's real demand with no order behind it yet. Forecasting puts it into the plan anyway.## Reordering policy@@ -19,13 +19,13 @@ Not every part should wait for demand to pull it. A fast-moving fastener wants a- Fixed Reorder Quantity: when on-hand falls to the reorder point, order a fixed reorder quantity. Predictable, supplier-friendly batch sizes.- Maximum Quantity: when on-hand falls to the reorder point, top back up to the maximum inventory quantity. Classic min/max for shelf stock.-A part set to Buy turns a replenishment into a purchase order; set to Make, it turns into a job. Lot size and minimum / maximum order quantities round the raw number into something you can actually order or build.+A part set to Buy turns a replenishment into a purchase order; set to Make, it turns into a job. The reorder quantity and the minimum / maximum order quantities round the raw number into something you can actually order or build.## Into jobs & POsNow Carbon turns the whole picture (orders, forecast, and each part's policy) into the work that fulfills it. It nets demand against what you already have (on-hand stock plus open jobs and purchase orders) and proposes the difference: `docs/reference/planning` suggests the jobs to build, purchasing planning suggests the purchase orders to raise.-Purchasing planning applies conversion factors as it goes, so a robot's worth of demand becomes the right quantity in the units you actually buy. Nothing is committed until you confirm a suggestion. That's the moment a proposed line becomes a real job or a real PO.+Purchasing planning applies conversion factors as it goes, so a satellite's worth of demand becomes the right quantity in the units you actually buy. Nothing is committed until you confirm a suggestion. That's the moment a proposed line becomes a real job or a real PO.Run different plans for different sites, and let each part replenish the way that site needs: full demand-driven planning in one, simple min/max for high-runners in another.@@ -33,4 +33,4 @@ Run different plans for different sites, and let each part replenish the way thaWhen a purchase order arrives, you receive it. A receipt starts as a Draft against the PO, auto-fills its lines from what was ordered, and validates the quantities; posting it turns the goods into on-hand stock on a shelf.-For a batch-tracked part like the motors, Carbon captures the lot right on the receipt line, and a conversion factor converts what you bought into what you stock, so a box of ten motors becomes ten units on the shelf. Months later, you can answer exactly which lot of motors went into which robots.+For a batch-tracked part like the BAT-LIION-48V battery packs, Carbon captures the batch number right on the receipt line, and a conversion factor converts what you bought into what you stock, so a case of ten packs becomes ten units on the shelf. Months later, you can answer exactly which lot of packs went into which satellites.diff --git a/apps/erp/app/modules/agent/kb/guides/quote-to-cash.md b/apps/erp/app/modules/agent/kb/guides/quote-to-cash.mdindex a184af0bbd..873158f874 100644--- a/apps/erp/app/modules/agent/kb/guides/quote-to-cash.md+++ b/apps/erp/app/modules/agent/kb/guides/quote-to-cash.md@@ -16,7 +16,7 @@ A sales order does not require a quote, and a quote does not require an RFQ. Eac## Build the quote-Open a new quote and add a line per item the customer asked about. Pricing lives on the line and supports quantity breaks, so the unit price for 10 can differ from the price for 100. The negotiated number you land on is what carries forward later.+Open a new quote and add a line per item the customer asked about. Pricing lives on the line and supports quantity breaks, so the unit price for one can differ from the price for twenty-five. The negotiated number you land on is what carries forward later.A fresh quote sits at **"Draft"**. Each line moves through its own state as you work it up: **"Draft"**, **"In Progress"**, then **"Complete"** once you've settled its pricing. The line states let you quote a multi-item inquiry piecemeal instead of all at once, marking lines complete one by one rather than all at once.@@ -26,7 +26,7 @@ When the numbers are ready, finalizing the quote moves it to **"Sent"** and markCarbon can hand the customer the quote directly. With digital quotes enabled, a **"Sent"** quote exposes a private share link: an unguessable id, no login required. Internal notes are stripped before anything reaches the customer.-From that link the customer does one of two things. They **accept**, optionally attaching their PO as a PDF, and the quote converts straight into a sales order. Or they **reject**, and the quote moves to **"Lost"**. Either way the outcome lands back in Carbon without a single email thread.+From that link the customer does one of two things. They **accept** — the page ends with an **"Accept Quote"** button — and the quote converts straight into a sales order; the option to attach their PO as a PDF appears once they've accepted. Or they **reject**, via the **"Reject Quote"** link underneath, and the quote moves to **"Lost"**. Either way the outcome lands back in Carbon without a single email thread.The customer-facing share link turns an accept into a real conversion and a reject into a recorded outcome. A companion customer portal then shows them live order and job status as the work proceeds.diff --git a/apps/erp/app/modules/agent/kb/guides/rfq-to-po.md b/apps/erp/app/modules/agent/kb/guides/rfq-to-po.mdindex 79594fe401..60fd206bcc 100644--- a/apps/erp/app/modules/agent/kb/guides/rfq-to-po.md+++ b/apps/erp/app/modules/agent/kb/guides/rfq-to-po.md@@ -2,7 +2,7 @@> Shop one item to many suppliers, then turn the winning quote into an order.-Every robot the shop builds is mostly parts it buys. RFQ to bill is the procurement side of the house, the mirror image of quote to cash, run from the buyer's chair. You ask suppliers for a price, you place an order, the goods arrive, and a supplier bill lands that you reconcile against what you actually ordered and received.+Every satellite the shop builds is mostly parts it buys. RFQ to bill is the procurement side of the house, the mirror image of quote to cash, run from the buyer's chair. You ask suppliers for a price, you place an order, the goods arrive, and a supplier bill lands that you reconcile against what you actually ordered and received.We'll follow one purchased part from a blank request all the way to a posted supplier invoice.diff --git a/apps/erp/app/modules/agent/kb/guides/ship.md b/apps/erp/app/modules/agent/kb/guides/ship.mdindex 870cb2ef4f..c924adf1f4 100644--- a/apps/erp/app/modules/agent/kb/guides/ship.md+++ b/apps/erp/app/modules/agent/kb/guides/ship.md@@ -2,11 +2,11 @@> Prove it's right, ship it, close the books.-Building the robot is most of the work, but it isn't the whole job. You still have to prove it was built right, and close the loop with the customer and your books.+Building the satellite is most of the work, but it isn't the whole job. You still have to prove it was built right, and close the loop with the customer and your books.## Raise an issue-Say an operator flags a defect on an arm. You open an Issue, Carbon's name for a non-conformance. It moves through a clear lifecycle, from Registered to In Progress to Closed, and it links to the part itself, so the arm now carries that open issue everywhere it appears in the system.+Say an operator flags a short in the EPS wiring harness. You open an Issue, Carbon's name for a non-conformance. It moves through a clear lifecycle, from Registered to In Progress to Closed, and it links to the part and the job operation it was found on, so the bus now carries that open issue everywhere it appears in the system.## Workflows & actions@@ -18,24 +18,24 @@ An issue doesn't just sit there — it runs a workflow you define. A classic 8D- Verification: prove the fix actually worked.- Communication: keep the customer in the loop.-A review step gates what happens to the non-conforming arms: use as is, rework, scrap, or return to the supplier. Nothing is dispositioned on a hunch; the decision is recorded against the issue alongside its actions.+A review step gates what happens to the non-conforming assemblies: use as is, rework, scrap, or return to the supplier. Nothing is dispositioned on a hunch; the decision is recorded against the issue alongside its actions.## Versioned procedures-Those work instructions the operator followed didn't appear from nowhere. They're generated from versioned procedures, the same Draft / Active / Archived discipline you saw on methods. When a corrective action changes how the arm is assembled, you publish a new revision; every future job picks it up, and every job already running keeps the revision it started on.+Those work instructions the operator followed didn't appear from nowhere. They're generated from versioned procedures, the same Draft / Active / Archived discipline you saw on methods. When a corrective action changes how the structural frame is assembled, you publish a new revision; every future job picks it up, and every job already running keeps the revision it started on.-New jobs pick up the latest published version; in-flight jobs never shift mid-build. And every robot's record pins the exact procedure revision it was actually built to.+New jobs pick up the latest published version; in-flight jobs never shift mid-build. And every satellite's record pins the exact procedure revision it was actually built to.## Traceability-Because everything was captured at build time, the genealogy of a finished robot is complete. Carbon stores it as a graph of tracked entities and the activities that link them, so from one serial you can walk backward to every ancestor (which arm, which motor lot, which raw material) or forward to every place a lot was used.+Because everything was captured at build time, the genealogy of a finished satellite is complete. Carbon stores it as a graph of tracked entities and the activities that link them, so from one serial you can walk backward to every ancestor (which frame, which battery lot, which plate of aluminium) or forward to every place a lot was used.-One click, or one scan of the robot's QR label, answers the question every auditor and every recall asks: what exactly went into this unit, and where else did that lot go?+One click, or one scan of the satellite's QR label, answers the question every auditor and every recall asks: what exactly went into this unit, and where else did that lot go?## Ship & invoice-Week one's 30 robots are done. You create a `guides/order-to-cash` against the sales order. It drafts its lines from what's outstanding, you pick and post it, then invoice that same 30. Because the order still has units to ship, it stays at "To Ship and Invoice" and simply carries the remaining 60 forward; the line's completed count rolls up as each batch ships.+The first finished units are ready. You create a `guides/order-to-cash` against the sales order. It drafts its lines from what's outstanding, and you ship only what's actually built: on SHP000001 the line reads 2 shipped against 3 ordered, so 1 stays outstanding. Post it, then invoice that same 2. Because the order still has a unit to ship, it stays at "To Ship and Invoice" and simply carries the remainder forward; the line's shipped count rolls up as each batch goes.Carbon ties the invoice straight into your accounting system, so the build that started at the `guides/quote-to-cash` closes on the books — partial quantity and all.-That's the whole loop: a 90-unit promise became three jobs, a tree of made and bought parts, a forecast-aware plan, traceable work on the floor, a quality save, and a shipped, invoiced, fully-traceable robot. Every entity you saw (methods, kits, policies, operations, issues) has its own page in the Reference when you're ready for the detail.+That's the whole loop: a 90-unit promise became three jobs, a tree of made and bought parts, a forecast-aware plan, traceable work on the floor, a quality save, and a shipped, invoiced, fully-traceable satellite. Every entity you saw (methods, kits, policies, operations, issues) has its own page in the Reference when you're ready for the detail.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex f734625205..8b0c4a6d02 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -99,15 +99,32 @@{"slug": "docs/platform/architecture","title": "Architecture",- "description": "How Carbon is built: the apps, packages, database, event system, background jobs, and auth behind a deployment.",+ "description": "One journey from a button click, through the server, into Postgres, out to background jobs, and back to the screen.","keywords": ["architecture", "docs", "platform"],"headings": [- "Apps",- "Packages",- "The stack",- "Database",- "Events & background jobs",- "Authentication",+ "Part 1: The map",+ "Part 2: Follow one click all the way down",+ "The short version",+ "The same story, with real files",+ "Part 3: Layer by layer",+ "3.1 The browser and the route file",+ "3.2 The gate: who is allowed to do what",+ "3.3 The service layer: four doors to the database",+ "3.4 The database",+ "Part 4: What happens after the write",+ "Part 5: The other engines",+ "Workflows: the customer's own automations",+ "The Assembler: the Rust service",+ "Part 6: The repo map",+ "Part 7: Where it all runs",+ "7.1 On a laptop",+ "7.2 The cloud Carbon runs",+ "7.3 On a customer's own server",+ "7.4 How a merge becomes production",+ "7.5 Knowing what is happening",+ "Part 8: There's a bug, where do I look?",+ "Part 9: House rules",+ "Glossary","Related"]},@@ -1542,7 +1559,7 @@{"slug": "guides/build","title": "Inside the build",- "description": "How each robot part is made or bought.",+ "description": "How each satellite part is made or bought.","keywords": ["inside", "the", "build", "guides"],"headings": ["The bill of materials",@@ -1618,7 +1635,7 @@{"slug": "guides/order","title": "Start with the order",- "description": "A 90-unit robot order becomes real work.",+ "description": "A 90-unit solar array wing order becomes real work.","keywords": ["start", "with", "the", "order", "guides"],"headings": ["The sales order",diff --git a/docs/app/reference.css b/docs/app/reference.cssindex 56f7ece79b..292e056e27 100644--- a/docs/app/reference.css+++ b/docs/app/reference.css@@ -88,6 +88,15 @@.prose :not(pre) > code::after {content: none !important;}+/* …but nowrap on a phone means one long inline path (a full `apps/erp/app/modules/…`+ * reference) widens the whole document and every section scrolls sideways with it.+ * Below the tablet breakpoint, let those chips wrap; desktop keeps identifiers intact. */+@media (max-width: 640px) {+ .prose :not(pre) > code {+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ }+}/* Fenced code → our dark API-playground panel. The MDX `pre` is overridden by* <MdxCodeBlock>, which wraps the shiki output in `pre.mdx-shiki`; the token@@ -300,3 +309,4 @@ figure.ed-codeblock figcaption {-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 24px);mask-image: linear-gradient(to bottom, transparent 0, #000 24px);}+diff --git a/docs/components/editorial/architecture-diagrams.tsx b/docs/components/editorial/architecture-diagrams.tsxnew file mode 100644index 0000000000..b1673cf3f2--- /dev/null+++ b/docs/components/editorial/architecture-diagrams.tsx@@ -0,0 +1,427 @@+/* Hand-laid architecture diagrams for /docs/platform/architecture. See `architecture-kit.tsx`+ * for the shape vocabulary and why these are drawn by hand rather than generated.+ *+ * Editing one means moving coordinates. That is the trade: an auto-layout engine is+ * cheaper to edit and produces something no one can read in a reading column. Keep the+ * canvas near 740 units wide — it is what forces labels short enough to stay legible.+ *+ * Colour is spent, not sprinkled: most boxes are paper and hairline, and a tone is used+ * only where it carries the point of that particular diagram. */++import type { ReactElement } from "react";+import {+ ArrowDefs,+ Badge,+ Boundary,+ Card,+ Edge,+ Eyebrow,+ INK,+ INK_45,+ Lines,+ LINE,+ Node,+ Store,+} from "./architecture-kit";++export type ArchitectureDiagramKey = "map" | "click" | "doors" | "paths" | "events" | "runs" | "triage";++/* Part 1. The spine only: people, the two apps, Supabase over Postgres, and the event+ * loop back into the ERP. Redis and the Assembler are deliberately absent — they are+ * side services, the prose covers them, and drawing them buried the loop that matters. */+function Map() {+ const chips = [+ { x: 34, w: 112, label: "PostgREST" },+ { x: 158, w: 82, label: "Auth" },+ { x: 252, w: 94, label: "Storage" },+ { x: 358, w: 98, label: "Realtime" },+ { x: 468, w: 158, label: "Edge functions" },+ ];+ return (+ <svg viewBox="0 0 740 596" className="w-full h-auto" role="img" aria-label="How Carbon fits together">+ <ArrowDefs />++ <Card x={16} y={14} w={190} h={48} label="Shop floor" sub="tablet" />+ <Card x={236} y={14} w={190} h={48} label="Office staff" sub="browser" />+ <Card x={456} y={14} w={190} h={48} label="Customer" sub="share link" />++ <Edge pts={[[111, 69], [111, 112], [181, 112], [181, 128]]} />+ <Edge pts={[[331, 69], [331, 112], [451, 112], [451, 128]]} />+ <Edge pts={[[551, 69], [551, 112], [511, 112], [511, 128]]} />++ <Boundary x={16} y={100} w={630} h={100} label="Carbon" />+ <Node x={56} y={128} w={250} h={56} label="MES" sub="the shop floor app" tone="app" />+ <Node x={356} y={128} w={250} h={56} label="ERP" sub="the office app, and where jobs run" tone="app" />++ <Edge pts={[[181, 184], [181, 240]]} />+ <Edge pts={[[481, 184], [481, 240]]} label="every read and write" labelAt={[331, 214]} />++ <Boundary x={16} y={240} w={630} h={250} label="Supabase" />+ {chips.map((c) => (+ <Node key={c.label} x={c.x} y={272} w={c.w} h={42} label={c.label} />+ ))}+ {chips.map((c) => (+ <path key={c.label} d={`M ${c.x + c.w / 2} 314 V 340`} fill="none" stroke="rgba(38,35,35,0.35)" strokeWidth={1.1} />+ ))}+ <path d="M 90 340 H 547" fill="none" stroke="rgba(38,35,35,0.35)" strokeWidth={1.1} />+ <Edge pts={[[331, 340], [331, 372]]} soft />++ <Store x={251} y={372} w={160} h={76} label="Postgres" sub="the source of truth" />++ <Edge pts={[[331, 448], [331, 508], [436, 508], [436, 522]]} label="subscribed writes queue an event" labelAt={[383, 502]} />++ <Node x={336} y={522} w={200} h={56} label="Inngest" sub="background jobs" tone="async" />+ <Node x={56} y={522} w={200} h={56} label="Outside world" sub="email, Slack, Xero" />++ <Edge pts={[[336, 550], [256, 550]]} />+ <Edge pts={[[536, 550], [690, 550], [690, 156], [606, 156]]} label="runs the job in the ERP" labelAt={[613, 538]} />+ </svg>+ );+}++/* Part 2, the short version. The section promises "pick this apart and you have seen+ * every layer", so the layers have to be IN the picture — they are the three lanes, and+ * every hop visibly crosses one. A flat list of the same steps reads as prose, not a+ * diagram; short hop labels are what keep this one readable. */+function Click() {+ const L = { browser: 140, erp: 390, pg: 620 };+ type Hop = { from: number; to: number; label: string; back?: boolean; note?: boolean };+ const hops: Hop[] = [+ { from: L.browser, to: L.browser, label: "the form is checked against a zod schema" },+ { from: L.browser, to: L.erp, label: "POST the fields" },+ { from: L.erp, to: L.erp, label: "a POST? and may this user create purchasing?" },+ { from: L.erp, to: L.pg, label: "ask for the next order number" },+ { from: L.pg, to: L.erp, label: '"PO000123"', back: true },+ { from: L.erp, to: L.pg, label: "insert the order, delivery and payment rows" },+ { from: L.pg, to: L.pg, label: "a trigger quietly queues an event", note: true },+ { from: L.pg, to: L.erp, label: "the new row id", back: true },+ { from: L.erp, to: L.browser, label: "302 redirect to the new order's page", back: true },+ { from: L.browser, to: L.erp, label: "GET that page — the loader runs" },+ { from: L.erp, to: L.pg, label: "read the purchaseOrders view" },+ { from: L.pg, to: L.erp, label: "the order, with totals already calculated", back: true },+ { from: L.erp, to: L.browser, label: "the finished page", back: true },+ ];++ const top = 108;+ const pitch = 42;+ const ruleY = top + hops.length * pitch + 6;+ const h = ruleY + 104;++ return (+ <svg viewBox={`0 0 740 ${h}`} className="w-full h-auto" role="img" aria-label="One click, all the way down">+ <ArrowDefs />++ <Card x={55} y={22} w={170} h={46} label="Browser" />+ <Node x={305} y={22} w={170} h={46} label="ERP server" tone="app" />+ <Node x={535} y={22} w={170} h={46} label="Postgres" tone="data" />++ {Object.values(L).map((x) => (+ <path key={x} d={`M ${x} 74 V ${ruleY - 10}`} stroke={LINE} strokeWidth={1.2} fill="none" />+ ))}++ <Eyebrow x={16} y={top - 24} label="The save" />+ <Eyebrow x={16} y={top + 8 * pitch - 14} label="The redirect" />++ {hops.map((hop, i) => {+ const y = top + i * pitch;+ if (hop.from === hop.to) {+ // Self-hop: a small loop hanging off the right of the lane, so work that happens+ // inside one layer still reads as a beat in the sequence.+ // The rightmost lane loops to its left, or the label runs off the canvas.+ const flip = hop.from > 500;+ const d = flip+ ? `M ${hop.from} ${y - 9} h -22 a 9 9 0 0 0 0 18 h 22`+ : `M ${hop.from} ${y - 9} h 22 a 9 9 0 0 1 0 18 h -22`;+ return (+ <g key={hop.label}>+ <path+ d={d}+ fill="none"+ stroke={hop.note ? "#EDA100" : "rgba(38,35,35,0.45)"}+ strokeWidth={1.3}+ markerEnd={hop.note ? undefined : "url(#ah)"}+ />+ <text+ x={flip ? hop.from - 40 : hop.from + 40}+ y={y + 13}+ textAnchor={flip ? "end" : "start"}+ fontSize="11"+ fill={hop.note ? "#8A6000" : INK}+ >+ {hop.label}+ </text>+ </g>+ );+ }+ const mid = (hop.from + hop.to) / 2;+ return (+ <g key={hop.label}>+ <Edge pts={[[hop.from, y], [hop.to, y]]} soft={hop.back} dashed={hop.back} />+ <text x={mid} y={y - 8} textAnchor="middle" fontSize="11" fill={hop.back ? INK_45 : INK}>+ {hop.label}+ </text>+ </g>+ );+ })}++ <path d={`M 16 ${ruleY} H 724`} stroke={LINE} strokeWidth={1.2} strokeDasharray="5 5" fill="none" />+ <text x={724} y={ruleY - 10} textAnchor="end" fontSize="10.5" fill={INK_45}>+ the user's request is finished here+ </text>++ <Eyebrow x={16} y={ruleY + 30} label="Later, on its own" />+ <Edge pts={[[L.pg, ruleY + 10], [L.pg, ruleY + 52]]} dashed soft />+ <Node x={490} y={ruleY + 52} w={215} h={46} label="Background job" sub="indexes the order for search" tone="async" />+ <Lines x={16} y={ruleY + 54} lines={["Nobody waited for this. The page", "had already rendered."]} size={11} />+ </svg>+ );+}++/* Part 3.3. The four doors, as columns rather than a flowchart — the thing a reader needs+ * is a side-by-side comparison of what each one does about RLS, and columns give that for+ * free. The badge row is the answer; the arrows are just plumbing. */+function Doors() {+ const doors = [+ { x: 16, label: "supabase-js", sub: "user scoped", rls: "rules ON", tone: "svc" as const, why: "the default" },+ { x: 196, label: "supabase-js", sub: "service role", rls: "rules OFF", tone: "async" as const, why: "needs to see everything" },+ { x: 376, label: "Kysely", sub: "direct SQL", rls: "rules OFF", tone: "async" as const, why: "needs a real transaction" },+ { x: 556, label: "Edge function", sub: "Deno", rls: "rules OFF", tone: "async" as const, why: "heavy set-based work" },+ ];+ const w = 168;+ return (+ <svg viewBox="0 0 740 486" className="w-full h-auto" role="img" aria-label="Four ways into the database">+ <ArrowDefs />+ <Node x={270} y={16} w={200} h={52} label="Server code" sub="loader, action, or job" tone="app" />++ {doors.map((d) => {+ const cx = d.x + w / 2;+ return (+ <g key={d.sub}>+ <Edge pts={[[370, 68], [370, 94], [cx, 94], [cx, 118]]} soft />+ <Node x={d.x} y={118} w={w} h={58} label={d.label} sub={d.sub} />+ <Badge x={cx} y={190} label={d.rls} tone={d.tone} />+ <text x={cx} y={228} textAnchor="middle" fontSize="11" fill={INK_45}>+ {d.why}+ </text>+ </g>+ );+ })}++ <Edge pts={[[100, 240], [100, 268], [188, 268], [188, 292]]} soft />+ <Edge pts={[[280, 240], [280, 268], [188, 268]]} soft />+ <Node x={108} y={292} w={160} h={46} label="PostgREST" />++ <Edge pts={[[188, 338], [188, 380], [370, 380], [370, 404]]} />+ <Edge pts={[[460, 240], [460, 380], [370, 380]]} />+ <Edge pts={[[640, 240], [640, 380], [370, 380]]} />++ <Store x={290} y={404} w={160} h={72} label="Postgres" />+ </svg>+ );+}++/* Part 3.4. Two rails, deliberately parallel, because the point is that they are separate+ * paths over the same data — writes land in a table, reads come back through a view. */+function Paths() {+ return (+ <svg viewBox="0 0 740 292" className="w-full h-auto" role="img" aria-label="Write path and read path">+ <ArrowDefs />++ <Boundary x={16} y={26} w={708} h={92} label="Write path" />+ <Node x={48} y={54} w={140} h={44} label="action" tone="app" />+ <Edge pts={[[188, 76], [248, 76]]} />+ <Node x={248} y={54} w={180} h={44} label="service upsert" tone="app" />+ <Edge pts={[[428, 76], [488, 76]]} />+ <Node x={488} y={54} w={200} h={44} label="purchaseOrder table" tone="data" />++ <Boundary x={16} y={174} w={708} h={92} label="Read path" />+ <Node x={48} y={202} w={140} h={44} label="loader" tone="app" />+ <Edge pts={[[188, 224], [248, 224]]} />+ <Node x={248} y={202} w={180} h={44} label="service get" tone="app" />+ <Edge pts={[[428, 224], [488, 224]]} />+ <Node x={488} y={202} w={200} h={44} label="purchaseOrders view" tone="data" />++ <Edge pts={[[588, 98], [588, 202]]} dashed soft label="the view reads the table, and joins the rest" labelAt={[588, 150]} />+ </svg>+ );+}++/* Part 4. The chain nothing in the calling code can see. Two things earn their space: the+ * trigger and the queue sit inside Postgres (which is why the enqueue is transactional),+ * and the fan-out at the bottom shows what a subscribed write actually costs. The top node+ * must keep saying "opted-in tables" — only ~90 carry the trigger, and even those enqueue+ * nothing without an active eventSystemSubscription for that company and operation. */+function Events() {+ const handlers = ["Search", "Workflows", "Webhooks", "Audit log", "Sync", "Embeddings"];+ const hw = 108;+ const hgap = 12;+ const hx = (i: number) => 20 + i * (hw + hgap);+ return (+ <svg viewBox="0 0 740 660" className="w-full h-auto" role="img" aria-label="What happens after a write">+ <ArrowDefs />++ <Node x={215} y={14} w={310} h={56} label="A write" sub="to one of the ~90 opted-in tables" tone="app" />+ <Edge pts={[[370, 70], [370, 104]]} />++ <Boundary x={16} y={104} w={708} h={210} label="Inside Postgres" />+ <Node x={215} y={132} w={310} h={56} label="Trigger" sub="dispatch_event_batch, same transaction" tone="data" />+ <Edge pts={[[290, 188], [290, 216], [170, 216], [170, 232]]} soft label="one per matching subscription" labelAt={[196, 210]} />+ <Edge pts={[[450, 188], [450, 216], [570, 216], [570, 240]]} soft />+ <Store x={80} y={232} w={180} h={68} label="PGMQ" sub="a queue, in tables" />+ <Node x={455} y={240} w={230} h={52} label="wake_event_queue" sub="an HTTP ping after commit" tone="data" />++ <Edge pts={[[570, 292], [570, 340]]} label="pg_net" labelAt={[600, 320]} />+ <Node x={475} y={340} w={190} h={48} label="event-wake" sub="edge function" tone="svc" />+ <Edge pts={[[570, 388], [570, 424]]} />+ <Node x={485} y={424} w={170} h={48} label="Inngest" tone="async" />+ <Edge pts={[[570, 472], [570, 500], [495, 500]]} label="POSTs /api/inngest" labelAt={[600, 494]} />++ <Node x={245} y={474} w={250} h={52} label="event-queue job" sub="drains the queue, groups by type" tone="async" />+ <Edge pts={[[170, 300], [170, 500], [245, 500]]} soft label="reads a batch" labelAt={[170, 440]} />++ {handlers.map((h, i) => (+ <g key={h}>+ <Edge pts={[[370, 526], [370, 554], [hx(i) + hw / 2, 554], [hx(i) + hw / 2, 578]]} soft />+ <Node x={hx(i)} y={578} w={hw} h={44} label={h} />+ </g>+ ))}+ </svg>+ );+}++/* Part 7. Three shapes of the same code base, stacked in the order a change travels+ * through them. The two arrows crossing from CI into AWS are the only real coupling. */+function Runs() {+ const wf = [+ { label: "check.yml", sub: "lint, types, tests" },+ { label: "deploy.yml", sub: "build and push images" },+ { label: "supabase.yml", sub: "migrations, edge fns" },+ { label: "inngest.yml", sub: "register jobs" },+ ];+ const ww = 164;+ return (+ <svg viewBox="0 0 740 566" className="w-full h-auto" role="img" aria-label="Where Carbon runs">+ <ArrowDefs />++ <Boundary x={16} y={22} w={708} h={168} label="Your laptop" />+ <Node x={44} y={78} w={180} h={56} label="pnpm dev" sub="the crbn CLI" tone="app" />+ <Edge pts={[[224, 92], [268, 92], [268, 74], [300, 74]]} soft />+ <Edge pts={[[224, 120], [268, 120], [268, 148], [300, 148]]} soft />+ <Node x={300} y={48} w={250} h={52} label="Docker stack" sub="Postgres, Supabase, Inngest" tone="app" />+ <Node x={300} y={122} w={250} h={52} label="Vite" sub="ERP and MES, on the host" tone="app" />+ <Edge pts={[[550, 148], [612, 148], [612, 74], [550, 74]]} soft />++ <Boundary x={16} y={232} w={708} h={110} label="GitHub Actions, on merge to main" />+ {wf.map((w, i) => (+ <Node key={w.label} x={32 + i * (ww + 12)} y={266} w={ww} h={54} label={w.label} sub={w.sub} tone="async" />+ ))}++ <Boundary x={16} y={392} w={708} h={152} label="AWS, one stack per customer" />+ <Node x={44} y={434} w={176} h={56} label="Load balancer" sub="plus WAF limits" tone="app" />+ <Edge pts={[[220, 462], [268, 462]]} />+ <Node x={268} y={434} w={200} h={56} label="ECS Fargate" sub="ERP and MES, 1 to 10" tone="app" />+ <Edge pts={[[468, 462], [516, 462]]} />+ <Store x={516} y={428} w={180} h={68} label="Supabase" sub="managed Postgres" />++ <Edge pts={[[290, 320], [290, 366], [368, 366], [368, 434]]} soft />+ <Edge pts={[[466, 320], [466, 366], [606, 366], [606, 428]]} soft />+ </svg>+ );+}++/* Part 8. A reader arrives knowing their symptom, not their position in a decision tree,+ * so this is three columns and no branching — you find your symptom and read down. */+type TriageColumn = { x: number; head: string; symptoms: { name: string; answer: string[] }[] };++const TRIAGE: TriageColumn[] = [+ {+ x: 16,+ head: "The save failed",+ symptoms: [+ { name: "Red text under a field", answer: ["The zod schema rejected it.", "Open {module}.models.ts"] },+ { name: "A red toast at the top", answer: ["The action's error branch,", "then the service function"] },+ {+ name: "Nothing happened at all",+ answer: ["Check the Network tab. No request", "is the browser validator; a 403", "is requirePermissions"],+ },+ ],+ },+ {+ x: 256,+ head: "The data is wrong",+ symptoms: [+ {+ name: "Wrong in the database too",+ answer: ["The write is wrong. Read the", "service function, then any", "trigger on that table"],+ },+ { name: "Right in the database", answer: ["Is the field computed? Totals", "live in the VIEW, not the table"] },+ { name: "Not computed either", answer: ["Then it is the loader,", "or the component"] },+ ],+ },+ {+ x: 496,+ head: "Nothing happened after",+ symptoms: [+ {+ name: "No email, not in search, no sync",+ answer: ["That is the event pipeline.", "Open the Inngest dashboard,", "find the run, read the failed step"],+ },+ ],+ },+];++const TRIAGE_COL_W = 228;+const TRIAGE_LINE_H = 14;++/* Stack each column's symptoms top-down, so a block's y depends only on the heights of+ * the ones above it rather than on a counter mutated during render. */+function stackSymptoms(symptoms: TriageColumn["symptoms"], from: number) {+ let y = from;+ return symptoms.map((s) => {+ const top = y + 22;+ y = top + (s.answer.length - 1) * TRIAGE_LINE_H + 26;+ return { ...s, top };+ });+}++function Triage() {+ return (+ <svg viewBox="0 0 740 412" className="w-full h-auto" role="img" aria-label="Where to look when something is wrong">+ <ArrowDefs />+ <Node x={245} y={14} w={250} h={48} label="Something is wrong" tone="app" />+ {TRIAGE.map((col) => {+ const cx = col.x + TRIAGE_COL_W / 2;+ return (+ <g key={col.head}>+ <Edge pts={[[370, 62], [370, 88], [cx, 88], [cx, 110]]} soft />+ <Node x={col.x} y={110} w={TRIAGE_COL_W} h={42} label={col.head} />+ {stackSymptoms(col.symptoms, 152).map((s) => (+ <g key={s.name}>+ <path+ d={`M ${col.x + 10} ${s.top - 12} V ${s.top + (s.answer.length - 1) * TRIAGE_LINE_H + 6}`}+ stroke={LINE}+ strokeWidth={1.2}+ fill="none"+ />+ <text x={col.x + 22} y={s.top - 2} fontSize="11.5" fontWeight={560} fill={INK}>+ {s.name}+ </text>+ <Lines x={col.x + 22} y={s.top + 16} lines={s.answer} size={11} />+ </g>+ ))}+ </g>+ );+ })}+ </svg>+ );+}++export const architectureDiagrams: Record<ArchitectureDiagramKey, () => ReactElement> = {+ map: Map,+ click: Click,+ doors: Doors,+ paths: Paths,+ events: Events,+ runs: Runs,+ triage: Triage,+};diff --git a/docs/components/editorial/architecture-kit.tsx b/docs/components/editorial/architecture-kit.tsxnew file mode 100644index 0000000000..62f402a8e7--- /dev/null+++ b/docs/components/editorial/architecture-kit.tsx@@ -0,0 +1,290 @@+/* Primitives for the hand-drawn architecture diagrams (`architecture-diagrams.tsx`).+ *+ * These are laid out by hand rather than generated, because a generated one could not be+ * read at rest: an auto-layout engine spreads a dozen nodes over ~2,000px, and the reading+ * column then shrinks that to a quarter size. Everything here is designed on a 740-unit+ * canvas instead — close to the real render width, so a 14px label renders at about 14px.+ * That constraint is the point: at this size only short labels fit, which is what keeps+ * the diagrams legible without zooming.+ *+ * The vocabulary carries meaning, so a reader can decode a shape before reading it:+ * Node a service or process Card something outside Carbon+ * Store a datastore (cylinder) Boundary a system that owns what's inside it+ * Edge a connector Badge a qualifier on a node+ */++import type { ReactNode } from "react";++export const INK = "#262323";+const INK_60 = "rgba(38,35,35,0.6)";+export const INK_45 = "rgba(38,35,35,0.45)";+const INK_35 = "rgba(38,35,35,0.35)";+export const LINE = "#D8D7D2";+const PAPER = "#FBFBF8";++/* Fill / stroke / text per role. The stroke is the categorical slot; the text is a+ * deeper step of it (the slot hues themselves fail 4.5:1 as text). `plain` is the+ * default — colour is for the nodes that carry the story, not every box. */+export const TONE = {+ plain: { fill: PAPER, stroke: LINE, text: INK },+ app: { fill: "#E8F1FC", stroke: "#2A78D6", text: "#1F5FA8" },+ svc: { fill: "#E3F5E3", stroke: "#008300", text: "#006B00" },+ data: { fill: "#FCEEF3", stroke: "#E87BA4", text: "#B04A72" },+ async: { fill: "#FDF3E0", stroke: "#EDA100", text: "#8A6000" },+} as const;++export type Tone = keyof typeof TONE;++export function ArrowDefs() {+ return (+ <defs>+ <marker id="ah" viewBox="0 0 8 8" refX="6.4" refY="4" markerWidth="7" markerHeight="7" orient="auto">+ <path d="M1 1.4 L6.2 4 L1 6.6" fill="none" stroke={INK_45} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />+ </marker>+ <marker id="ah-soft" viewBox="0 0 8 8" refX="6.4" refY="4" markerWidth="7" markerHeight="7" orient="auto">+ <path d="M1 1.4 L6.2 4 L1 6.6" fill="none" stroke={INK_35} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />+ </marker>+ </defs>+ );+}++export function Node({+ x,+ y,+ w,+ h,+ label,+ sub,+ tone = "plain",+}: {+ x: number;+ y: number;+ w: number;+ h: number;+ label: string;+ sub?: string;+ tone?: Tone;+}) {+ const t = TONE[tone];+ return (+ <g>+ <rect x={x} y={y} width={w} height={h} rx={11} fill={t.fill} stroke={t.stroke} strokeWidth={1.4} />+ <text+ x={x + w / 2}+ y={sub ? y + h / 2 - 3 : y + h / 2 + 5}+ textAnchor="middle"+ fontSize="14"+ fontWeight={545}+ fill={t.text}+ >+ {label}+ </text>+ {sub && (+ <text x={x + w / 2} y={y + h / 2 + 14} textAnchor="middle" fontSize="11" fill={INK_45}>+ {sub}+ </text>+ )}+ </g>+ );+}++/* Something Carbon talks to but does not run — a person's browser, another company's+ * system. The doubled base line reads as a physical thing sitting on a surface, which is+ * what separates it at a glance from the services Carbon owns. */+export function Card({+ x,+ y,+ w,+ h,+ label,+ sub,+}: {+ x: number;+ y: number;+ w: number;+ h: number;+ label: string;+ sub?: string;+}) {+ return (+ <g>+ <rect x={x + 7} y={y + h + 3} width={w - 14} height={4} rx={2} fill="none" stroke={LINE} strokeWidth={1.2} />+ <rect x={x} y={y} width={w} height={h} rx={11} fill="#FFFFFF" stroke={LINE} strokeWidth={1.4} />+ <text x={x + w / 2} y={sub ? y + h / 2 - 3 : y + h / 2 + 5} textAnchor="middle" fontSize="14" fontWeight={545} fill={INK}>+ {label}+ </text>+ {sub && (+ <text x={x + w / 2} y={y + h / 2 + 14} textAnchor="middle" fontSize="11" fill={INK_45}>+ {sub}+ </text>+ )}+ </g>+ );+}++/* Cylinder. `y` is the top of the body, `h` its full height including both caps. */+export function Store({+ x,+ y,+ w,+ h,+ label,+ sub,+ tone = "data",+}: {+ x: number;+ y: number;+ w: number;+ h: number;+ label: string;+ sub?: string;+ tone?: Tone;+}) {+ const t = TONE[tone];+ const ry = 9;+ const body = h - ry * 2;+ return (+ <g>+ <path+ d={`M ${x} ${y + ry} v ${body} a ${w / 2} ${ry} 0 0 0 ${w} 0 v ${-body}`}+ fill={t.fill}+ stroke={t.stroke}+ strokeWidth={1.4}+ />+ <ellipse cx={x + w / 2} cy={y + ry} rx={w / 2} ry={ry} fill="#FFFFFF" stroke={t.stroke} strokeWidth={1.4} />+ <text x={x + w / 2} y={y + ry + body / 2 + (sub ? -1 : 5)} textAnchor="middle" fontSize="14" fontWeight={545} fill={t.text}>+ {label}+ </text>+ {sub && (+ <text x={x + w / 2} y={y + ry + body / 2 + 15} textAnchor="middle" fontSize="11" fill={INK_45}>+ {sub}+ </text>+ )}+ </g>+ );+}++/* A system that owns everything inside it. The label sits on the boundary line itself,+ * in a paper-filled gap, so the rule reads as continuous. */+export function Boundary({+ x,+ y,+ w,+ h,+ label,+ children,+}: {+ x: number;+ y: number;+ w: number;+ h: number;+ label: string;+ children?: ReactNode;+}) {+ const tw = label.length * 6.6 + 18;+ return (+ <g>+ <rect x={x} y={y} width={w} height={h} rx={14} fill="none" stroke={LINE} strokeWidth={1.2} strokeDasharray="5 5" />+ <rect x={x + 22} y={y - 7} width={tw} height={14} fill="#FBFBFB" />+ <text x={x + 22 + tw / 2} y={y + 4} textAnchor="middle" fontSize="10" fontWeight={600} letterSpacing="0.1em" fill={INK_45}>+ {label.toUpperCase()}+ </text>+ {children}+ </g>+ );+}++/* Small pill — a status or qualifier attached to a node, not a node itself. */+export function Badge({ x, y, label, tone = "plain" }: { x: number; y: number; label: string; tone?: Tone }) {+ const t = TONE[tone];+ const w = label.length * 5.6 + 18;+ return (+ <g>+ <rect x={x - w / 2} y={y} width={w} height={19} rx={9.5} fill={t.fill} stroke={t.stroke} strokeWidth={1} />+ <text x={x} y={y + 13} textAnchor="middle" fontSize="10" fontWeight={560} fill={t.text}>+ {label}+ </text>+ </g>+ );+}++/* SVG has no text wrapping, so multi-line copy is authored as an explicit array of+ * lines. Keeping the break points by hand is a feature here — it stops a diagram from+ * silently reflowing into something ugly when a label changes. */+export function Lines({+ x,+ y,+ lines,+ size = 11,+ fill = INK_60,+ anchor = "start",+ lead = 14,+}: {+ x: number;+ y: number;+ lines: string[];+ size?: number;+ fill?: string;+ anchor?: "start" | "middle";+ lead?: number;+}) {+ return (+ <text x={x} y={y} textAnchor={anchor} fontSize={size} fill={fill}>+ {lines.map((l, i) => (+ <tspan key={l} x={x} dy={i ? lead : 0}>+ {l}+ </tspan>+ ))}+ </text>+ );+}++/* Mono uppercase section label — the same eyebrow the Boundary uses, free-standing. */+export function Eyebrow({ x, y, label }: { x: number; y: number; label: string }) {+ return (+ <text x={x} y={y} fontSize="10" fontWeight={600} letterSpacing="0.1em" fill={INK_45}>+ {label.toUpperCase()}+ </text>+ );+}++/* Orthogonal connector. `pts` are absolute points; the line is drawn through them in+ * order, so a right-angle route is just three points. */+export function Edge({+ pts,+ label,+ labelAt,+ soft,+ dashed,+}: {+ pts: [number, number][];+ label?: string;+ labelAt?: [number, number];+ soft?: boolean;+ dashed?: boolean;+}) {+ const d = pts.map(([px, py], i) => `${i ? "L" : "M"} ${px} ${py}`).join(" ");+ const [lx, ly] = labelAt ?? [0, 0];+ return (+ <g>+ <path+ d={d}+ fill="none"+ stroke={soft ? INK_35 : INK_45}+ strokeWidth={soft ? 1.1 : 1.3}+ strokeDasharray={dashed ? "4 4" : undefined}+ strokeLinecap="round"+ strokeLinejoin="round"+ markerEnd={soft ? "url(#ah-soft)" : "url(#ah)"}+ />+ {label && labelAt && (+ <>+ <rect x={lx - (label.length * 5.4) / 2 - 5} y={ly - 9} width={label.length * 5.4 + 10} height={15} rx={4} fill="#FBFBFB" />+ <text x={lx} y={ly + 2} textAnchor="middle" fontSize="10.5" fill={INK_60}>+ {label}+ </text>+ </>+ )}+ </g>+ );+}diff --git a/docs/components/editorial/mdx.tsx b/docs/components/editorial/mdx.tsxindex 9b28eb2ad4..c9a835b4d3 100644--- a/docs/components/editorial/mdx.tsx+++ b/docs/components/editorial/mdx.tsx@@ -1,4 +1,5 @@import type { ComponentPropsWithoutRef, ReactNode } from "react";+import { type ArchitectureDiagramKey, architectureDiagrams } from "./architecture-diagrams";import { Field, FieldTable } from "./field-table";import { type IllustrationKey, illustrations } from "./illustrations";import { Status, StatusFlow } from "./status-flow";@@ -54,6 +55,27 @@ export function Figure({ illustration, caption }: { illustration: IllustrationKe);}+/** A hand-laid architecture diagram (`architecture-diagrams.tsx`). Wider than the prose+ * column on purpose: these are drawn on a ~740-unit canvas and the column is ~595px, so+ * without the bleed every label renders a fifth smaller than it was drawn. The negative+ * margin is clamped at 0 and only applies from `xl`, where the article really is 47.5rem+ * wide; below that the figure just fills the column. */+export function Diagram({ name, caption }: { name: ArchitectureDiagramKey; caption?: ReactNode }) {+ const Svg = architectureDiagrams[name];+ return (+ <figure className="my-10 xl:mr-[min(0px,calc(100%_-_47.5rem))]">+ <Zoomable wide>+ <div className="rounded-xl border border-ed-hairline bg-ed-paper px-5 py-6 shadow-[inset_0_1px_0_#fff] sm:px-7">+ <Svg />+ </div>+ </Zoomable>+ {caption && (+ <figcaption className="mt-3 text-center text-ed-12 text-ink-faint">{caption}</figcaption>+ )}+ </figure>+ );+}+/** A captured screenshot once `src` is set (a path under `docs/public/`, e.g.* "/screens/sales-order.png"); until then, the dashed placeholder box, so a slot can be* authored before the image exists. `label` is the alt text either way. A real image keeps@@ -261,6 +283,7 @@ export const editorialMdxComponents = {a: Anchor,Figure,Screenshot,+ Diagram,Callout,Divider,Term,diff --git a/docs/components/editorial/zoomable.tsx b/docs/components/editorial/zoomable.tsxindex 50ffa586e9..12b7e34cac 100644--- a/docs/components/editorial/zoomable.tsx+++ b/docs/components/editorial/zoomable.tsx@@ -22,7 +22,10 @@ function ignoreAbort(t: ViewTransitionLike | undefined) {t?.ready?.catch(() => {});}-export function Zoomable({ children }: { children: ReactNode }) {+/* `wide` widens the lightbox for content that is much bigger than the prose column.+ * A screenshot at 1100px is already past its native resolution, but an architecture+ * diagram is drawn far wider than the column it renders in. */+export function Zoomable({ children, wide = false }: { children: ReactNode; wide?: boolean }) {const [open, setOpen] = useState(false);const [mounted, setMounted] = useState(false);// True only while a zoom open/close transition is in flight — see `set`.@@ -103,7 +106,9 @@ export function Zoomable({ children }: { children: ReactNode }) {<divonClick={(e) => e.stopPropagation()}style={{ viewTransitionName: name }}- className="relative z-10 max-h-[88vh] w-full max-w-[min(1100px,92vw)] cursor-zoom-out overflow-auto"+ className={`relative z-10 max-h-[88vh] w-full cursor-zoom-out overflow-auto ${+ wide ? "max-w-[min(1900px,96vw)]" : "max-w-[min(1100px,92vw)]"+ }`}>{children}</div>diff --git a/docs/components/mdx.tsx b/docs/components/mdx.tsxindex 2801e3810a..34118a989d 100644--- a/docs/components/mdx.tsx+++ b/docs/components/mdx.tsx@@ -9,7 +9,7 @@ import { Field, FieldTable } from "@/components/editorial/field-table";import { Glossary } from "@/components/editorial/glossary";// Figure/Screenshot + the shared Zoomable island so the Reference gets the same// click-to-enlarge visuals as the Guide (one component, both surfaces).-import { AgentContext, Figure, Screenshot } from "@/components/editorial/mdx";+import { AgentContext, Diagram, Figure, Screenshot } from "@/components/editorial/mdx";// Editorial Callout/Card so the Reference matches the Guide (not Fumadocs defaults).import { Callout, Card, Cards, EnvVar, EnvVars, PlanBadge } from "@/components/editorial/reference-components";import { StatusFlow, Status } from "@/components/editorial/status-flow";@@ -63,6 +63,7 @@ export function getMDXComponents(components?: MDXComponents) {Status,Figure,Screenshot,+ Diagram,PlanBadge,Term,Step,diff --git a/docs/content/docs/platform/architecture.mdx b/docs/content/docs/platform/architecture.mdxindex f07ca0dacf..b54991b27f 100644--- a/docs/content/docs/platform/architecture.mdx+++ b/docs/content/docs/platform/architecture.mdx@@ -1,62 +1,957 @@---title: Architecture-description: "How Carbon is built: the apps, packages, database, event system, background jobs, and auth behind a deployment."+description: "One journey from a button click, through the server, into Postgres, out to background jobs, and back to the screen."----Carbon is a TypeScript monorepo: a handful of apps over a shared set of packages, backed by a single-Postgres database.+Carbon is software that runs a manufacturing business: what it buys, what it holds in stock, what it+builds, what it ships, and whether the quality held up. Two separate apps do that. The **ERP** is the+office app, where people quote, purchase, plan and invoice. The **MES** is the shop floor app, used on+tablets next to the machines to run and record the actual work.-## Apps+This page follows one journey. A user clicks a button, something is saved, other things happen because+of it, and the screen updates. Everything else hangs off that spine. [Part 1](#part-1-the-map) and+[Part 2](#part-2-follow-one-click-all-the-way-down) are the ones to read in order; the rest stands on+its own, so take it in any order you like.-| App | Stack | What it is |+Any term you might not know is marked with a number the first time it appears, like this:+Postgres [[17]](#g17). The number links to a one-line definition in the [Glossary](#glossary) at the+end. Nothing is assumed.++<Callout type="note" title="A snapshot, not a contract">+The file paths, line numbers and counts throughout are accurate as of August 2026. They will drift as+the repository moves; the ideas they illustrate outlast them.+</Callout>++---++## Part 1: The map++Carbon is a monorepo [[10]](#g10): one Git repository holding several applications and+about twenty-five shared libraries, built together by pnpm workspaces and+Turborepo [[25]](#g25). Two of those applications are the products people log into, the+ERP and the MES. Everything else exists to serve them.++The centre of gravity is a single Postgres [[17]](#g17) database. Almost every arrow in+this doc eventually points at it. Unusually for a web app, a lot of logic that you might+expect to live in application code lives _inside_ the database instead: permissions,+computed totals, and the "something changed" notifications. That is the single most+important thing to understand about Carbon, and [Part 3](#part-3-layer-by-layer) explains why.++<Diagram name="map" caption="Everything Carbon runs. The loop on the right is the surprise: Inngest is a timer and a queue, but the job itself executes back inside the ERP." />++Colour is used sparingly in these diagrams, and it means the same thing in all of them:+**blue** is our own apps, **pink** is stored state, **amber** is work that happens in the+background. Everything else is left plain on purpose.++**The five things worth taking from that picture:**++1. **The ERP app is the hub.** It serves pages, and it is also where background jobs+ execute. Inngest [[5]](#g5) does not run our code on its own machines; it calls back+ into the ERP container: it is a timer and a queue that POSTs to `/api/inngest` saying+ "run this job now", and our own code does the work. See+ [Part 4](#part-4-what-happens-after-the-write).+2. **Most database access is not raw SQL.** It goes through PostgREST [[18]](#g18), a+ service that turns `client.from("purchaseOrder").select(...)` into a SQL query. We use+ the `supabase-js` library to talk to it.+3. **The database enforces permissions itself.** Even if application code forgets a+ filter, Postgres will not return another company's rows. (Except on one specific+ escape hatch: see [Part 3](#part-3-layer-by-layer).)+4. **Writes on the right tables cause events automatically.** Around ninety tables opt+ in to a database trigger, and where a company has subscribed to one, search indexing,+ webhooks, audit logs and customer automations all happen without the code that did the+ write knowing about them.+5. **The Rust service is optional.** It turns uploaded CAD files into 3D models the+ browser can show, and works out the order parts come apart in for assembly+ instructions. Carbon runs fine without it.++---++## Part 2: Follow one click all the way down++Here is the whole system in one story: **a buyer creates a Purchase Order.**++Pick this one apart and you have seen every layer: a form, validation, a permission+check, a database write, logic living in Postgres, a background side effect, and the+screen updating. Every other feature in Carbon is a variation on it.++### The short version++<Diagram name="click" caption="One click, all the way down. Every hop crosses a layer, and everything above the dashed line happens while the user waits." />++Notice the shape: the user's request finishes as soon as the row is written. The search+indexing happens afterwards, on its own, and nobody waited for it.++### The same story, with real files++Every path below is real. Open them in your editor as you read.++**1. The button.** It is a link, not a submit button.++`apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx:502`++```tsx+primaryAction={+ permissions.can("create", "purchasing") && (+ <New label={t`Purchase Order`} to={path.to.newPurchaseOrder} />+ )+}+```++Two conventions in three lines. `permissions.can(...)` hides UI the user is not allowed+to use; this is _cosmetic only_, the real check happens on the server. And the URL comes+from `path.to.*`, a single registry of every URL in the app+(`apps/erp/app/utils/path.ts`, ~2,200 lines). **Never hardcode a URL string.**++**2. The form.** `apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm.tsx:116`++```tsx+<ValidatedForm+ method="post"+ validator={purchaseOrderValidator}+ defaultValues={initialValues}+>+```++`ValidatedForm` is our wrapper around a plain HTML form. You hand it a schema; it blocks+submission and shows inline field errors if the data is wrong, and it re-displays server+errors in the same place. Fields (`<Input name="...">`, `<Supplier name="...">`) come+from `~/components/Form`, which re-exports generic inputs plus about ninety+Carbon-specific pickers (Customer, Supplier, Item, Location, Currency…).++**3. The schema.** `apps/erp/app/modules/purchasing/purchasing.models.ts:127`++```ts+export const purchaseOrderValidator = z.object({+ id: zfd.text(z.string().optional()),+ purchaseOrderId: zfd.text(z.string().optional()),+ purchaseOrderType: z.enum(purchaseOrderTypeType, {+ /* ... */+ }),+ supplierId: z.string().min(1, { message: "Supplier is required" }),+ locationId: zfd.text(z.string().optional()),+});+```++zod [[28]](#g28) is a schema library: you describe the shape of the data once, and get+both runtime validation and a TypeScript type from it. `zfd` (`zod-form-data`) handles the+fact that HTML forms send everything as strings: `zfd.text()` turns an empty field into+`undefined` rather than `""`.++**One schema, used in three places:** the browser validates against it, the server+re-validates against it, and the service function's argument type is derived from it. That+is why the three can never drift apart.++**4. The route.** `apps/erp/app/routes/x+/purchase-order+/new.tsx:29`++```ts+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, {+ create: "purchasing",+ bypassRls: true,+ });++ const formData = await request.formData();+ const validation = await validator(newPurchaseOrderValidator).validate(+ formData+ );+ if (validation.error) return validationError(validation.error);++ const result = await insertPurchaseOrder(client, {+ ...validation.data,+ companyId,+ companyGroupId,+ createdBy: userId,+ customFields: setCustomFields(formData),+ });++ if (result.error || !result.data) {+ throw redirect(+ path.to.purchaseOrders,+ await flash(+ request,+ error(result.error, "Failed to insert purchase order")+ )+ );+ }+ throw redirect(path.to.purchaseOrder(result.data.id));+}+```++This is the shape of _every_ write in Carbon:++> **assert the method → check permissions → validate → call a service → redirect.**++A file under `apps/erp/app/routes/` can export up to three things that matter here:++| Export | Runs where | Job |+| ------------------- | -------------------------- | --------------------------- |+| `loader` [[8]](#g8) | server only | fetch the data a page needs |+| `action` [[1]](#g1) | server only | handle a form submission |+| `export default` | server first, then browser | the React component |++`loader` and `action` are stripped out of the JavaScript sent to the browser, so it is+safe to use secrets and database clients in them. This is the same idea as Next.js+server components or a traditional controller; the file just happens to hold both+halves.++**5. The service function.** `apps/erp/app/modules/purchasing/purchasing.service.ts:1393`++Routes never talk to the database directly. They call a _service function_: a plain+function whose first argument is a database client and which returns Supabase's raw+`{ data, error }` without throwing.++```ts+const seq = await client.rpc("get_next_sequence", {+ sequence_name: "purchaseOrder",+ company_id: input.companyId,+});++const order = await client+ .from("purchaseOrder")+ .insert({+ purchaseOrderId,+ supplierId: input.supplierId,+ status: "Draft",+ companyId: input.companyId,+ createdBy: input.createdBy /* ... */,+ })+ .select("id, purchaseOrderId")+ .single();++const [delivery, payment] = await Promise.all([+ client.from("purchaseOrderDelivery").insert({+ /* ... */+ }),+ client.from("purchaseOrderPayment").insert({+ /* ... */+ }),+]);++if (delivery.error || payment.error) {+ await deletePurchaseOrder(client, orderId); // manual undo+ return { data: null, error: delivery.error ?? payment.error };+}+```++That last block is the honest, ugly truth about `supabase-js`: **three `.insert()` calls+are three separate HTTP requests, so they are not a transaction.** If the second fails,+the first is already committed, and we have to undo it by hand. When you need a real+transaction, use Kysely [[6]](#g6) instead. See+[Part 3.3](#33-the-service-layer-four-doors-to-the-database).++**6. What Postgres does by itself.** Two things happened that no TypeScript asked for.++_The order number._ `client.rpc("get_next_sequence", ...)` calls an RPC [[21]](#g21), a+function that lives _inside_ the database+(`packages/database/supabase/migrations/20241115101526_rpc-get-next-sequence.sql`). It+reads and bumps a counter and formats the result (`PO` + zero-padding + optional date+tokens) in a single atomic step. Doing this in application code would hand two+simultaneous buyers the same number.++_The event._ Every insert into `purchaseOrder` fires a Postgres **trigger**, a function+the database runs automatically on a write. It drops a small JSON message onto a queue+that lives in a database table. Nothing in the route knows this is happening. [Part 4](#part-4-what-happens-after-the-write)+follows that message to the end.++**7. The screen updates.** The action ends with `throw redirect(...)`. React Router+follows the redirect and runs the destination's `loader`, which re-reads from the+database and renders the finished page. There is no client-side cache to invalidate and+no "add the new row to the list in state" code. **After any non-GET submission, React+Router automatically re-runs the loaders for the current page.** That is the whole+refresh mechanism.++---++## Part 3: Layer by layer++### 3.1 The browser and the route file++The apps are **React Router v7** in framework mode: server-rendered React, where a+single file owns both a URL's data-loading and its UI. (It is not Remix and not Next.js,+though it is the direct descendant of Remix.) Vite [[27]](#g27) builds it; Tailwind v4+styles it.++**Routes are files on disk.** `apps/erp/app/routes/` has about 1,400 of them, and the+folder structure _is_ the URL structure, with a few conventions:++| In a filename | Means |+| --------------- | ---------------------------------------------------------------------------------- |+| `x+/` | a URL segment and a folder: `x+/purchase-order+/new.tsx` → `/x/purchase-order/new` |+| `_public+/` | a folder for grouping that adds **no** URL segment |+| `_layout.tsx` | a wrapper shared by every route in the folder |+| `$orderId` | a URL parameter: `$orderId.tsx` → `/:orderId` |+| `.` in the name | a `/` in the URL: `dimensions.new.tsx` → `dimensions/new` |+| `_index.tsx` | the page for the folder's own URL |+| `*.server.ts` | ignored by the router; a helper file that never reaches the browser |++Top-level namespaces: `x+` is the logged-in app (66 module folders), `api+` holds JSON+endpoints with no UI, `_public+` is login/logout, and `share+` is the _unauthenticated_+surface: links you email to a customer to view a quote.++**Getting data in.** A `loader` runs on the server, calls service functions, and returns+plain JSON; the component reads it with `useLoaderData<typeof loader>()`. Data shared by+the whole app (the current user, their company, their permissions, feature flags) is+loaded once in `apps/erp/app/routes/x+/_layout.tsx` (about eighteen parallel queries) and+read anywhere via hooks like `useUser()`, `usePermissions()`, `useCompanySettings()`.+Those hooks read the layout route's loader data, not a React context.++**Getting data out.** Forms post to an `action`, as in [Part 2](#part-2-follow-one-click-all-the-way-down). For writes that should+_not_ navigate (reordering rows, an inline edit, a delete button), use `useFetcher()`,+which posts in the background and still triggers the automatic revalidation.++**Shared UI.** Look in two places before writing a component:++- `packages/react/`: the design system (`@carbon/react`). Buttons, modals, comboboxes,+ menus, layout primitives. Built on Radix UI [[19]](#g19) and Tailwind.+- `apps/erp/app/components/`: app-level pieces. The big one is+ `components/Table/Table.tsx`, a single generic table (~1,500 lines, built on TanStack+ Table) that every list screen uses. It handles sorting, filtering, pagination, saved+ views, CSV import/export, column visibility and inline editing. You pass `data`,+ `columns` and `count`; the server does the paging via URL search params.++**Client state** is deliberately small. Reference lists that everything needs (items,+customers, suppliers, people) live in nanostores [[13]](#g13) and are kept fresh by+`RealtimeDataProvider`. Ephemeral UI state (is the search modal open) uses+zustand [[29]](#g29). User and permission data lives in _neither_; it comes from the+route loader.++**Translations** use Lingui [[7]](#g7): wrap a string in `` t`...` `` or `<Trans>`, run+`pnpm lingui:extract`, and translators fill in thirteen locale files.++**MES is the same stack, simpler.** No `modules/` folder: services sit flat in+`apps/mes/app/services/`, all validators in one `models.ts`, routes are one flat level,+and the UI is built for gloved hands on a tablet.++### 3.2 The gate: who is allowed to do what++Every server-side entry point in Carbon starts with the same call. There are about 1,600+of them.++```ts+const { client, companyId, userId } = await requirePermissions(request, {+ create: "purchasing",+});+```++Defined at `packages/auth/src/services/auth.server.ts:195`. It does four jobs at once:++1. **Identifies the caller.** Either from the session cookie (a browser) or from a+ `carbon-key` header (our public API, which additionally gets rate-limited and scope-checked).+2. **Loads their permissions.** Permissions are stored as `<module>_<action>` keys such+ as `purchasing_create` or `sales_view`, each mapping to the list of companies where the+ user holds it. They are fetched by a Postgres function called `get_claims` and cached+ in Redis for an hour. They are _not_ in the JWT.+3. **Refuses if they lack it.** Redirect to login if not signed in at all, or an "Access+ Denied" toast otherwise.+4. **Hands back a database client already scoped to this user**, plus their `companyId`+ and `userId`.++**Multi-tenancy** [[12]](#g12) is the reason for a lot of what follows: Carbon is one+database serving many customer companies. Nearly every table has a `companyId` column and+a composite primary key `("id", "companyId")`. Which company you are acting as is read+from your session cookie, never from the URL.++**RLS (Row Level Security)** [[20]](#g20) is the part worth understanding even if you+never write SQL. It is a Postgres feature where each table carries a rule that is silently+`AND`ed onto every query the database receives. Ours look like this:++```sql+CREATE POLICY "SELECT" ON "public"."reportPin"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);+```++So if a query for another company's purchase orders reaches Postgres, it returns zero+rows. The tenant boundary is enforced by the database, not by us remembering a `.eq()`.+Service functions still filter by `companyId` anyway, as a second line of defence.++**The escape hatch.** Notice `bypassRls: true` in the Purchase Order action. RLS costs+real query time on hot paths, so for trusted employee requests we hand back a service-role+[[22]](#g22) client that skips it entirely. That is a deliberate trade, and it moves the+responsibility back to us: any loader using `bypassRls` must re-check the tenant by hand,+as the PO detail route does:++```ts+if (purchaseOrder.data?.companyId !== companyId)+ throw redirect(path.to.purchaseOrders);+```++**Three kinds of user** share one login system, distinguished by a `role` on their+company membership: `employee`, `customer`, `supplier`. Portal users get much narrower+permission sets, and routes can demand `{ role: "employee" }`. Separately, `share+/`+routes are fully unauthenticated; a long unguessable token in the URL is the credential.++### 3.3 The service layer: four doors to the database++A service function's first argument is always a client, and there is more than one kind.+Picking the wrong one is the most common mistake made here.++<Diagram name="doors" caption="Four ways into the database. Only the first one leaves the database's own security rules switched on." />++**1. The user-scoped client.** What `requirePermissions` normally returns. Every query+runs as that user with RLS applied. Use it unless you have a reason not to.++**2. The service-role client** (`getCarbonServiceRole()`) ignores RLS entirely. Needed+by background jobs (which have no logged-in user), by `share+/` routes, and by+`bypassRls: true` requests. **You are now the only thing standing between a bug and a+cross-tenant data leak.**++**3. Kysely** is a TypeScript SQL query builder that holds a real connection to Postgres,+so it can open a real transaction. This is the answer to the "three inserts aren't+atomic" problem from [Part 2](#part-2-follow-one-click-all-the-way-down):++```ts+return db.transaction().execute(async (trx) => {+ for (const { id, sortOrder, updatedBy } of updates) {+ await trx+ .updateTable("quoteLine")+ .set({ sortOrder, updatedBy })+ .where("id", "=", id)+ .execute();+ }+});+```++Three warnings. Kysely **throws** on failure rather than returning `{ error }`, so wrap it+in `try/catch`. It applies **no** RLS, so authorise before you call it. And the pool it+draws from is small (edge functions ask for exactly one connection,+`getConnectionPool(1)`): if code inside a transaction reaches for a second connection from+the same pool, that second request queues behind a transaction that cannot finish until it+is served, and the whole thing hangs until the timeout. Do all the work of a transaction+on the `trx` handle you were given, never on `db`.++**4. Edge functions** are small programs written for Deno [[2]](#g2), deployed next to the+database and called over HTTP [[4]](#g4). There are about forty in+`packages/database/supabase/functions/`, and they own the genuinely heavy work:+MRP [[11]](#g11), production scheduling, posting a shipment or an invoice to the general+ledger, CSV import, exporting a whole company. Call one and wait for its answer:++```ts+const { data, error } = await client.functions.invoke("post-shipment", {+ body: { type: "post", shipmentId, userId, companyId },+});+```++They exist for two reasons: they can hold a database connection and run a big+multi-thousand-row transaction properly, and they are callable from anywhere (the ERP,+the MES, a background job, the public API), not just from a route handler.++"Heavy" here means heavy in SQL, not heavy in the function. Supabase caps an edge function+tightly, a couple of hundred megabytes of memory and a short processor-time budget, far+below a normal server or an ordinary Lambda, so the useful pattern is to let Postgres do+the lifting and keep the function itself thin. Work that is heavy in JavaScript, or that+runs for minutes, belongs in an Inngest job instead; work that needs real computing power,+like CAD geometry, belongs in the Rust service.++There is also a fifth, narrower door: **RPCs**, plain Postgres functions called with+`client.rpc("name", args)`. About 85 call sites. `get_next_sequence` from [Part 2](#part-2-follow-one-click-all-the-way-down) is one.++### 3.4 The database++Postgres 15, wrapped by Supabase [[24]](#g24), an open-source bundle that adds an+auto-generated REST API (PostgREST), user authentication, file storage, a realtime change+feed, and the edge function runtime, all on top of one ordinary Postgres database.++Rough size, for a sense of scale: **923 migration files**, 362 tables,+101 views, 238 database functions, 154 enum types.++**Migrations** [[9]](#g9). Every schema change is a timestamped SQL file in+`packages/database/supabase/migrations/`, named `YYYYMMDDHHMMSS_kebab-name.sql`. Create+one with `pnpm db:migrate:new <name>`, apply with `pnpm db:migrate`. They are applied in+filename order and never edited after merge.++A typical table shows every convention at once:++```sql+CREATE TABLE "itarCertification" (+ "id" TEXT NOT NULL DEFAULT id('itc'),+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);+ALTER TABLE "public"."itarCertification" ENABLE ROW LEVEL SECURITY;+```++`id('itc')` generates a prefixed, sortable, URL-safe id such as `itc_3xK9...`. The prefix tells+you what an id refers to at a glance.++**Views** [[26]](#g26) **are the read path.** This is the second-most-important idea in+Carbon after RLS.++We **write to tables** but **read from views**. A view is a saved query that behaves like+a table. `purchaseOrders` (plural, that is the naming convention) joins in the supplier+name, sums the line amounts into `orderTotal`, converts currency, counts received+quantities, and fetches a thumbnail. So the create path never calculates a total: it+inserts a header, and the view derives everything else on read.++<Diagram name="paths" caption="Writes land in tables; reads come back through views, which is where computed values like order totals live." />++When a list screen shows a number you cannot find in any table, look for the view. They+are defined in migrations, always with `WITH (security_invoker = true)` so the caller's+RLS still applies.++**Types are generated, never written.** `pnpm run generate:types` points the Supabase CLI+at your local database and writes `packages/database/src/types.ts`, about 80,000 lines+describing every table, view, function and enum. App code imports from it:++```ts+import type { Database } from "@carbon/database";+type PurchaseOrderRow =+ Database["public"]["Tables"]["purchaseOrder"]["Row"];+```++**Run `pnpm run generate:types` after pulling migrations or writing one, before you+typecheck.** Half of all "this property doesn't exist" errors are a stale types file.++**Logic that lives in Postgres.** We push logic into the database when it must hold true+for _every_ writer: the ERP, the MES, an edge function, a background job, the public+API, or someone running SQL by hand. Two examples:++- `update_picking_list_status()` is a trigger that recomputes a picking list's header+ status whenever one of its lines changes. Written from four different places;+ recomputing it in each caller would drift.+- `dispatch_event_batch()` is the event trigger from [Part 4](#part-4-what-happens-after-the-write). It must enqueue in the _same+ transaction_ as the write that caused it, so a rolled-back write never emits a+ phantom event.++**Files** live in Supabase Storage buckets: `private` is the workhorse (attachments,+drawings, quality records), `public` and `avatars` are self-explanatory, plus one bucket+per company and `temp-staging` for large CAD uploads.++---++## Part 4: What happens after the write++Back to that queued event. This chain is the piece most likely to surprise you, because+none of it is visible from the code that did the write.++It is not every write, though. A table only emits events once a migration has opted it in+with `attach_event_trigger('tableName')` — about ninety have — and even then the trigger+enqueues nothing unless that company has an **active subscription** matching the table and+the operation. So the same `UPDATE` can fan out to six handlers for one company and do+absolutely nothing for another.++<Diagram name="events" caption="A subscribed write becomes up to six side effects, none of them visible from the code that did the write." />++Three unfamiliar pieces in that chain: PGMQ [[16]](#g16) is the queue, which lives in+ordinary Postgres tables so a trigger can write to it inside the same transaction;+pg_net [[15]](#g15) is what lets the database make the outbound HTTP ping after that+transaction commits; and Inngest [[5]](#g5) is the background job runner.++In plain terms, Inngest works like this: you send it a named event, it calls one of your+registered functions over HTTP, and it remembers how far that function got. Each+`step.run("id", fn)` inside a function is a checkpoint: if step four fails and retries,+steps one to three are not re-executed; their saved results are handed back. That is why+it is used for anything that must survive a crash.++The wiring is three files:++| What | Where |+| -------------------------------- | ------------------------------------- |+| The client | `packages/lib/src/inngest/client.ts` |+| The list of all 55 job functions | `packages/jobs/src/inngest/index.ts` |+| The HTTP endpoint Inngest calls | `apps/erp/app/routes/api+/inngest.ts` |++That last row is the surprising one: **background jobs run inside the ERP container.**+Inngest is a scheduler and a memory, not a compute host.++**Firing a job on purpose.** The automatic trigger path above is for row changes. When+code wants to _deliberately_ kick something off, it calls the typed helper `trigger()`+(about 108 call sites):++```ts+await trigger("notify", {+ event: NotificationEvent.JobAssignment /* ... */,+});+```++Event names are always `carbon/<something>`.++**Scheduled work** comes from two places. Inngest crons handle app-level jobs: MRP every+three hours, notification digests every fifteen minutes, exchange rates and audit+archiving nightly, workflow-run cleanup at 04:00. All of them are UTC, and any job that+needs a company's local day computes it inside the run. Database-level maintenance uses+pg_cron [[14]](#g14) instead, for refreshing cached aggregate tables and sweeping the event+queue.++**Notifications** fan out from one job (`packages/jobs/.../notifications/notify.ts`) to+three destinations: in-app rows (which the topbar picks up live over Realtime), email via+Resend, and Slack. `packages/notifications` itself is only the list of event types; it+sends nothing.++---++## Part 5: The other engines++### Workflows: the customer's own automations++Carbon ships a drag-and-drop canvas where a _customer_ builds "when a quote is accepted,+notify the account manager and create a job". Confusingly these are also called+workflows, and they are a completely different thing from Inngest jobs:++| | Inngest jobs | Workflows |+| ---------- | ----------------------------- | ---------------------------------------- |+| Written by | us, in TypeScript | customers, on a canvas |+| Stored as | code | JSON rows in `workflowVersion` |+| Runs as | service role, sees everything | **the workflow's owner**, with their RLS |+| Changed by | a deploy | the customer, at any moment |++They reuse the event pipeline from [Part 4](#part-4-what-happens-after-the-write), the `WORKFLOW` branch. A matcher takes the+row change, works out which catalog events it corresponds to, finds subscribed workflows,+and queues one run each. `packages/workflows` holds the pure definition/validation logic+and touches nothing; `packages/jobs/src/workflows/` holds the runtime that actually does+things. Every run and every step is recorded, so a customer can open a run and see what+happened.++### The Assembler: the Rust service++`apps/assembler` plus `crates/` is a Rust HTTP service that converts CAD files (STEP) into+web-renderable 3D (GLB) and plans a collision-free disassembly sequence for assembly+instructions. It wraps two C++ libraries (OpenCASCADE for geometry, FCL for collision).+`packages/viewer` renders its output in the browser.+It is entirely optional; everything else boots without it.++It is not a call-and-wait service. A job is submitted and answered later: the caller posts+the work and gets a job id back, then waits for a callback, with polling as a fallback.+Files never travel through the ERP. The caller hands over signed URLs, one to read the CAD+file from and one to write the result to, and the Rust service streams straight to and+from the storage bucket itself; it holds no database credentials and can see nothing else.+Redis is where job state and finished-result pointers live, which is why the service+refuses to start without it.++---++## Part 6: The repo map++**Applications** (`apps/`, plus `docs/` at the root):++| App | What it is | Dev port |+| ----------- | --------------------------------------------------------------------------- | -------- |+| `erp` | The main product, and the host for all background jobs. By far the largest. | 3000 |+| `mes` | Shop floor: job operations, work centres, scheduling. Touch-first. | 3001 |+| `academy` | Training app for new Carbon users. | 4111 |+| `starter` | A minimal example app showing auth + database + forms. | 4000 |+| `assembler` | The Rust CAD/3D service. | varies |+| `docs` | Public documentation site. The only Next.js app here. | 3002 |++**Libraries** (`packages/`). The ones you will actually touch are near the top:++| Package | What it does |+| --------------- | ----------------------------------------------------------------------- |+| `react` | The design system. **Check here before writing any UI.** |+| `database` | Generated types, migrations, edge functions, database clients. |+| `auth` | Login, sessions, `requirePermissions`, API keys, permission caching. |+| `form` | `ValidatedForm`, field components, zod helpers. |+| `jobs` | Every Inngest background function, plus the workflow runtime. |+| `lib` | Shared server utilities: the Inngest client, `trigger()`, email, Slack. |+| `utils` | Pure helpers: dates, money, arrays, strings, BOM maths. |+| `workflows` | Customer workflow schema, validation and pure runtime. No I/O. |+| `documents` | PDF generation, email templates, barcode and label rendering. |+| `locale` | Lingui setup and language switching. |+| `env` | The one place [environment variables](/docs/platform/self-hosting/environment-variables) are read and validated. |+| `logger` | Structured logging, with request-id correlation. |+| `notifications` | The notification event taxonomy (enums only). |+| `printing` | Printer registry, label queue, physical print delivery. |+| `onboarding` | New-company setup, the "Implementation Hub". |+| `kv` | Redis client plus rate limiting. |+| `stripe` | Billing. Cloud edition only. |+| `ee` | Enterprise-only code: Xero, Slack, Jira, Linear, Onshape, plan gating. |+| `viewer` | 3D model and assembly-instruction rendering. |+| `tiptap` | Rich text editor. |+| `dev` | The `crbn` CLI that runs your local stack. |+| `checks` | Repo conformance rules enforced in CI. |+| `config` | Shared tsconfig, Tailwind theme, vitest preset. No runtime code. |+| `glossary` | Canonical manufacturing term definitions used in field help. |+| `harness` | Internal AI-agent tooling. Not shipped. |++**Inside an ERP module** (there are eighteen, under `apps/erp/app/modules/{module}/`):++```+purchasing/+├── purchasing.models.ts zod schemas and the types derived from them+├── purchasing.service.ts every database operation for this module+├── purchasing.server.ts server-only helpers (optional)+├── types.ts shared types+├── index.ts barrel, import from "~/modules/purchasing"+└── ui/ React components, grouped by feature+```++---++## Part 7: Where it all runs++The same code base runs in three shapes: on a laptop, on the cloud Carbon operates for+customers, and on a server a customer owns. Nothing in the application knows which one it+is in; the difference is entirely in configuration.++<Diagram name="runs" caption="The same code base in three shapes, and the four CI workflows that move it between them." />++### 7.1 On a laptop++`pnpm dev` runs `crbn up`, a custom CLI that boots an eleven-container Docker stack, waits+for Postgres, applies migrations, regenerates the database types, seeds a test user, and+starts the apps. The apps themselves run as ordinary Node processes on the host, not in+containers, which is what makes hot reload fast.++Each Git worktree (a second checkout of the same repository) gets its own ports, its own+database and its own freshly minted keys, so several branches can run at once. Redis is+the one exception: a single shared container, with each worktree given its own numbered+slot inside it.++### 7.2 The cloud Carbon runs++The ERP and MES are packaged as Docker images and run on ECS Fargate [[3]](#g3), which is+Amazon running your container for you without any server to look after. Each service sits+behind its own load balancer on port 3000, is checked for life at `/health`, and scales+between one and ten copies on processor and memory pressure. All of that is described in+`sst.config.ts` (SST [[23]](#g23) is infrastructure-as-code, where you write cloud+resources in TypeScript instead of clicking in a console). The+[AWS with SST](/docs/platform/self-hosting/aws-sst) recipe is the same stack, run by you.++The part that surprises people: **this is not one big shared installation.** There is a+`workspaces` table, and on every deploy `ci/src/deploy.ts` walks it and runs+`sst deploy --stage prod` once per row, each with that customer's own AWS account, region,+domain, certificates, Supabase project and Redis. So Carbon separates customers twice+over: by `companyId` on every row inside one installation ([Part 3](#part-3-layer-by-layer)), and by giving a+customer their own installation entirely. Adding a customer means adding a workspace row.+A row missing a required field is skipped with a log line rather than failing the deploy,+so a tenant can silently not deploy.++Postgres is managed Supabase. There is nothing on Vercel despite some leftover Vercel+packages. There is one Lambda: the Assembler ships as a single image that runs either as a+Lambda function behind an API gateway (the default) or as a container, which is why 3D+conversion can be turned on per customer without changing the main stack.++### 7.3 On a customer's own server++`contrib/deploying/simple-docker-caddy/` holds a complete [self-hosted stack](/docs/platform/self-hosting/docker-caddy): a Docker+Swarm file that brings up Postgres, the Supabase services, Redis, Inngest and both apps on+one machine, with Caddy in front as the only thing exposed to the internet. Secrets are+Swarm secrets rather than environment variables in a file. Migrations run as a throwaway+one-shot container before the apps roll. `scripts/backup.sh` takes a database dump plus+the uploaded files (see [backups](/docs/platform/backups)), and `scripts/harden.sh` does the+basic firewall setup.++Which features exist is decided by one variable, `CARBON_EDITION`: `community`,+`cloud`, `enterprise` or `test`. What each of those buys you is the+[licensing model](/docs/platform/licensing). Self-hosting defaults to `community`; the cloud fan-out+sets `enterprise`.++### 7.4 How a merge becomes production++Four GitHub Actions workflows, and they are deliberately independent of each other rather+than one pipeline:++| Workflow | Fires when | What it does || --- | --- | --- |-| `erp` | React Router 7 + Vite | The ERP: orders, purchasing, planning, accounting. Also hosts the API, the MCP server, and the OAuth endpoints. |-| `mes` | React Router 7 + Vite | The Manufacturing Execution System: shop-floor job execution. |-| `academy` | React Router 7 + Vite | Hosts training video lessons. |-| `docs` | Next.js (Fumadocs) | This documentation site. |+| `check.yml` | every pull request | Biome, typecheck, tests, translation and workflow-catalog checks |+| `deploy.yml` | merge to `main` touching `apps/erp`, `apps/mes` or `packages` | builds both images from the one root `Dockerfile`, pushes them to Amazon's image registry tagged with the commit, then fans out `sst deploy` per workspace |+| `supabase.yml` | merge touching `packages/database/supabase` | applies migrations and deploys edge functions, per workspace |+| `inngest.yml` | after `deploy.yml` succeeds | calls `PUT /api/inngest` on each app so Inngest learns the current list of jobs |-## Packages+Two consequences worth knowing. First, `check.yml` never builds the apps, so a pull+request can go green and still break the image build on merge. Second, migrations and app+code deploy in parallel with no ordering between them, so a migration and the code that+depends on it can land seconds apart in either order; write migrations that are safe+against the previous version of the code.-Shared libraries live in `packages/`, including `database` (Supabase schema + generated types), `react`-(the UI component library), `jobs` (background jobs), `auth`, `ee` (enterprise edition + integrations),-`stripe`, `kv` (Redis), `documents`, `printing`, `locale`, and `dev` (the `crbn` CLI).+There is no version tagging and no rollback button. An image is identified by its commit,+so rolling back means redeploying an older commit. Configuration is not held in a secrets+manager: values are read from the `workspaces` table at deploy time and set as plain+environment variables on the container.-## The stack+### 7.5 Knowing what is happening-- **Framework:** React Router 7 for the apps; Next.js for these docs.-- **Monorepo:** pnpm workspaces + Turborepo.-- **Tooling:** Vite, Biome (lint + format), tsup, strict TypeScript.+Observability is deliberately thin. Logs go through LogTape: colour on a laptop, one JSON+line per entry in production, with sensitive field names blanked out and a request id+threaded through everything so one page load can be followed end to end. There is no log+shipping of its own, so logs are whatever the platform collects: CloudWatch on AWS,+`docker service logs` when self-hosted. PostHog covers product analytics and is switched+off entirely in controlled (ITAR) environments. There is no Sentry and no distributed+tracing.-## Database+----Carbon runs on **Supabase / PostgreSQL**. Multi-tenancy is enforced in the database: every row is scoped-to a company, and **Row Level Security** policies gate access. Types are generated from the schema. Local-development runs Supabase in Docker.+## Part 8: There's a bug, where do I look?-<Callout type="note">-Carbon is multi-company. One deployment can host many companies; isolation is enforced by RLS, not by-application code.-</Callout>+Start from what the user saw and walk inwards. This mirrors the order things happen.-## Events & background jobs+<Diagram name="triage" caption="Start from what the user saw, then read down the one column that matches." />-- **Event system:** Postgres triggers enqueue change events into a PGMQ queue; an **Inngest** cron drains- the queue and routes each event to its handlers (webhook, workflow, sync, search).-- **Background jobs:** run on **Inngest** (`packages/jobs`): MRP, scheduling, exchange-rate updates,- integration syncs, and notifications. App code fires jobs with `trigger()` / `batchTrigger()`.-- **Edge functions:** transactional work runs as **Supabase edge functions** (Deno): posting receipts,- shipments, and invoices; running MRP; importing CSV; issuing and picking material.+**A few specific traps, each of which has caught someone out:**-<Callout type="warn">-Older notes attribute jobs and events to Trigger.dev. That migration is done. Jobs and the event queue-run on **Inngest**; edge functions run on **Supabase / Deno**.-</Callout>+- _TypeScript says a column doesn't exist._ Run `pnpm run generate:types`. Your generated+ types are behind your migrations.+- _A query returns nothing but the row is definitely there._ RLS. Either the `companyId`+ is wrong or you are using a user-scoped client where you needed service role.+- _A write half-succeeded._ Chained `supabase-js` calls are not a transaction. Look for a+ manual rollback that didn't cover the failure.+- _You see another company's data._ Something is using `bypassRls: true` or the+ service-role client without re-checking the tenant. **Treat this as urgent.**+- _A number on a list screen is wrong._ It is almost certainly computed in a view.++---++## Part 9: House rules++The full list is in `AGENTS.md` at the repo root. The ones that cause+the most damage when broken:++- **`pnpm`, never `npm`.**+- **Never use JavaScript `Date`** for parsing, formatting or arithmetic. Use+ `@internationalized/date` and `@carbon/utils`. A build check enforces this. Timezones in+ a manufacturing schedule are not cosmetic.+- **Never hand-edit the generated database types.** Regenerate them.+- **Never skip `companyId` scoping**, even though RLS would probably catch it.+- **Never chain `supabase-js` writes and call it a transaction.** Use Kysely, or an RPC.+- **Never query inside a loop.** Collect the ids and make one `.in()` call.+- **One `{module}.service.ts` and one `{module}.models.ts` per module.** Don't scatter them.+- **Run `pnpm run generate:types` after any migration, before typechecking.**++Useful commands:++```bash+pnpm dev # boot everything+pnpm db:migrate:new <name> # create a migration+pnpm db:migrate # apply migrations+pnpm run generate:types # regenerate database types+pnpm exec turbo run typecheck --filter=erp # typecheck one package+pnpm run lint # Biome+pnpm run test # unit tests+```++Typechecking the whole repo at once runs out of memory, so always use `--filter`.++---++## Glossary++Numbered so the body can point at them. Alphabetical.++<a id="g1"></a>+**1. Action:** the function a route file exports to handle a form submission. Runs on the+server only, never shipped to the browser.++<a id="g2"></a>+**2. Deno:** an alternative JavaScript runtime to Node.js. Our edge functions are written+for it, which is why they use `https://` imports instead of `node_modules`.++<a id="g3"></a>+**3. ECS Fargate:** Amazon's service for running Docker containers without managing the+servers underneath. The ERP and MES run here in production.++<a id="g4"></a>+**4. Edge function:** a small server-side program deployed next to the database, called+over HTTP and awaited like a normal function. Ours are written for Deno.++<a id="g5"></a>+**5. Inngest:** the background job runner. Send it an event; it calls your function over+HTTP and remembers each completed step, so a retry resumes rather than restarts.-## Authentication+<a id="g6"></a>+**6. Kysely:** a TypeScript SQL query builder. Unlike `supabase-js` it holds a real+database connection, so it can run real transactions. It also bypasses RLS.-Carbon uses **Supabase Auth** with HTTP-only cookie sessions and Redis-cached permissions (role- and-attribute-based). Sign-in is by magic link, Google, or Outlook. Programmatic access uses **API keys** (a `carbon-key`-header), and a full **OAuth 2.0 server** backs the Claude remote connector.+<a id="g7"></a>+**7. Lingui:** the translation library. You mark strings in code; it extracts them into+per-language files for translators.++<a id="g8"></a>+**8. Loader:** the function a route file exports to fetch the data its page needs. Runs+on the server only.++<a id="g9"></a>+**9. Migration:** one timestamped SQL file describing a schema change. The full ordered+set of them _is_ the schema; there is no separate schema file.++<a id="g10"></a>+**10. Monorepo:** one Git repository holding several applications and shared libraries+that are versioned and released together.++<a id="g11"></a>+**11. MRP:** Material Requirements Planning. Works out what to buy and make, and when,+given demand and current stock. Runs as an edge function.++<a id="g12"></a>+**12. Multi-tenancy:** one database and one running application serving many separate+customer companies, with each company's data invisible to the others.++<a id="g13"></a>+**13. nanostores:** a very small state library. We use it for reference lists (items,+customers, suppliers) that many screens read and Realtime keeps fresh.++<a id="g14"></a>+**14. pg_cron:** a Postgres extension that runs SQL on a schedule, inside the database.+Used for cache refreshes and queue sweeping.++<a id="g15"></a>+**15. pg_net:** a Postgres extension that lets the database make outbound HTTP calls. We+use it for exactly one thing: pinging the event queue awake after a commit.++<a id="g16"></a>+**16. PGMQ:** a message queue implemented in ordinary Postgres tables. Lets a database+trigger enqueue work inside the same transaction as the write that caused it.++<a id="g17"></a>+**17. Postgres:** the relational database everything in Carbon is built on. Version 15.++<a id="g18"></a>+**18. PostgREST:** a service that exposes Postgres tables and views as a REST API. Every+`client.from(...).select(...)` is a PostgREST call, not raw SQL.++<a id="g19"></a>+**19. Radix UI:** an unstyled, accessible React component library. Our design system adds+Tailwind styling on top of it.++<a id="g20"></a>+**20. RLS (Row Level Security):** a Postgres feature where a per-table rule is+automatically added to every query. It is what keeps one company's data invisible to+another.++<a id="g21"></a>+**21. RPC:** here, calling a function defined inside Postgres from application code, via+`client.rpc("name", args)`.++<a id="g22"></a>+**22. Service role:** a database credential that bypasses all RLS. Powerful; use+carefully.++<a id="g23"></a>+**23. SST:** infrastructure-as-code for AWS, written in TypeScript. `sst.config.ts`+defines our production cluster.++<a id="g24"></a>+**24. Supabase:** an open-source bundle around Postgres: REST API, auth, storage,+realtime and edge functions. We run its containers locally and use the managed version in+production.++<a id="g25"></a>+**25. Turborepo:** the build orchestrator that knows which packages depend on which, so+`pnpm build` only rebuilds what changed.++<a id="g26"></a>+**26. View:** a saved query that behaves like a read-only table. Carbon writes to tables+and reads from views; computed values like order totals live in the view.++<a id="g27"></a>+**27. Vite:** the build tool and dev server behind all our React apps.++<a id="g28"></a>+**28. zod:** a schema library. Describe data once, get validation and a TypeScript type+from the same definition.++<a id="g29"></a>+**29. zustand:** a small React state library. We use it only for throwaway UI state, like+whether a modal is open.++---## Related@@ -67,4 +962,10 @@ header), and a full **OAuth 2.0 server** backs the Claude remote connector.<Card title="Environment variables" href="/docs/platform/self-hosting/environment-variables">The full configuration surface.</Card>+ <Card title="Licensing" href="/docs/platform/licensing">+ What Community, Enterprise and Cloud each include.+ </Card>+ <Card title="Backups" href="/docs/platform/backups">+ Dumping the database and the uploaded files.+ </Card></Cards>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d22e505414..17bcfd3d2d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -6,237 +6,15 @@ settings:catalogs:default:- '@ai-sdk/openai':- specifier: 2.0.102- version: 2.0.102- '@dnd-kit/core':- specifier: 6.3.1- version: 6.3.1- '@dnd-kit/sortable':- specifier: 8.0.0- version: 8.0.0- '@dnd-kit/utilities':- specifier: 3.2.2- version: 3.2.2- '@emoji-mart/data':- specifier: 1.2.1- version: 1.2.1- '@emoji-mart/react':- specifier: 1.1.1- version: 1.1.1- '@internationalized/date':- specifier: 3.12.0- version: 3.12.0- '@lingui/cli':- specifier: 5.9.4- version: 5.9.4- '@lingui/core':- specifier: 5.9.4- version: 5.9.4- '@lingui/macro':- specifier: 5.9.4- version: 5.9.4- '@lingui/react':- specifier: 5.9.4- version: 5.9.4- '@lingui/vite-plugin':- specifier: 5.9.4- version: 5.9.4- '@logtape/logtape':- specifier: 2.2.3- version: 2.2.3- '@logtape/redaction':- specifier: 2.2.3- version: 2.2.3- '@logtape/testing':- specifier: 2.2.3- version: 2.2.3- '@nanostores/react':- specifier: 0.7.3- version: 0.7.3- '@paralleldrive/cuid2':- specifier: 2.2.2- version: 2.2.2- '@react-aria/i18n':- specifier: 3.12.16- version: 3.12.16- '@react-email/components':- specifier: 0.3.3- version: 0.3.3- '@react-pdf/renderer':- specifier: 3.4.5- version: 3.4.5- '@react-router/dev':- specifier: 7.15.1- version: 7.15.1- '@react-router/remix-routes-option-adapter':- specifier: 7.15.1- version: 7.15.1- '@react-router/serve':- specifier: 7.15.1- version: 7.15.1- '@shikijs/langs':- specifier: 4.0.2- version: 4.0.2- '@shikijs/themes':- specifier: 4.0.2- version: 4.0.2- '@shikijs/types':- specifier: 4.0.2- version: 4.0.2- '@slack/web-api':- specifier: 7.10.0- version: 7.10.0- '@supabase/functions-js':- specifier: 2.1.5- version: 2.1.5- '@supabase/postgrest-js':- specifier: 2.80.0- version: 2.80.0- '@supabase/storage-js':- specifier: 2.80.0- version: 2.80.0- '@supabase/supabase-js':- specifier: 2.80.0- version: 2.80.0'@tailwindcss/typography':specifier: 0.5.19version: 0.5.19- '@tailwindcss/vite':- specifier: 4.3.0- version: 4.3.0- '@tiptap/core':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-color':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-list-item':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-table':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-table-cell':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-table-header':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-table-row':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-text-style':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-underline':- specifier: 2.27.2- version: 2.27.2- '@tiptap/extension-youtube':- specifier: 2.27.2- version: 2.27.2- '@tiptap/pm':- specifier: 2.27.2- version: 2.27.2- '@tiptap/react':- specifier: 2.27.2- version: 2.27.2- '@tiptap/starter-kit':- specifier: 2.27.2- version: 2.27.2- '@types/node':- specifier: '24'- version: 24.12.2- '@typescript/native-preview':- specifier: 7.0.0-dev.20260703.1- version: 7.0.0-dev.20260703.1- '@vercel/analytics':- specifier: 1.6.1- version: 1.6.1- '@vercel/react-router':- specifier: 1.2.6- version: 1.2.6- axios:- specifier: 1.15.0- version: 1.15.0- class-variance-authority:- specifier: 0.7.1- version: 0.7.1- cookie:- specifier: 1.1.1- version: 1.1.1- cross-env:- specifier: 7.0.3- version: 7.0.3- dompurify:- specifier: 3.4.0- version: 3.4.0- framer-motion:- specifier: 11.18.2- version: 11.18.2- intl-parse-accept-language:- specifier: 1.0.0- version: 1.0.0- isbot:- specifier: '5'- version: 5.1.37- jose:- specifier: 6.0.11- version: 6.0.11- kysely:- specifier: 0.28.15- version: 0.28.15- nanoid:- specifier: 5.1.7- version: 5.1.7- nanostores:- specifier: 0.9.5- version: 0.9.5- nodemon:- specifier: 3.1.14- version: 3.1.14non.geist:specifier: 1.0.4version: 1.0.4- npm-run-all:- specifier: 4.1.5- version: 4.1.5- posthog-js:- specifier: 1.367.0- version: 1.367.0- react-dropzone:- specifier: 14.4.1- version: 14.4.1- react-hotkeys-hook:- specifier: 4.5.1- version: 4.5.1- react-icons:- specifier: 5.6.0- version: 5.6.0- react-pdf:- specifier: 10.4.1- version: 10.4.1- react-resizable-panels:- specifier: 2.1.9- version: 2.1.9- react-router:- specifier: 7.15.1- version: 7.15.1- remix-flat-routes:- specifier: 0.8.5- version: 0.8.5rimraf:specifier: 5.0.10version: 5.0.10- sst:- specifier: 4.6.9- version: 4.6.9- supabase:- specifier: 2.89.0- version: 2.89.0- tailwind-merge:- specifier: 3.3.0- version: 3.3.0tailwind-scrollbar:specifier: 4.0.2version: 4.0.2@@ -249,36 +27,9 @@ catalogs:tailwindcss-animate:specifier: 1.0.7version: 1.0.7- tsup:- specifier: 8.5.1- version: 8.5.1- tsx:- specifier: 4.21.0- version: 4.21.0typescript:specifier: 5.8.3version: 5.8.3- vite:- specifier: 8.0.10- version: 8.0.10- vite-plugin-babel-macros:- specifier: 1.0.6- version: 1.0.6- vitest:- specifier: 4.1.6- version: 4.1.6- wait-on:- specifier: 7.2.0- version: 7.2.0- zod:- specifier: 3.25.76- version: 3.25.76- zod-form-data:- specifier: 2.0.8- version: 2.0.8- zustand:- specifier: 5.0.12- version: 5.0.12overrides:react: 18.3.1@@ -310,7 +61,7 @@ importers:version: 1.40.0'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])+ version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1@@ -347,7 +98,7 @@ importers:version: 5.9.4([email protected])([email protected])'@react-router/dev':specifier: 'catalog:'- version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@types/aws-lambda':specifier: 8.10.152version: 8.10.152@@ -398,7 +149,7 @@ importers:version: 5.8.3vite-plugin-babel-macros:specifier: 'catalog:'- version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))optionalDependencies:'@rollup/rollup-linux-x64-gnu':specifier: 4.60.1@@ -703,7 +454,7 @@ importers:version: 3.4.5([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])+ version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@react-router/serve':specifier: 'catalog:'version: 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])@@ -748,7 +499,7 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@visx/responsive':specifier: 2.17.0version: 2.17.0([email protected])@@ -983,16 +734,16 @@ importers:version: 5.9.4(@lingui/[email protected]([email protected])([email protected]))([email protected])([email protected])'@lingui/vite-plugin':specifier: 'catalog:'- version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@react-router/dev':specifier: 'catalog:'- version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])'@tailwindcss/vite':specifier: 'catalog:'- version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@types/d3':specifier: 7.4.3version: 7.4.3@@ -1052,13 +803,13 @@ importers:version: 5.8.3vite:specifier: 'catalog:'- version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-babel-macros:specifier: 'catalog:'- version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: 'catalog:'- version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/mes:dependencies:@@ -11336,6 +11087,7 @@ packages:resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}+ deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained.resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}@@ -17150,7 +16902,7 @@ snapshots:'@babel/traverse': 7.29.0'@babel/types': 7.29.0convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17170,7 +16922,7 @@ snapshots:'@babel/types': 7.29.0'@jridgewell/remapping': 2.3.5convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17340,7 +17092,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])globals: 11.12.0transitivePeerDependencies:- supports-color@@ -17353,7 +17105,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3transitivePeerDependencies:- supports-color@@ -18426,16 +18178,6 @@ snapshots:transitivePeerDependencies:- typescript- '@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@lingui/cli': 5.9.4([email protected])([email protected])- '@lingui/conf': 5.9.4([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - babel-plugin-macros- - supports-color- - typescript-'@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@lingui/cli': 5.9.4([email protected])([email protected])@@ -18797,7 +18539,7 @@ snapshots:dependencies:'@oclif/core': 4.11.7ansis: 3.17.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])npm: 11.17.0npm-package-arg: 11.0.3npm-run-path: 5.3.0@@ -22114,7 +21856,7 @@ snapshots:'@react-pdf/primitives': 4.2.0'@react-pdf/stylesheet': 6.1.4- '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.29.0'@babel/generator': 7.29.1@@ -22144,7 +21886,7 @@ snapshots:semver: 7.7.4tinyglobby: 0.2.17valibot: 1.3.1([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:'@react-router/serve': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])@@ -22164,56 +21906,6 @@ snapshots:- tsx- yaml- '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':- dependencies:- '@babel/core': 7.29.0- '@babel/generator': 7.29.1- '@babel/parser': 7.29.2- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])- '@babel/preset-typescript': 7.28.5(@babel/[email protected])- '@babel/traverse': 7.29.0- '@babel/types': 7.29.0- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@remix-run/node-fetch-server': 0.13.1- arg: 5.0.2- babel-dead-code-elimination: 1.0.12- chokidar: 4.0.3- dedent: 1.7.2([email protected])- es-module-lexer: 1.7.0- exit-hook: 2.2.1- isbot: 5.1.37- jsesc: 3.0.2- lodash: 4.17.21- p-map: 7.0.4- pathe: 1.1.2- picocolors: 1.1.1- pkg-types: 2.3.0- prettier: 3.8.1- react-refresh: 0.14.2- semver: 7.7.4- tinyglobby: 0.2.17- valibot: 1.3.1([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- optionalDependencies:- '@react-router/serve': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- typescript: 5.8.3- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - jiti- - less- - lightningcss- - sass- - sass-embedded- - stylus- - sugarss- - supports-color- - terser- - tsx- - yaml-'@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.29.0@@ -22286,15 +21978,9 @@ snapshots:optionalDependencies:typescript: 5.8.3- '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- optionalDependencies:- typescript: 5.8.3-- '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':+ '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])optionalDependencies:typescript: 5.8.3@@ -23579,13 +23265,6 @@ snapshots:postcss-selector-parser: 6.0.10tailwindcss: 4.3.0- '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@tailwindcss/node': 4.3.0- '@tailwindcss/oxide': 4.3.0- tailwindcss: 4.3.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@tailwindcss/node': 4.3.0@@ -24453,16 +24132,6 @@ snapshots:'@vercel/[email protected]': {}- '@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@vercel/static-config': 3.2.0- isbot: 5.1.37- react: 18.3.1- react-dom: 18.3.1([email protected])- ts-morph: 12.0.0-'@vercel/[email protected](patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':dependencies:'@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -24601,14 +24270,6 @@ snapshots:optionalDependencies:vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@vitest/spy': 4.1.6- estree-walker: 3.0.3- magic-string: 0.30.21- optionalDependencies:- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 4.1.6@@ -25078,7 +24739,7 @@ snapshots:dependencies:bytes: 3.1.2content-type: 1.0.5- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])http-errors: 2.0.1iconv-lite: 0.7.2on-finished: 2.4.1@@ -25763,6 +25424,10 @@ snapshots:dependencies:ms: 2.1.3+ dependencies:+ ms: 2.1.3+dependencies:ms: 2.1.3@@ -25959,7 +25624,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0xmlhttprequest-ssl: 2.1.2@@ -25979,7 +25644,7 @@ snapshots:base64id: 2.0.0cookie: 0.7.2cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0transitivePeerDependencies:@@ -26396,7 +26061,7 @@ snapshots:content-type: 1.0.5cookie: 0.7.2cookie-signature: 1.2.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0encodeurl: 2.0.0escape-html: 1.0.3@@ -26525,7 +26190,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3on-finished: 2.4.1@@ -27091,14 +26756,14 @@ snapshots:dependencies:agent-base: 7.1.4- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-colordependencies:agent-base: 9.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -27211,7 +26876,7 @@ snapshots:canonicalize: 1.0.8chalk: 4.1.2cross-fetch: 4.1.0([email protected])- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])hash.js: 1.1.7json-stringify-safe: 5.0.1ms: 2.1.3@@ -27249,7 +26914,7 @@ snapshots:canonicalize: 1.0.8chalk: 4.1.2cross-fetch: 4.1.0([email protected])- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])hash.js: 1.1.7json-stringify-safe: 5.0.1ms: 2.1.3@@ -27311,7 +26976,7 @@ snapshots:dependencies:'@ioredis/commands': 1.5.1cluster-key-slot: 1.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])denque: 2.1.0lodash.defaults: 4.2.0lodash.isarguments: 3.1.0@@ -28437,7 +28102,7 @@ snapshots:dependencies:'@types/debug': 4.1.13- debug: 4.4.3([email protected])+ debug: 4.4.3decode-named-character-reference: 1.3.0devlop: 1.1.0micromark-core-commonmark: 2.0.3@@ -30021,7 +29686,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4resolve: 1.22.11transitivePeerDependencies:@@ -30029,7 +29694,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4transitivePeerDependencies:- supports-color@@ -30146,7 +29811,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0is-promise: 4.0.0parseurl: 1.3.3@@ -30254,7 +29919,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3etag: 1.8.1@@ -30461,7 +30126,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])ws: 8.21.0transitivePeerDependencies:- bufferutil@@ -30482,7 +30147,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -30491,7 +30156,7 @@ snapshots:accepts: 1.3.8base64id: 2.0.0cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io: 6.6.9socket.io-adapter: 2.5.8socket.io-parser: 4.2.6@@ -30954,7 +30619,7 @@ snapshots:dependencies:callsites: 3.1.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])is-observable: 2.1.0observable-fns: 0.6.1optionalDependencies:@@ -31100,7 +30765,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -31128,7 +30793,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -31430,7 +31095,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31451,7 +31116,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31469,25 +31134,14 @@ snapshots:- tsx- yaml- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])'@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])'@types/babel__core': 7.20.5babel-plugin-macros: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - supports-color-- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- '@babel/core': 7.29.0- '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])- '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])- '@types/babel__core': 7.20.5- babel-plugin-macros: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -31585,7 +31239,7 @@ snapshots:tsx: 4.21.0yaml: 2.8.3- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0picomatch: 4.0.4@@ -31594,14 +31248,14 @@ snapshots:tinyglobby: 0.2.17optionalDependencies:'@types/node': 24.12.2- esbuild: 0.28.0+ esbuild: 0.27.7fsevents: 2.3.3jiti: 2.7.0terser: 5.48.0tsx: 4.21.0yaml: 2.8.3- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0picomatch: 4.0.4@@ -31609,8 +31263,8 @@ snapshots:rolldown: 1.0.0-rc.17tinyglobby: 0.2.17optionalDependencies:- '@types/node': 26.1.0- esbuild: 0.27.7+ '@types/node': 24.12.2+ esbuild: 0.28.0fsevents: 2.3.3jiti: 2.7.0terser: 5.48.0@@ -31761,34 +31415,6 @@ snapshots:transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- '@vitest/expect': 4.1.6- '@vitest/mocker': 4.1.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.6- '@vitest/runner': 4.1.6- '@vitest/snapshot': 4.1.6- '@vitest/spy': 4.1.6- '@vitest/utils': 4.1.6- es-module-lexer: 2.0.0- expect-type: 1.3.0- magic-string: 0.30.21- obug: 2.1.1- pathe: 2.0.3- picomatch: 4.0.4- std-env: 4.0.0- tinybench: 2.9.0- tinyexec: 1.2.4- tinyglobby: 0.2.17- tinyrainbow: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0- optionalDependencies:- '@opentelemetry/api': 1.9.0- '@types/node': 26.1.0- transitivePeerDependencies:- - msw-[email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.6