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
feat(telemetry): capture work-done events server-side (#1401)
BettrCallRaul44f20be26a30
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 40162223a3..6213f48619 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -2,6 +2,8 @@ import type { Database, Json } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";+import type { JobSource } from "@carbon/lib/telemetry";+import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";@@ -287,6 +289,24 @@ export async function convertSalesOrderLinesToJobs(continue;}+ // This function inserts into `job` itself rather than going through+ // insertJob, so it inherits none of its instrumentation. Without this,+ // "Create Jobs" on a sales order — the make-to-order path, and for some+ // shops the only way jobs are ever raised — produced no job_created at+ // all, and the account would read as not running production.+ trackWorkEvent("job_created", {+ companyId,+ userId,+ jobId: createJob.data.id,+ itemId: data.itemId,+ quantity: data.quantity,+ scrapQuantity: data.scrapQuantity ?? 0,+ locationId: locationId ?? null,+ salesOrderLineId: line.id,+ deadlineType: data.deadlineType ?? null,+ source: "salesOrder"+ });+if (quoteId) {const upsertMethod = await client.functions.invoke("get-method", {body: {@@ -2424,6 +2444,14 @@ export async function updateJobStatus(companyId,actorId: updatedBy});+ // Same guard as the moment above: a real transition, never a re-save.+ trackWorkEvent("job_released", {+ companyId,+ userId: updatedBy,+ jobId: id,+ priorStatus: prior.data.status,+ source: "erp"+ });} else if (status === "Paused") {await raiseMoment("production.jobHeld", {outputs: { job: { id }, heldBy: { id: updatedBy } },@@ -2746,6 +2774,20 @@ export async function upsertProductionQuantity(}}+/**+ * `options.source` is telemetry-only: which surface raised the job. Five+ * routes, MRP, the MCP tools and the workflow engine all funnel through here+ * and the `job` row cannot tell them apart, so the caller has to say.+ *+ * Unset is reported as `unknown`, never as `erp`. The MCP tool and the+ * workflow engine both reach this through `dispatch(call, context, inputs)`,+ * which has nowhere to put an option, and an `erp` default would file+ * automated job creation as human work — the one thing the field separates.+ *+ * Kept out of the options type literal on purpose: the MCP metadata generator+ * parses that object textually and turns a JSDoc block above a property into a+ * property name of its own, which then ships in the public tool schema.+ */export async function insertJob(client: SupabaseClient<Database>,input: {@@ -2777,6 +2819,7 @@ export async function insertJob(skipMethod?: boolean;skipRecalculate?: boolean;methodSource?: "item" | "quoteLine";+ source?: JobSource;}): Promise<{data: { id: string; jobId: string } | null;@@ -2905,6 +2948,21 @@ export async function insertJob(const createdJobId = job.data.id;+ trackWorkEvent("job_created", {+ companyId: input.companyId,+ userId: input.createdBy,+ jobId: createdJobId,+ itemId: input.itemId,+ quantity: input.quantity,+ scrapQuantity,+ locationId: locationId ?? null,+ salesOrderLineId: input.salesOrderLineId ?? null,+ deadlineType,+ // Narrowed, not trusted: this arrives from an MCP caller as an untyped+ // schema field, so TypeScript is not a guard on it.+ source: asJobSource(options?.source)+ });+if (!options?.skipMethod) {const methodSource =options?.methodSource ??diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 7fe1085120..9858385def 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -1,6 +1,7 @@import type { Database, Json } from "@carbon/database";import { fetchAllFromTable, getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import type { PickPartial } from "@carbon/utils";@@ -230,6 +231,17 @@ export async function convertQuoteToOrder(// employee who created the quote.actorId: payload.digitalQuoteAcceptedBy ? null : payload.userId});++ trackWorkEvent("quote_accepted", {+ companyId: payload.companyId,+ // Same reasoning as the moment above: on a digital acceptance there is+ // no Carbon user, so the event is anonymous rather than attributed to+ // whoever happened to write the quote.+ userId: payload.digitalQuoteAcceptedBy ? null : payload.userId,+ quoteId: payload.id,+ salesOrderId: result.data.convertedId,+ acceptedBy: payload.digitalQuoteAcceptedBy ? "portal" : "internal"+ });}return result;@@ -2043,6 +2055,10 @@ export async function finalizeQuote(actorId: userId});+ // finalizeQuote is the only writer of status 'Sent', and it is also the MCP+ // write path, so this one capture covers API callers too.+ trackWorkEvent("quote_sent", { companyId, userId, quoteId });+return lineUpdate;}diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 9f54409a74..4dc8eb4619 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -1,5 +1,6 @@import type { Database, Tables } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";import { getPurchaseOrderStatus, supportedModelTypes } from "@carbon/utils";import type {@@ -139,6 +140,24 @@ export async function approveRequest(return updatedApproval;});+ // After the transaction, so a rollback emits nothing. The order became+ // real here, not on the finalize route — that one stopped at the gate.+ // Without this, every order a customer routes through an approval+ // threshold is missing from "POs issued", and the shops that configure+ // approval thresholds are the larger ones.+ if (documentType === "purchaseOrder") {+ trackWorkEvent(+ "purchase_order_finalized",+ {+ companyId: approvalRequest.companyId,+ userId,+ purchaseOrderId: documentId,+ stage: "committed"+ },+ { discriminator: "committed" }+ );+ }+return { data: result, error: null };} catch (error) {// Transaction automatically rolled back on errordiff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex f64f3cdfa2..5d70416b84 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { trigger } from "@carbon/jobs";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";import { Loading } from "@carbon/react";import { datetime } from "@carbon/utils";@@ -118,7 +119,7 @@ async function handleKanban({companyId,createdBy: userId},- { skipMethod: true, skipRecalculate: true }+ { skipMethod: true, skipRecalculate: true, source: "kanban" });const id = createdJob.data?.id;@@ -184,6 +185,17 @@ async function handleKanban({}).eq("id", id)]);++ // This path writes job.status directly, so it never reaches+ // updateJobStatus and its raiseMoment. The job was just created above,+ // so the prior status is always Draft.+ trackWorkEvent("job_released", {+ companyId,+ userId,+ jobId: id,+ priorStatus: "Draft",+ source: "kanban"+ });} else if (upsertMethod.error) {logger.error("Kanban operation failed", { error: upsertMethod.error });}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 29221a7e48..293196dd61 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-16T23:17:39.255Z",+ "generated": "2026-08-17T12:34:03.161Z","totalTools": 1442,"modules": 15,"tools": [@@ -21885,7 +21885,8 @@"item","quoteLine"]- }+ },+ "source": {}}}},diff --git a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx b/apps/erp/app/routes/x+/job+/$jobId.complete.tsxindex 5ea24d10fa..da9d061cc6 100644--- a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";@@ -59,6 +60,16 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // complete_job_to_inventory explicitly supports re-completion, so this route+ // can fire twice for one job. The idempotency key is the job id, so the+ // repeat collapses rather than counting a second completion.+ trackWorkEvent("job_completed", {+ companyId,+ userId,+ jobId,+ path: "manual"+ });+// Note: for Non-Inventory (Service) jobs, complete_job_to_inventory itself// fulfills the linked sales-order line — completion is also reachable via// the sync_finish_job_operation interceptor, so the SQL function is thediff --git a/apps/erp/app/routes/x+/job+/$jobId.quantities.new.tsx b/apps/erp/app/routes/x+/job+/$jobId.quantities.new.tsxindex 48f2f75c17..8904ba00f2 100644--- a/apps/erp/app/routes/x+/job+/$jobId.quantities.new.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.quantities.new.tsx@@ -2,6 +2,7 @@ import { assertIsPost, error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";+import { trackWorkEvent } from "@carbon/lib/telemetry";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, redirect, useLoaderData } from "react-router";import {@@ -36,7 +37,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {create: "production"});@@ -79,6 +80,29 @@ export async function action({ request, params }: ActionFunctionArgs) {...d,companyId});++ if (!insert.error && insert.data?.id) {+ // Back-office entry, not the shop floor. The source property is what makes+ // the MES-vs-ERP ratio readable — a clerk typing yesterday's paper+ // traveller in here is a different fact from an operator on a station.+ const common = {+ companyId,+ userId,+ productionQuantityId: insert.data.id,+ jobOperationId: d.jobOperationId,+ quantity: d.quantity,+ source: "erp" as const+ };+ if (d.type === "Scrap") {+ trackWorkEvent("scrap_reported", {+ ...common,+ scrapReasonId: d.scrapReasonId ?? null+ });+ } else if (d.type === "Production") {+ trackWorkEvent("production_quantity_reported", common);+ }+ }+if (insert.error) {return data({},diff --git a/apps/erp/app/routes/x+/job+/bulk.new.tsx b/apps/erp/app/routes/x+/job+/bulk.new.tsxindex 48ebf8020c..4c29f53f37 100644--- a/apps/erp/app/routes/x+/job+/bulk.new.tsx+++ b/apps/erp/app/routes/x+/job+/bulk.new.tsx@@ -110,7 +110,7 @@ export async function action({ request }: ActionFunctionArgs) {createdBy: userId,customFields: setCustomFields(formData)},- { skipRecalculate: true }+ { skipRecalculate: true, source: "bulk" });if (createJob.error || !createJob.data) {diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsxindex f5aca971e0..48cc46a9f2 100644--- a/apps/erp/app/routes/x+/job+/new.tsx+++ b/apps/erp/app/routes/x+/job+/new.tsx@@ -45,14 +45,18 @@ export async function action({ request }: ActionFunctionArgs) {}}- const result = await insertJob(getCarbonServiceRole(), {- ...data,- jobId: data.jobId || undefined,- configuration,- companyId,- createdBy: userId,- customFields: setCustomFields(formData)- });+ const result = await insertJob(+ getCarbonServiceRole(),+ {+ ...data,+ jobId: data.jobId || undefined,+ configuration,+ companyId,+ createdBy: userId,+ customFields: setCustomFields(formData)+ },+ { source: "erp" }+ );if (result.error || !result.data) {throw redirect(diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.status.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.status.tsxindex e32dbab043..9939d67acc 100644--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.status.tsx+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.status.tsx@@ -1,6 +1,7 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { trackWorkEvent } from "@carbon/lib/telemetry";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import {@@ -116,6 +117,27 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (status === "Completed" || status === "Partial") {+ // Partial is the interesting one: it means a line could not be filled,+ // which is the material-availability half of job cycle time.+ //+ // The status is the discriminator, not just a property: a list goes+ // Partial and later Completed, and both are real occurrences. Keyed on the+ // list alone the second collapses into the first and the completion is+ // lost, while re-saving the same status still de-duplicates.+ trackWorkEvent(+ "picking_list_completed",+ {+ companyId,+ userId,+ pickingListId: id,+ finalStatus: status,+ source: "erp"+ },+ { discriminator: status }+ );+ }+throw redirect(path.to.pickingList(id),await flash(request, success("Updated picking list status"))diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex 7895c10056..07133b8c0f 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -182,7 +182,7 @@ export async function action({ request }: ActionFunctionArgs) {createdBy: userId,unitOfMeasureCode: "EA"},- { skipMethod: true, skipRecalculate: true }+ { skipMethod: true, skipRecalculate: true, source: "mrp" });if (createJob.error) {diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsxindex 06e3c8dfa6..6d1cd2b3dd 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx@@ -1,5 +1,6 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import type { ActionFunctionArgs } from "react-router";import { getCompanySettings } from "~/modules/settings";@@ -117,6 +118,12 @@ export async function action({ request, params }: ActionFunctionArgs) {actorId: userId});+ trackWorkEvent("purchase_invoice_posted", {+ companyId,+ userId,+ purchaseInvoiceId: invoiceId+ });+const receiptId =skipReceiptPost && receiptIds?.[0] ? receiptIds[0] : undefined;diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsxindex e15a87646a..ec7e7f84e9 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx@@ -5,6 +5,7 @@ import { flash } from "@carbon/auth/session.server";import { PurchaseOrderEmail } from "@carbon/documents/email";import { validationError, validator } from "@carbon/form";import { trigger } from "@carbon/jobs";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";import { PO_EMAIL_ATTACHMENT_LIMIT_MB } from "@carbon/utils";@@ -122,6 +123,22 @@ export async function action(args: ActionFunctionArgs) {);}+ // Emitted here, not at the end of the route: the order is finalized as of+ // this line, and five things below can redirect out first — a failed PDF+ // upload, a failed document row, any PDF throw, the form validation (which+ // runs after this), and a failed email. Every one of them leaves a finalized+ // order behind, so anything further down under-counts.+ trackWorkEvent(+ "purchase_order_finalized",+ {+ companyId,+ userId,+ purchaseOrderId: orderId,+ stage: approvalRequired ? "gated" : "committed"+ },+ { discriminator: approvalRequired ? "gated" : "committed" }+ );+// If approval is required, create the request and return early// PDF generation, email sending, and price updates happen after approvalif (approvalRequired) {diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsxindex 6677634834..d048763814 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx@@ -8,6 +8,7 @@ import {isBlocked} from "@carbon/ee/storage-rules.server";import { trigger } from "@carbon/jobs";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import { getCachedPrinterConfig } from "@carbon/printing/printing.server";@@ -197,6 +198,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ /** Set by the catch below when the post was rolled back to Draft. */+ let reverted = false;+try {const receiptMetadata = await serviceRole.from("receipt")@@ -296,6 +300,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (thrown instanceof Response) throw thrown;// Only reset to Draft for actual errors+ reverted = true;await client.from("receipt").update({@@ -312,5 +317,19 @@ export async function action({ request, params }: ActionFunctionArgs) {actorId: userId});+ // Below the catch is not the same as "only on success": the catch resets the+ // receipt to Draft and then falls through to here. `reverted` is what makes+ // this a post that actually stuck. (The raiseMoment above has the same+ // exposure and predates this change — see #1294 — but changing when+ // workflows fire is a separate decision.)+ if (!reverted) {+ trackWorkEvent("receipt_posted", {+ companyId,+ userId,+ receiptId,+ sourceDocument: receiptForSurface?.sourceDocument ?? null+ });+ }+throw redirect(path.to.receipt(receiptId));}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsxindex f849108510..99ae14254d 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx@@ -4,6 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { SalesInvoiceEmail } from "@carbon/documents/email";import { validator } from "@carbon/form";import { trigger } from "@carbon/jobs";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { renderAsync } from "@react-email/components";import { parseAcceptLanguage } from "intl-parse-accept-language";@@ -123,6 +124,12 @@ export async function action(args: ActionFunctionArgs) {actorId: userId});+ trackWorkEvent("sales_invoice_posted", {+ companyId,+ userId,+ salesInvoiceId: invoiceId+ });+const acceptLanguage = request.headers.get("accept-language");const locales = parseAcceptLanguage(acceptLanguage, {validate: Intl.DateTimeFormat.supportedLocalesOfdiff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsxindex 4468a482c1..abfc9d24f3 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.job.tsx@@ -47,7 +47,7 @@ export async function action({ request, params }: ActionFunctionArgs) {createdBy: userId,customFields: setCustomFields(formData)},- { methodSource }+ { methodSource, source: "salesOrder" });if (createJob.error || !createJob.data) {diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsxindex 455f758731..3057b68ed5 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx@@ -2,6 +2,7 @@ import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { validator } from "@carbon/form";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { datetime, getSalesOrderStatus } from "@carbon/utils";import { parseAcceptLanguage } from "intl-parse-accept-language";import type { ActionFunctionArgs } from "react-router";@@ -175,6 +176,17 @@ export async function action(args: ActionFunctionArgs) {userId: userId});+ // Below every early return above, so a failed email or a failed status+ // write never counts as a confirmed order.+ trackWorkEvent("sales_order_confirmed", {+ companyId,+ userId,+ salesOrderId: orderId,+ lineCount: orderLines.data?.length ?? 0,+ derivedStatus: status,+ emailed: notification === "Email"+ });+return {success: true,message: "Sales order confirmed"diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex 4e91b37461..02fa37cb0a 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -8,6 +8,7 @@ import {isBlocked} from "@carbon/ee/storage-rules.server";import { trigger } from "@carbon/jobs";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import { getCachedPrinterConfig } from "@carbon/printing/printing.server";@@ -191,6 +192,9 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ /** Set by the catch below when the post was rolled back to Draft. */+ let reverted = false;+try {// Get shipment details to check if it's related to a sales orderconst { data: shipment } = await serviceRole@@ -340,6 +344,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}} catch (thrown) {if (thrown instanceof Response) throw thrown;+ reverted = true;await client.from("shipment").update({@@ -356,6 +361,17 @@ export async function action({ request, params }: ActionFunctionArgs) {actorId: userId});+ // See the receipt post route: below the catch still runs after a rollback,+ // so the flag is what makes this "the post stuck", not the position.+ if (!reverted) {+ trackWorkEvent("shipment_posted", {+ companyId,+ userId,+ shipmentId,+ sourceDocument: shipmentForSurface?.sourceDocument ?? null+ });+ }+if (expiredWarning) {throw redirect(path.to.shipmentDetails(shipmentId),diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex 13ed89492f..0e3d5929fb 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -266,13 +266,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}} else {- const insertProduction = await insertProductionQuantity(serviceRole, {- quantity: quantityToComplete,- jobOperationId: jobOperation.data.id,- notes: "Generated by QR code",- companyId,- createdBy: userId- });+ const insertProduction = await insertProductionQuantity(+ serviceRole,+ {+ quantity: quantityToComplete,+ jobOperationId: jobOperation.data.id,+ notes: "Generated by QR code",+ companyId,+ createdBy: userId+ },+ "mes_qr"+ );if (insertProduction.error) {return redirect(diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.status.tsxindex 9a6dd25fb6..97cd2707ec 100644--- a/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx+++ b/apps/mes/app/routes/x+/picking.$pickingListId.status.tsx@@ -1,6 +1,7 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { trackWorkEvent } from "@carbon/lib/telemetry";import type { ActionFunctionArgs } from "react-router";import { userContext } from "~/context";import { getCompanySettings } from "~/services/inventory.service";@@ -113,6 +114,20 @@ export async function action({ context, request, params }: ActionFunctionArgs) {};}+ // Discriminated on the status for the same reason as the ERP route: a list+ // that goes Partial and later Completed must produce two events.+ trackWorkEvent(+ "picking_list_completed",+ {+ companyId,+ userId: effectiveUserId,+ pickingListId,+ finalStatus: finalStatus,+ source: "mes"+ },+ { discriminator: finalStatus }+ );+return { success: true };}diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex c8e137e02f..acf9b630a9 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -181,7 +181,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {companyId,createdBy: userId},- trackedEntityId || undefined+ trackedEntityId || undefined,+ undefined,+ "mes_qr");if (startEvent.error) {diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 33c66910ff..60106dfd51 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1,5 +1,7 @@import type { Database } from "@carbon/database";import { getCompanyTimeZone } from "@carbon/database";+import type { WorkSource } from "@carbon/lib/telemetry";+import { trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";@@ -206,6 +208,40 @@ export async function finishJobOperation(companyId: args.companyId,actorId: args.userId});++ // The status write above has no prior-status guard, so finishing an+ // already-Done operation writes again. The idempotency key is the+ // operation id, so the repeat collapses instead of counting twice.+ trackWorkEvent("job_operation_finished", {+ companyId: args.companyId,+ userId: args.userId,+ jobOperationId: args.jobOperationId,+ jobId+ });++ // The only way to observe the automatic completion. When this was the+ // last operation, sync_finish_job_operation has already flipped the job+ // to Completed inside the same transaction as the status write above —+ // in Postgres, with no application call site in any runtime. Reading the+ // row back here is what closes the last link of the benchmark chain+ // (created → released → started → reported → finished → completed).+ // Keyed on jobId, so it collapses with the manual complete route rather+ // than counting a second completion.+ const completed = await client+ .from("job")+ .select("status")+ .eq("id", jobId)+ .eq("companyId", args.companyId)+ .maybeSingle();++ if (completed.data?.status === "Completed") {+ trackWorkEvent("job_completed", {+ companyId: args.companyId,+ userId: args.userId,+ jobId,+ path: "auto"+ });+ }}}@@ -1537,9 +1573,11 @@ export async function insertProductionQuantity(// index on inspectionSampleId is the double-count guard).inspectionId?: string;inspectionSampleId?: string;- }+ },+ /** Which surface posted it. Telemetry only — the row cannot tell. */+ source: WorkSource = "mes") {- return client+ const result = await client.from("productionQuantity").insert(sanitize({@@ -1548,6 +1586,20 @@ export async function insertProductionQuantity(})).select("*");++ const inserted = result.data?.[0];+ if (inserted) {+ trackWorkEvent("production_quantity_reported", {+ companyId: data.companyId,+ userId: data.createdBy,+ productionQuantityId: inserted.id,+ jobOperationId: data.jobOperationId,+ quantity: data.quantity,+ source+ });+ }++ return result;}export async function insertScrapQuantity(@@ -1679,7 +1731,9 @@ export async function startProductionEvent(createdBy: string;},trackedEntityId: string | undefined,- unitIndex?: number+ unitIndex?: number,+ /** `mes_qr` when the operator scanned a traveller rather than tapping a station. */+ source: WorkSource = "mes") {if (trackedEntityId) {const activityId = nanoid();@@ -1748,6 +1802,15 @@ export async function startProductionEvent(userId: data.createdBy});+ trackWorkEvent("job_operation_started", {+ companyId: data.companyId,+ userId: data.createdBy,+ productionEventId: eventInsert.data.id,+ jobOperationId: data.jobOperationId,+ eventType: data.type,+ source+ });+return eventInsert;}@@ -1761,6 +1824,18 @@ export async function startProductionEvent(jobOperationId: data.jobOperationId,userId: data.createdBy});++ const inserted = eventInsert.data?.[0];+ if (inserted) {+ trackWorkEvent("job_operation_started", {+ companyId: data.companyId,+ userId: data.createdBy,+ productionEventId: inserted.id,+ jobOperationId: data.jobOperationId,+ eventType: data.type,+ source+ });+ }}return eventInsert;diff --git a/packages/lib/AGENTS.md b/packages/lib/AGENTS.mdindex 7ef6739a59..b70974210b 100644--- a/packages/lib/AGENTS.md+++ b/packages/lib/AGENTS.md@@ -8,6 +8,7 @@ Shared server utilities — event system, Inngest client, trigger dispatch, Rese- **Add new events to the `Events` type in `events.ts`** — every Inngest event needs a typed payload here- **Add new task mappings to `taskToEvent` in `trigger.ts`** — maps human-readable task IDs to `carbon/*` event names- **Guard external calls** — `resend.server.ts` respects `DISABLE_RESEND` env; `slack.server.ts` skips sends on localhost+- **Add new work events to `src/telemetry/events.ts`** — the `WorkEvents` type map is the contract; `captureWorkEvent` is typed off it, so an unlisted name will not compile## Ask First@@ -23,6 +24,7 @@ Shared server utilities — event system, Inngest client, trigger dispatch, Rese```bashpnpm --filter @carbon/lib typecheck # tsgo --noEmit+pnpm --filter @carbon/lib test # vitest run```## Key Patterns@@ -30,7 +32,8 @@ pnpm --filter @carbon/lib typecheck # tsgo --noEmit- **Inngest client**: `src/inngest/client.ts` — singleton `new Inngest({ id: "carbon", logger: createInngestLogger() })`. The `logger` (from `@carbon/logger/inngest`) routes every job's `ctx.logger` into LogTape under the `["carbon","jobs"]` category.- **Trigger helper**: `trigger(taskId, payload)` / `batchTrigger(taskId, items)` — typed dispatch- **Events**: `src/events.ts` — full `Events` type map (`carbon/notify`, `carbon/send-email`, `carbon/send-slack`, etc.)-- **Exports**: `./events`, `./inngest`, `./trigger`, `./resend.server`, `./slack.server`, `./twenty.server`+- **Exports**: `./events`, `./inngest`, `./trigger`, `./telemetry`, `./resend.server`, `./slack.server`, `./twenty.server`+- **Work-event telemetry**: `src/telemetry/` — `trackWorkEvent()` records work done on the platform (jobs released, quotes sent, POs issued) as a PostHog event, over a bare `fetch` with no SDK. Three rules it must keep: it **never throws into the caller** (same contract as `raiseMoment` — a lost measurement beats a failed action), the event `uuid` is **deterministic** from (companyId, event, recordId, discriminator) so a retry collapses instead of double-counting, and it emits only when `POSTHOG_PROJECT_PUBLIC_KEY` is set and `CONTROLLED_ENVIRONMENT` is off — the same gate `apps/erp/app/entry.client.tsx:31` puts on the browser SDK. Deliberately **not** named `.server`: MES service files are in the client graph (React components import their types), so a `.server` specifier fails the React Router build — which is also why the hash is plain TypeScript rather than `node:crypto`. See `src/telemetry/README.md` for the coverage gaps and `VERIFICATION.md` for the post-deploy runbook- **Workflow moments**: `src/workflows/raise-moment.ts` — `raiseMoment()` announces a business moment (as opposed to a row change) to the workflow matcher. Two rules it must keep: it **never throws into the caller** (a failed announcement must not fail the business operation that raised it — it logs instead), and the `momentId` it mints is used twice, as the Inngest event id *and* as the matcher's `sourceEventId`, which is what makes a redelivery idempotent. See `.claude/rules/workflow-matcher.md`## Cross-Referencesdiff --git a/packages/lib/package.json b/packages/lib/package.jsonindex 1236f6d8de..2af9b92fca 100644--- a/packages/lib/package.json+++ b/packages/lib/package.json@@ -23,7 +23,8 @@"rimraf": "catalog:","tsup": "catalog:","tsx": "catalog:",- "typescript": "catalog:"+ "typescript": "catalog:",+ "vitest": "catalog:"},"exports": {"./events": "./src/events.ts",@@ -31,6 +32,7 @@"./resend.server": "./src/resend.server.ts","./shims": "./src/shims.ts","./slack.server": "./src/slack.server.ts",+ "./telemetry": "./src/telemetry/capture.ts","./trigger": "./src/trigger.ts","./twenty.server": "./src/twenty.server.ts","./workflows": "./src/workflows/raise-moment.ts"@@ -40,7 +42,8 @@"clean": "rimraf .turbo node_modules dist","dev": "tsup --watch","lint": "biome lint --write ",- "typecheck": "tsgo --noEmit"+ "typecheck": "tsgo --noEmit",+ "test": "vitest run"},"sideEffects": ["./src/shims.ts"diff --git a/packages/lib/src/telemetry/README.md b/packages/lib/src/telemetry/README.mdnew file mode 100644index 0000000000..b34108a3f4--- /dev/null+++ b/packages/lib/src/telemetry/README.md@@ -0,0 +1,105 @@+# Work-event telemetry++Server-side capture of *work done on the platform* — jobs released, quotes sent,+POs issued — as opposed to screens opened, which is all Carbon measured before.++`capture.ts` is the emitter, `events.ts` is the typed catalog, `idempotency.ts`+mints the stable event id. The full 47-event catalog this draws from, with the+deferred waves and the reasoning per event, is+`adoption-tracking/work-done-events.md` in the parent directory of this repo.++## Adding an event++1. Add it to `WorkEvents` in `events.ts` with its properties.+2. Add it to `WORK_EVENT_MODULE` and `WORK_EVENT_RECORD_KEY`.+3. Call `trackWorkEvent("name", { ... })` at the seam.++The type map is the contract: an unknown name or a missing property will not+compile. Payloads carry ids, enums, counts and quantities — never money, part+numbers, names or free text (see the header of `events.ts` for why).++## Where to put the call++**Immediately after the write that makes the work true**, not at the end of the+handler. Everything between the two is a chance to redirect out and lose the+event: the purchase-order route has five such exits — a failed PDF upload, a+failed document row, a PDF throw, the form validation, and a failed email — all+after the order is already finalized.++**Below a rollback catch is not the same as "only on success."** Carbon's+posting routes reset the document to Draft inside the catch and then *fall+through*, so a capture placed after the catch still fires on a reverted post.+Set a flag in the catch and test it. (`raiseMoment` sits in that position with a+comment claiming otherwise — it has fired on rolled-back receipts since #1294.+Left alone here: changing when customer workflows fire is a separate decision.)++**Watch for the second half of a lifecycle in another module.** `approveRequest`+in `~/modules/shared` is what releases a gated purchase order, and it never+returns to the finalize route — a single capture there counted the orders that+stopped at a threshold and missed every one that actually committed money.++Pick the record whose id makes one occurrence unique. For a status change that is+the document; for repeatable work — a production posting, an operator clocking on+— it is the row that posting created, never the operation it was against.++## Semantics: an event counts entry into a state++The id is (companyId, event, recordId, discriminator), so a document that+re-enters a state produces the same id and de-duplicates. That is right for a+double-clicked Post button and wrong for genuine repeat work, so where both+states are real occurrences, pass the state as the `discriminator` —+`purchase_order_finalized` (`gated` / `committed`) and `picking_list_completed`+(`Partial` / `Completed`) both do.++Three sequences still collapse by design, and their tiles should be labelled+accordingly: a quote revised and re-sent, a receipt voided and re-posted, an+order reopened and re-confirmed. Each counts once. Read those tiles as+"documents that ever reached this state", never as "times someone did this".++## What it does not cover++Deliberate gaps, so nobody reads a zero as "no work happened":++| Path | Why | What would fix it |+|---|---|---|+| `scrap_reported` from the MES floor (`apps/mes/app/routes/x+/scrap.tsx:37`) | The `productionQuantity` row is created inside the `issue` Deno function and its id is never returned to the route, so there is no key that makes one posting distinct. Keying on the operation would under-count a shift's repeat postings. | Return the inserted id from the `issue` function. |+| `production_quantity_reported` serial and batch branches | Same function, same reason (`functions/issue/index.ts:1117`, `:1266`). The untracked branch goes through `insertProductionQuantity` and *is* covered. | As above. |+| ~~`job_completed` via the automatic path~~ | Covered. `sync_finish_job_operation` runs inside the same transaction as the operation status flip, so `finishJobOperation` reads the job back and emits `path: "auto"` when it flipped. Keyed on `jobId`, so it collapses with the manual route. | — |+| `quote_accepted` from the customer portal | Covered, but anonymous — `actorId` is deliberately null for a customer's own acceptance. | Nothing; this is correct. |+| `job_created` via MCP or a customer workflow | Covered, but `source` is `unknown`. Both dispatch `production_insertJob` through a generic `(call, context, inputs)` signature with nowhere to put an option. Reported honestly rather than defaulted to `erp`, which would file automation as human work. | Thread a provenance field through the dispatch contract, or read the `workflow_run_id` JWT claim the event system already captures. |+| `job_created` via the deprecated `upsertJob` | Not covered. Inserts a `job` row directly (`production.service.ts`) and is still exposed as an MCP tool. | Route it through `insertJob`, or delete it. |++### Write paths no app-layer capture can see++Found by reading every entry point for each event, not by inspection of the+routes I happened to instrument. None of these are fixable from a route+handler, and each one makes the corresponding count a floor rather than a+total.++| Path | Reaches | Note |+|---|---|---|+| **PostgREST with a `carbon-key`** — `PATCH /rest/v1/job`, `/salesOrder`, `/purchaseOrder`, `/quote`, `/pickingList`, `/salesInvoice` | every status-change event | Carbon's public API is the generated PostgREST surface. An API key with the module's `_update` scope can set any status directly. Structurally invisible to app code. |+| **Deno edge functions invoked directly** — `post-receipt`, `post-shipment`, `post-sales-invoice`, `post-purchase-invoice`, `post-picking`, `schedule`, `convert` | the four posting events, `picking_list_completed`, `job_released` | `requirePermissions` accepts a `carbon-key`, so these are callable without ever entering the app. |+| **Postgres trigger `update_picking_list_status_trigger`** | `picking_list_completed` | The header completes as a consequence of line picks, not a status call — so the two instrumented routes see only the subset a human closed by hand. |+| **`schedule` with `mode: "initial"`** sets `job.status = 'Ready'` in Kysely | `job_released` | Latent today via `packages/jobs/.../recalculate.ts:95`; the two live callers also call `updateJobStatus`, which does emit. |+| **Inngest `carbon/post-transaction`** | receipt, shipment, purchase-invoice posts | Registered and fully wired, with no in-repo sender. Silent the day one appears. |+| **Paperless Parts webhook** inserts a `salesOrder` at `Confirmed` | `sales_order_confirmed` | A real integration, entirely outside the confirm route. |+| **MES inspection-lot disposition** (`inspection-lot.$id.disposition.tsx`) | `scrap_reported` | Scrap that a customer would absolutely call scrap. Emits nothing today. |+| **MCP tools** — `updateJobStatus`, `updateSalesOrderStatus`, `releaseSalesOrder`, `finalizePurchaseOrder`, `upsert*` | most events | Covered *only* where the capture sits in the service rather than the route, because MCP dispatches into services by name. `quote_sent` gets this right; the route-level captures do not. |++That last row is the pattern worth acting on: **instrument the service choke+point, not the route**, wherever the service is the single writer. It covers+MCP and API callers for free. The route-level placements here trade that away+for properties only the route knows (`emailed`, `source`, the derived status).++Everything above is the honest ceiling of the app-layer approach. Closing it+means the event-system queue handler (a Postgres trigger sees every one of+these, since they all end in a row change) or changes inside the Deno+functions.++## Verifying it after deploy++Nothing is observable until this is on `main` and deployed — the emitter is gated+on `POSTHOG_PROJECT_PUBLIC_KEY`, which is unset in local development by design.+`VERIFICATION.md` beside this file is the runbook: what to check at one hour, one+day and three days, with the exact queries and the pass criteria for each.diff --git a/packages/lib/src/telemetry/VERIFICATION.md b/packages/lib/src/telemetry/VERIFICATION.mdnew file mode 100644index 0000000000..f625d8f949--- /dev/null+++ b/packages/lib/src/telemetry/VERIFICATION.md@@ -0,0 +1,182 @@+# Verifying work events after deploy++Work events cannot be observed before this is on `main` and deployed. The emitter+is gated on `POSTHOG_PROJECT_PUBLIC_KEY`, which local development deliberately+leaves unset, so a green local build proves the code compiles and nothing else.++This is the runbook for the first three days. Each check states what passes, what+fails, and what a failure means — a check with no failure condition is not a+check.++Run the queries in PostHog against project **CarbonOS** (id 80891, US cloud).++---++## Before merging++- [ ] Read `POSTHOG_API_HOST` from the deployed ERP env and confirm the browser+ is currently ingesting through it. The emitter POSTs to+ `${POSTHOG_API_HOST}/e/` — deliberately the same host and path `posthog-js`+ uses, because that is the one combination proven against the deployed+ value rather than against the docs. If the browser's events are arriving,+ the server's will too. **This is the most likely single point of failure+ and the cheapest thing to check.**+- [ ] Confirm the ERP and MES deployments share that project key. If they differ,+ MES-sourced events land in a different project and the MES-vs-ERP ratio is+ silently wrong rather than absent.++---++## T+1 hour — is anything arriving at all?++```sql+SELECT event, count() AS n, min(timestamp) AS first_seen, max(timestamp) AS last_seen+FROM events+WHERE timestamp > now() - INTERVAL 2 HOUR+ AND properties.work_event = true+GROUP BY event+ORDER BY n DESC+```++**Pass:** at least one row. **Fail:** zero rows.++Zero does not by itself mean the code is broken — it may mean nobody did any+work in that hour, which on this customer base is entirely plausible. Distinguish+the two before touching anything:++```sql+SELECT count() FROM events WHERE timestamp > now() - INTERVAL 2 HOUR+```++If that is also near zero, nobody was using Carbon; wait. If it is healthy and+`work_event` is empty, the emitter is failing. Check the ERP logs for+`work event rejected` (a non-2xx from PostHog, which logs the status and body)+or `work event failed` (network, timeout, or a thrown error). The emitter never+throws into the request, so a total failure is silent everywhere except the log.++---++## T+1 day — is it the right shape?++### 1. Company attribution++```sql+SELECT+ count() AS total,+ countIf($group_0 != '') AS with_company,+ uniqIf($group_0, $group_0 != '') AS companies+FROM events+WHERE timestamp > now() - INTERVAL 1 DAY AND properties.work_event = true+```++**Pass:** `with_company = total`. **Fail:** any row without a group.++A work event with no company cannot be attributed to an account and is useless.+Every emit path sets `$groups`, so a gap here means a payload lost `companyId`.++### 2. Identity joins the browser person++```sql+SELECT count() AS server_events, uniq(distinct_id) AS ids,+ countIf(distinct_id LIKE 'company:%') AS anonymous+FROM events+WHERE timestamp > now() - INTERVAL 1 DAY AND properties.work_event = true+```++**Pass:** `anonymous` is small and confined to `quote_accepted` from the customer+portal. **Fail:** a large anonymous share.++Anonymous events mean `userId` arrived null. The browser calls+`posthog.identify(userId)`, so a server event keyed on the same id lands on the+same person with no merge; a null actor breaks per-user analysis for that event.++### 3. No duplicates++```sql+SELECT count() AS rows, uniq(uuid) AS distinct_uuids, count() - uniq(uuid) AS excess+FROM events+WHERE timestamp > now() - INTERVAL 1 DAY AND properties.work_event = true+```++**Pass:** `excess = 0`. **Investigate, do not panic, if not.**++PostHog de-duplicates on `uuid` only eventually, through background ClickHouse+merges, and its own docs say that is not guaranteed. A non-zero `excess` here is+therefore expected behaviour, not a bug — it is exactly why the id is+deterministic. What matters is that duplicates share a uuid so the warehouse can+collapse them. The failure case is `excess = 0` *with* inflated counts, which+would mean the same occurrence is minting different ids.++### 4. Payload hygiene++```sql+SELECT DISTINCT arrayJoin(JSONExtractKeys(properties)) AS key+FROM events+WHERE timestamp > now() - INTERVAL 1 DAY AND properties.work_event = true+ORDER BY key+```++**Pass:** ids, enums, counts, quantities, and PostHog's own `$`-prefixed keys.+**Fail:** any key holding money, a part number, an item description, a customer+or supplier name, or free text.++This is a standing check, not a one-off — it is what stops the payload drifting+into the sensitive territory the catalog deliberately excluded.++---++## T+3 days — does it agree with reality?++This is the check that catches the failure nobody notices: a number that is+plausible and wrong.++Pick two or three active accounts. For each, compare the event count against the+ERP's own data for the same window.++```sql+-- PostHog+SELECT $group_0 AS company, event, count() AS n+FROM events+WHERE timestamp > now() - INTERVAL 3 DAY AND properties.work_event = true+GROUP BY company, event ORDER BY company, n DESC+```++Then, against the Carbon database for the same company and window:++| Event | Compare against |+|---|---|+| `job_created` | `SELECT count(*) FROM "job" WHERE "companyId" = ? AND "createdAt" > ?` |+| `receipt_posted` | `SELECT count(*) FROM "receipt" WHERE "companyId" = ? AND status = 'Posted' AND "postingDate" >= ?` |+| `job_operation_started` | `SELECT count(*) FROM "productionEvent" WHERE "companyId" = ? AND "createdAt" > ?` |+| `production_quantity_reported` | `SELECT count(*) FROM "productionQuantity" WHERE "companyId" = ? AND type = 'Production' AND "createdAt" > ?` |++**Pass:** equal, or PostHog lower by a small margin.++**PostHog lower** is the expected direction and has three benign causes: a work+path this branch does not cover (see the gaps table in `README.md`), an event lost+to a transient network failure, or ingestion lag. Lower by a *lot* means a seam+was missed.++**PostHog higher** is never benign. It means one occurrence produced two ids, and+the idempotency key is wrong.++Mind two traps when comparing. The event timestamp is UTC while Carbon's business+dates are company-local, so a day boundary will disagree — compare over three+days, not one. And `job_created` counts every job including MRP-planned ones;+filter by `source` if the ERP query does not.++---++## Standing checks once it is trusted++- **Coverage:** which of the wired events have *never* been seen. An event that+ produces nothing in a month is either a seam that broke or a feature nobody+ uses; both are worth knowing and they look identical on a dashboard.+- **Volume:** PostHog drops events once a billing limit is exceeded **and still+ returns HTTP 200**. Nothing in the app can detect this. Current usage is around+ 218k events/month against a 1M free tier, so there is headroom, but a sudden+ flat-line across all events at once is the signature to watch for.+- **Batch export:** the mirror into Supabase has `filters: null`, so work events+ flow through automatically. If an event allow-list is ever set in the PostHog+ console, it lives there and not in git — a new event would silently never reach+ the warehouse.diff --git a/packages/lib/src/telemetry/capture.test.ts b/packages/lib/src/telemetry/capture.test.tsnew file mode 100644index 0000000000..99da12e19a--- /dev/null+++ b/packages/lib/src/telemetry/capture.test.ts@@ -0,0 +1,277 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const env = vi.hoisted(() => ({+ POSTHOG_API_HOST: "https://us.i.posthog.com",+ POSTHOG_PROJECT_PUBLIC_KEY: "phc_test",+ CONTROLLED_ENVIRONMENT: false+}));++vi.mock("@carbon/env", () => env);+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })+}));++const { captureWorkEvent, trackWorkEvent } = await import("./capture");++function lastRequest() {+ const mock = vi.mocked(globalThis.fetch);+ const [url, init] = mock.mock.calls.at(-1)!;+ return {+ url: String(url),+ body: JSON.parse(String((init as RequestInit).body))+ };+}++describe("captureWorkEvent", () => {+ beforeEach(() => {+ env.POSTHOG_API_HOST = "https://us.i.posthog.com";+ env.POSTHOG_PROJECT_PUBLIC_KEY = "phc_test";+ env.CONTROLLED_ENVIRONMENT = false;+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("ok", { status: 200 }))+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ const released = {+ companyId: "co_1",+ userId: "user_1",+ jobId: "job_1",+ priorStatus: "Draft",+ source: "erp" as const+ };++ it("posts to the same path posthog-js ingests through", async () => {+ await captureWorkEvent("job_released", released);+ expect(lastRequest().url).toBe("https://us.i.posthog.com/e/");+ });++ it("preserves a base path, so a reverse-proxied host still resolves", async () => {+ // new URL("/e/", "https://proxy/ingest") would silently drop "/ingest" and+ // send every event to a 404 that capture can never report.+ env.POSTHOG_API_HOST = "https://proxy.example.com/ingest";+ await captureWorkEvent("job_released", released);+ expect(lastRequest().url).toBe("https://proxy.example.com/ingest/e/");+ });++ it("does not double the separator when the host has a trailing slash", async () => {+ env.POSTHOG_API_HOST = "https://us.i.posthog.com/";+ await captureWorkEvent("job_released", released);+ expect(lastRequest().url).toBe("https://us.i.posthog.com/e/");+ });++ it("sends the event name, the project key and the actor as distinct_id", async () => {+ await captureWorkEvent("job_released", released);+ const { body } = lastRequest();+ expect(body.event).toBe("job_released");+ expect(body.api_key).toBe("phc_test");+ expect(body.distinct_id).toBe("user_1");+ });++ it("attributes the event to the company group", async () => {+ await captureWorkEvent("job_released", released);+ expect(lastRequest().body.properties.$groups).toEqual({+ company: "co_1"+ });+ });++ it("tags the module so adoption can be grouped by area", async () => {+ await captureWorkEvent("job_released", released);+ const { properties } = lastRequest().body;+ expect(properties.module).toBe("production");+ expect(properties.work_event).toBe(true);+ });++ it("carries a stable uuid, so a retry of one occurrence collapses", async () => {+ const first = await captureWorkEvent("job_released", released);+ const second = await captureWorkEvent("job_released", released);+ expect(first).toEqual(second);+ expect(first.sent && first.eventId).toBeTruthy();+ });++ it("gives a different uuid to a different job", async () => {+ const first = await captureWorkEvent("job_released", released);+ const second = await captureWorkEvent("job_released", {+ ...released,+ jobId: "job_2"+ });+ expect(first).not.toEqual(second);+ });++ // Both of these are regressions. Keyed on the document alone, the second+ // event of a lifecycle carries the same uuid as the first and is discarded+ // downstream — so the order that reached an approver was counted and the one+ // that actually committed money was not.+ it("separates the two stages of one purchase order", async () => {+ const base = {+ companyId: "co_1",+ userId: "user_1",+ purchaseOrderId: "po_1"+ };+ const gated = await captureWorkEvent(+ "purchase_order_finalized",+ { ...base, stage: "gated" },+ { discriminator: "gated" }+ );+ const committed = await captureWorkEvent(+ "purchase_order_finalized",+ { ...base, stage: "committed" },+ { discriminator: "committed" }+ );+ expect(gated.sent && committed.sent).toBe(true);+ expect((gated as { eventId: string }).eventId).not.toEqual(+ (committed as { eventId: string }).eventId+ );+ });++ it("still collapses a repeat of the same stage", async () => {+ const payload = {+ companyId: "co_1",+ userId: "user_1",+ purchaseOrderId: "po_1",+ stage: "committed" as const+ };+ const first = await captureWorkEvent("purchase_order_finalized", payload, {+ discriminator: "committed"+ });+ const again = await captureWorkEvent("purchase_order_finalized", payload, {+ discriminator: "committed"+ });+ expect(first).toEqual(again);+ });++ it("separates a picking list that goes Partial and then Completed", async () => {+ const base = {+ companyId: "co_1",+ userId: "user_1",+ pickingListId: "pl_1",+ source: "mes" as const+ };+ const partial = await captureWorkEvent(+ "picking_list_completed",+ { ...base, finalStatus: "Partial" },+ { discriminator: "Partial" }+ );+ const completed = await captureWorkEvent(+ "picking_list_completed",+ { ...base, finalStatus: "Completed" },+ { discriminator: "Completed" }+ );+ expect((partial as { eventId: string }).eventId).not.toEqual(+ (completed as { eventId: string }).eventId+ );+ });++ it("separates two postings against the same operation", async () => {+ const base = {+ companyId: "co_1",+ userId: "user_1",+ jobOperationId: "op_1",+ quantity: 5,+ source: "mes" as const+ };+ const first = await captureWorkEvent("production_quantity_reported", {+ ...base,+ productionQuantityId: "pq_1"+ });+ const second = await captureWorkEvent("production_quantity_reported", {+ ...base,+ productionQuantityId: "pq_2"+ });+ expect(first).not.toEqual(second);+ });++ it("keeps companyId out of the payload spread but present as a property", async () => {+ await captureWorkEvent("job_released", released);+ const { properties } = lastRequest().body;+ expect(properties.companyId).toBe("co_1");+ // userId is carried by distinct_id, not duplicated into properties.+ expect(properties.userId).toBeUndefined();+ });++ describe("when there is no actor", () => {+ const portal = {+ companyId: "co_1",+ userId: null,+ quoteId: "quote_1",+ salesOrderId: "so_1",+ acceptedBy: "portal" as const+ };++ it("falls back to a company-scoped distinct_id", async () => {+ await captureWorkEvent("quote_accepted", portal);+ expect(lastRequest().body.distinct_id).toBe("company:co_1");+ });++ it("turns off person processing, per PostHog's guidance on catch-all ids", async () => {+ await captureWorkEvent("quote_accepted", portal);+ expect(lastRequest().body.properties.$process_person_profile).toBe(false);+ });+ });++ describe("gating", () => {+ it("sends nothing when no api host is configured", async () => {+ env.POSTHOG_API_HOST = "";+ const result = await captureWorkEvent("job_released", released);+ expect(result).toEqual({ sent: false, reason: "disabled" });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it("sends nothing when no project key is configured", async () => {+ env.POSTHOG_PROJECT_PUBLIC_KEY = "";+ const result = await captureWorkEvent("job_released", released);+ expect(result).toEqual({ sent: false, reason: "disabled" });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it("sends nothing from a controlled (ITAR) environment", async () => {+ env.CONTROLLED_ENVIRONMENT = true;+ const result = await captureWorkEvent("job_released", released);+ expect(result).toEqual({+ sent: false,+ reason: "controlled_environment"+ });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+ });++ describe("failure is never the caller's problem", () => {+ it("resolves rather than throwing when PostHog rejects the event", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("nope", { status: 400 }))+ );+ await expect(captureWorkEvent("job_released", released)).resolves.toEqual(+ { sent: false, reason: "failed" }+ );+ });++ it("resolves rather than throwing when the network fails", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new Error("ECONNREFUSED");+ })+ );+ await expect(captureWorkEvent("job_released", released)).resolves.toEqual(+ { sent: false, reason: "failed" }+ );+ });++ it("does not leave an unhandled rejection when fired and forgotten", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new Error("ECONNREFUSED");+ })+ );+ expect(() => trackWorkEvent("job_released", released)).not.toThrow();+ await new Promise((resolve) => setImmediate(resolve));+ });+ });+});diff --git a/packages/lib/src/telemetry/capture.ts b/packages/lib/src/telemetry/capture.tsnew file mode 100644index 0000000000..3e920f931e--- /dev/null+++ b/packages/lib/src/telemetry/capture.ts@@ -0,0 +1,217 @@+import {+ CONTROLLED_ENVIRONMENT,+ POSTHOG_API_HOST,+ POSTHOG_PROJECT_PUBLIC_KEY+} from "@carbon/env";+import { getLogger } from "@carbon/logger";+import {+ WORK_EVENT_MODULE,+ WORK_EVENT_RECORD_KEY,+ type WorkEventName,+ type WorkEvents+} from "./events";+import { workEventId } from "./idempotency";++const log = getLogger("lib", "telemetry");++/**+ * Server-side work-event capture.+ *+ * ## Why there is no SDK here+ *+ * `posthog-node` is not a dependency and does not need to be. Capture is a JSON+ * POST with an api_key, and the two things the SDK adds on top — batching and+ * retry — are the wrong shape for this: a work event is low-frequency, and a+ * retry without a stable id is how you double-count a released job. This mirrors+ * the decision already made for Inngest in+ * `packages/database/supabase/functions/lib/inngest.ts`, and the shape of+ * `packages/stripe/src/gtm-events.server.ts`, which POSTs product events to the+ * GTM endpoint the same way.+ *+ * ## Exactly-once+ *+ * Each event carries a `uuid` derived from (companyId, event, recordId,+ * discriminator) — see `./idempotency.ts`. PostHog's own de-duplication on that+ * field is eventual and documented as not guaranteed, so this id is what the+ * warehouse de-duplicates on downstream. Emitting the same occurrence twice is+ * therefore safe by construction, which is what lets every call site here be+ * fire-and-forget.+ *+ * ## When nothing is sent+ *+ * Both conditions mirror the browser SDK's own gate exactly — see+ * `apps/erp/app/entry.client.tsx:31`, `if (POSTHOG_PROJECT_PUBLIC_KEY &&+ * !CONTROLLED_ENVIRONMENT)`. Server capture must not be reachable anywhere the+ * browser's is not, or a deployment that believes it has analytics switched off+ * would start emitting business records.+ *+ * - No `POSTHOG_PROJECT_PUBLIC_KEY`. Self-hosted deployments set no PostHog+ * variables at all, so they stay silent.+ * - `CONTROLLED_ENVIRONMENT` is on. An ITAR deployment ships nothing about a+ * U.S.-Persons-only environment to a third-party vendor.+ */++/**+ * The capture endpoint.+ *+ * `/e/` rather than the documented `/i/v0/e/`, and string concatenation rather+ * than `new URL`, for the same reason: this is the exact host and path+ * `posthog-js` already ingests through, so it is the one combination proven+ * against whatever `POSTHOG_API_HOST` is actually set to in production. Two+ * traps this avoids —+ *+ * - `new URL("/i/v0/e/", host)` silently discards any base path, so a host of+ * `https://proxy.example.com/ingest` would resolve to+ * `https://proxy.example.com/i/v0/e/` and 404.+ * - `/i/v0/e/` is documented against the ingestion host (`us.i.posthog.com`),+ * while `.env.example:23` carries the app host (`us.posthog.com`).+ *+ * Either mistake loses every event silently: capture never throws, so the only+ * trace would be a log line. Getting this wrong is the single largest risk in+ * the whole path, which is why it copies a proven value instead of a documented+ * one.+ */+function captureUrl(): string {+ return `${(POSTHOG_API_HOST ?? "").replace(/\/+$/, "")}/e/`;+}++/** Abandon a capture rather than hold a request open behind it. */+const TIMEOUT_MS = 3_000;++export type CaptureResult =+ | { sent: true; eventId: string }+ | { sent: false; reason: "disabled" | "controlled_environment" | "failed" };++function isEnabled(): CaptureResult | null {+ // The host is as load-bearing as the key: without it the URL below would be+ // a bare "/e/", which fetch rejects. Treat it as not configured rather than+ // as an error on every write.+ if (!POSTHOG_PROJECT_PUBLIC_KEY || !POSTHOG_API_HOST)+ return { sent: false, reason: "disabled" };+ if (CONTROLLED_ENVIRONMENT)+ return { sent: false, reason: "controlled_environment" };+ return null;+}++/**+ * Record that a piece of work happened.+ *+ * Never throws and never rejects: a failed capture must not fail the action that+ * produced it. Callers may leave the promise unawaited.+ *+ * @param event the work that happened+ * @param payload its properties — ids, enums, counts and quantities only+ * @param options `discriminator` distinguishes repeat work on one record, so a+ * second production quantity against the same operation is not+ * mistaken for a retry of the first+ */+export async function captureWorkEvent<E extends WorkEventName>(+ event: E,+ payload: WorkEvents[E],+ options?: { discriminator?: string | number | null }+): Promise<CaptureResult> {+ try {+ const disabled = isEnabled();+ if (disabled) return disabled;++ const { companyId, userId, ...properties } = payload;++ const recordId = String(+ (payload as Record<string, unknown>)[+ WORK_EVENT_RECORD_KEY[event] as string+ ] ?? ""+ );++ const eventId = workEventId({+ event,+ companyId,+ recordId,+ discriminator: options?.discriminator+ });++ // PostHog warns against a shared "backend" distinct_id: it rate-limits the+ // stream and bills every event as identified. A company-scoped id with+ // person processing off is their recommended shape for actorless events.+ // https://posthog.com/docs/product-analytics/identity-resolution+ const anonymous = !userId;++ const body = {+ api_key: POSTHOG_PROJECT_PUBLIC_KEY,+ event,+ // The browser calls posthog.identify(userId), so a server event keyed on+ // the same id lands on the same person with no merge.+ distinct_id: userId ?? `company:${companyId}`,+ uuid: eventId,+ timestamp: new Date().toISOString(),+ properties: {+ ...properties,+ companyId,+ module: WORK_EVENT_MODULE[event],+ /** Marks the row as a business fact rather than browser telemetry. */+ work_event: true,+ /** Attribution to the company group; does not create the group. */+ $groups: { company: companyId },+ ...(anonymous ? { $process_person_profile: false } : {})+ }+ };++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);++ try {+ const res = await fetch(captureUrl(), {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ signal: controller.signal+ });++ if (!res.ok) {+ const text = await res.text().catch(() => "");+ log.error("work event rejected", {+ event,+ status: res.status,+ body: text.slice(0, 500)+ });+ return { sent: false, reason: "failed" };+ }++ return { sent: true, eventId };+ } finally {+ clearTimeout(timer);+ }+ } catch (err) {+ // Includes the abort. A lost measurement beats a failed action.+ log.error("work event failed", { event, err });+ return { sent: false, reason: "failed" };+ }+}++/**+ * Fire-and-forget form, for call sites that should not await telemetry.+ *+ * Prefer this everywhere in a request path. The returned promise is already+ * handled; ignoring it will not produce an unhandled rejection.+ */+export function trackWorkEvent<E extends WorkEventName>(+ event: E,+ payload: WorkEvents[E],+ options?: { discriminator?: string | number | null }+): void {+ void captureWorkEvent(event, payload, options);+}++export type {+ JobSource,+ WorkEventName,+ WorkEvents,+ WorkModule,+ WorkSource+} from "./events";+export {+ asJobSource,+ JOB_SOURCES,+ WORK_EVENT_MODULE,+ WORK_EVENT_NAMES+} from "./events";+export { workEventId } from "./idempotency";diff --git a/packages/lib/src/telemetry/events.ts b/packages/lib/src/telemetry/events.tsnew file mode 100644index 0000000000..ac03f1f0fb--- /dev/null+++ b/packages/lib/src/telemetry/events.ts@@ -0,0 +1,287 @@+/**+ * The work-done event catalog.+ *+ * "Work done" means a record was created, a state changed in a way that means+ * work happened, a quantity was recorded against reality, or something was sent+ * outward. Opening a screen is not work; neither is searching, filtering, or a+ * write that happens as a side effect of viewing a page.+ *+ * Every event here answers a question a plant manager or an operator would ask+ * by name. The full catalog these are drawn from, including the deferred waves+ * and the reasoning per event, lives in `adoption-tracking/work-done-events.md`+ * alongside this repo.+ *+ * ## What may go in a payload+ *+ * Ids, enum values, counts, and physical quantities. Nothing else.+ *+ * Deliberately excluded: monetary amounts, part numbers, item descriptions,+ * customer and supplier names, free text of any kind. Adoption is measured in+ * counts and elapsed time, so values add sensitivity without adding signal —+ * and Carbon sells to defense and aerospace accounts whose part numbers and+ * order values are the sensitive part. An id is resolvable against the+ * customer's own database when someone genuinely needs the detail.+ *+ * @see ./capture.ts for how these reach PostHog.+ */++/** The Carbon module a piece of work belongs to. Used to group adoption by area. */+export type WorkModule =+ | "production"+ | "inventory"+ | "sales"+ | "purchasing"+ | "invoicing";++/**+ * Which surface the work was entered from.+ *+ * This is the single most useful property in the catalog: it separates a shop+ * floor genuinely using the MES from a clerk typing yesterday's paper traveller+ * into the back office. Nothing else distinguishes those two, and they mean+ * completely different things about adoption.+ */+export type WorkSource = "erp" | "mes" | "mes_qr" | "api" | "portal";++/**+ * Where a job came from.+ *+ * A separate axis from `WorkSource`: every creation path funnels through one+ * service function and the `job` row itself cannot tell them apart, so the+ * caller has to say. The distinction is the difference between a shop planning+ * its work and a shop reacting to one.+ */+export const JOB_SOURCES = [+ "erp",+ "bulk",+ "mrp",+ "salesOrder",+ "kanban",+ "api",+ "workflow",+ /**+ * The caller did not say. Reaching `insertJob` without a source is normal —+ * the MCP tool and the workflow engine both dispatch `production_insertJob`+ * by name through a generic (call, context, inputs) signature that has+ * nowhere to put one. Defaulting those to `erp` would report automation as+ * human work, which is the single thing this field exists to separate.+ */+ "unknown"+] as const;++export type JobSource = (typeof JOB_SOURCES)[number];++/**+ * Narrow an untrusted value to a `JobSource`, falling back to `unknown`.+ *+ * `insertJob` is reachable as an MCP tool, and the generated tool schema types+ * this parameter as `{}` — the generator resolves inline unions but not an+ * imported alias — so nothing between a caller and the event enforces the set.+ * TypeScript is not a runtime guard here: without this, an agent passing+ * `source: "banana"` would put "banana" in the analytics enum permanently.+ */+export function asJobSource(value: unknown): JobSource {+ return JOB_SOURCES.includes(value as JobSource)+ ? (value as JobSource)+ : "unknown";+}++type Base = {+ companyId: string;+ /** Carbon `userId` of the actor. Null for service-role and customer-portal work. */+ userId: string | null;+};++/**+ * Every work event, with the properties it carries.+ *+ * Adding an entry here is the whole change on the emit side — `captureWorkEvent`+ * is typed off this map, so a name that is not in it will not compile, and a+ * payload missing a property will not either.+ */+export type WorkEvents = {+ // ------------------------------------------------------------- production+ job_created: Base & {+ jobId: string;+ itemId: string;+ quantity: number;+ scrapQuantity: number;+ locationId: string | null;+ /** Set when the job was raised to serve a specific sales order line. */+ salesOrderLineId: string | null;+ deadlineType: string | null;+ source: JobSource;+ };+ job_released: Base & {+ jobId: string;+ /** What the job was before. A re-save of an already-Ready job never emits. */+ priorStatus: string;+ /** `kanban` when a scan released it, so auto-releases stay separable. */+ source: JobSource;+ };+ job_operation_started: Base & {+ /**+ * The `productionEvent` row. An operator clocks on and off a step many+ * times, so the operation id would collapse a shift into one event — this+ * is what makes each clock-on its own occurrence.+ */+ productionEventId: string;+ jobOperationId: string;+ /** Setup, Labor or Machine. */+ eventType: string;+ source: WorkSource;+ };+ production_quantity_reported: Base & {+ /** The `productionQuantity` row — one posting, not one operation. */+ productionQuantityId: string;+ jobOperationId: string;+ quantity: number;+ /**+ * Which surface posted it. The ratio of `mes`/`mes_qr` to `erp` is the best+ * single measure of whether the shop floor app is genuinely in use or a+ * clerk is typing yesterday's paper traveller into the back office.+ */+ source: WorkSource;+ };+ job_operation_finished: Base & {+ jobOperationId: string;+ jobId: string;+ };+ job_completed: Base & {+ jobId: string;+ /** `manual` from the complete route; `auto` when the last operation closed it. */+ path: "manual" | "auto";+ };+ scrap_reported: Base & {+ /** The `productionQuantity` row carrying type 'Scrap'. */+ productionQuantityId: string;+ jobOperationId: string;+ quantity: number;+ scrapReasonId: string | null;+ source: WorkSource;+ };++ // -------------------------------------------------------------- inventory+ receipt_posted: Base & {+ receiptId: string;+ /** Purchase Order, Inbound Transfer, and so on. */+ sourceDocument: string | null;+ };+ shipment_posted: Base & {+ shipmentId: string;+ /** Sales Order, Purchase Order (outside processing), Outbound Transfer. */+ sourceDocument: string | null;+ };+ picking_list_completed: Base & {+ pickingListId: string;+ /** Completed, Partial or Cancelled. */+ finalStatus: string;+ /** `mes` when the floor closed it, `erp` when the office did. */+ source: WorkSource;+ };++ // ------------------------------------------------------------------ sales+ quote_sent: Base & {+ quoteId: string;+ };+ quote_accepted: Base & {+ quoteId: string;+ salesOrderId: string;+ /** `portal` means the customer accepted it themselves, with no Carbon user. */+ acceptedBy: "internal" | "portal";+ };+ sales_order_confirmed: Base & {+ salesOrderId: string;+ lineCount: number;+ /** The status the line mix derived — To Ship and Invoice, and so on. */+ derivedStatus: string;+ emailed: boolean;+ };++ // ------------------------------------------------------------- purchasing+ purchase_order_finalized: Base & {+ purchaseOrderId: string;+ /**+ * Where the order got to, and the discriminator — one `gated` and one+ * `committed` event per order, never two of either.+ *+ * `gated`: the finalize stopped at an approval threshold. Nothing is owed+ * to the supplier yet, so this must never be counted as spend.+ * `committed`: the order is live. Reached either directly, when no+ * threshold applied, or later from `approveRequest` when an approver+ * released a gated one — a different module, which is why a single emit on+ * the finalize route left approved orders uncounted entirely.+ *+ * "POs issued this week" is `stage = committed`.+ */+ stage: "gated" | "committed";+ };++ // --------------------------------------------------------------- invoicing+ sales_invoice_posted: Base & {+ salesInvoiceId: string;+ };+ purchase_invoice_posted: Base & {+ purchaseInvoiceId: string;+ };+};++export type WorkEventName = keyof WorkEvents;++/** Which module each event belongs to, for grouping adoption by area. */+export const WORK_EVENT_MODULE: Record<WorkEventName, WorkModule> = {+ job_created: "production",+ job_released: "production",+ job_operation_started: "production",+ production_quantity_reported: "production",+ job_operation_finished: "production",+ job_completed: "production",+ scrap_reported: "production",+ receipt_posted: "inventory",+ shipment_posted: "inventory",+ picking_list_completed: "inventory",+ quote_sent: "sales",+ quote_accepted: "sales",+ sales_order_confirmed: "sales",+ purchase_order_finalized: "purchasing",+ sales_invoice_posted: "invoicing",+ purchase_invoice_posted: "invoicing"+};++export const WORK_EVENT_NAMES = Object.keys(+ WORK_EVENT_MODULE+) as WorkEventName[];++/** The payload keys of one event that hold a string id. */+type IdKeyOf<E extends WorkEventName> = {+ [K in keyof WorkEvents[E]]: WorkEvents[E][K] extends string ? K : never;+}[keyof WorkEvents[E]];++/**+ * The record whose id makes an occurrence unique, per event.+ *+ * Used to build the idempotency key, so a retry collapses instead of counting+ * twice. Where an event can legitimately recur against one record — a second+ * production quantity on the same operation — the emit site supplies a+ * discriminator as well.+ */+export const WORK_EVENT_RECORD_KEY: {+ [E in WorkEventName]: IdKeyOf<E>;+} = {+ job_created: "jobId",+ job_released: "jobId",+ job_operation_started: "productionEventId",+ production_quantity_reported: "productionQuantityId",+ job_operation_finished: "jobOperationId",+ job_completed: "jobId",+ scrap_reported: "productionQuantityId",+ receipt_posted: "receiptId",+ shipment_posted: "shipmentId",+ picking_list_completed: "pickingListId",+ quote_sent: "quoteId",+ quote_accepted: "quoteId",+ sales_order_confirmed: "salesOrderId",+ purchase_order_finalized: "purchaseOrderId",+ sales_invoice_posted: "salesInvoiceId",+ purchase_invoice_posted: "purchaseInvoiceId"+};diff --git a/packages/lib/src/telemetry/idempotency.test.ts b/packages/lib/src/telemetry/idempotency.test.tsnew file mode 100644index 0000000000..a326c82ee7--- /dev/null+++ b/packages/lib/src/telemetry/idempotency.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";+import { asJobSource, JOB_SOURCES } from "./events";+import { __testing, workEventId } from "./idempotency";++describe("workEventId", () => {+ const occurrence = {+ event: "job_released",+ companyId: "co_1",+ recordId: "job_1"+ };++ it("is stable across calls, which is what makes a retry safe", () => {+ expect(workEventId(occurrence)).toBe(workEventId(occurrence));+ });++ it("is a syntactically valid v5 UUID", () => {+ expect(workEventId(occurrence)).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/+ );+ });++ it("separates companies, so one tenant cannot collide with another", () => {+ expect(workEventId(occurrence)).not.toBe(+ workEventId({ ...occurrence, companyId: "co_2" })+ );+ });++ it("separates events on the same record", () => {+ expect(workEventId(occurrence)).not.toBe(+ workEventId({ ...occurrence, event: "job_completed" })+ );+ });++ it("separates records", () => {+ expect(workEventId(occurrence)).not.toBe(+ workEventId({ ...occurrence, recordId: "job_2" })+ );+ });++ it("treats an omitted, null and undefined discriminator as the same occurrence", () => {+ const base = workEventId(occurrence);+ expect(workEventId({ ...occurrence, discriminator: null })).toBe(base);+ expect(workEventId({ ...occurrence, discriminator: undefined })).toBe(base);+ });++ it("separates repeat work on one record when a discriminator is given", () => {+ const first = workEventId({ ...occurrence, discriminator: 1 });+ const second = workEventId({ ...occurrence, discriminator: 2 });+ expect(first).not.toBe(second);+ });++ it("does not let a discriminator forge a different record", () => {+ // "job_1" + "2" must not equal "job_12" + "" — the separator prevents it.+ expect(workEventId({ ...occurrence, discriminator: "2" })).not.toBe(+ workEventId({ ...occurrence, recordId: "job_12" })+ );+ });++ it("computes SHA-1 correctly against the standard vectors", () => {+ const hash = (text: string) =>+ __testing.toHex(__testing.sha1(new TextEncoder().encode(text)));+ expect(hash("")).toBe("da39a3ee5e6b4b0d3255bfef95601890afd80709");+ expect(hash("abc")).toBe("a9993e364706816aba3e25717850c26c9cd0d89d");+ expect(+ hash("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")+ ).toBe("84983e441c3bd26ebaae4aa1f95129e5e54670f1");+ // Multi-block: crosses the 64-byte boundary and exercises the length field.+ expect(hash("a".repeat(1000))).toBe(+ "291e9a6c66994949b57ba5e650361e98fc36b1ba"+ );+ });++ it("matches the RFC 4122 §A worked example, so the hash is a real v5", () => {+ // The canonical DNS namespace and name from the RFC's own test vector.+ expect(+ __testing.uuidv5(+ "www.example.org",+ "6ba7b810-9dad-11d1-80b4-00c04fd430c8"+ )+ ).toBe("74738ff5-5367-5958-9aee-98fffdcd1876");+ });+});++describe("asJobSource", () => {+ it("passes a real source through", () => {+ expect(asJobSource("kanban")).toBe("kanban");+ });++ // insertJob is an MCP tool and the generated schema types this field as {},+ // so an agent can send anything. Without narrowing it lands in the analytics+ // enum permanently.+ it("narrows anything else to unknown", () => {+ for (const bad of ["banana", "", null, undefined, 7, {}, ["erp"]]) {+ expect(asJobSource(bad)).toBe("unknown");+ }+ });++ it("keeps the runtime list and the type in step", () => {+ // A source added to the union but not the array would silently narrow to+ // "unknown" at runtime; deriving the type from the array makes that+ // impossible, and this pins the array itself.+ expect([...JOB_SOURCES]).toEqual([+ "erp",+ "bulk",+ "mrp",+ "salesOrder",+ "kanban",+ "api",+ "workflow",+ "unknown"+ ]);+ });+});diff --git a/packages/lib/src/telemetry/idempotency.ts b/packages/lib/src/telemetry/idempotency.tsnew file mode 100644index 0000000000..a438e8f9d2--- /dev/null+++ b/packages/lib/src/telemetry/idempotency.ts@@ -0,0 +1,174 @@+/**+ * Namespace for Carbon work-event ids. A fixed random UUID, per RFC 4122 §4.3 —+ * it only has to be constant, not secret.+ */+const CARBON_WORK_EVENT_NAMESPACE = "6f9c1f1a-3d3e-4a1e-9a4b-2c8f5b7e0d21";++/**+ * SHA-1, in plain TypeScript.+ *+ * Not `node:crypto`: the emit sites live in service files that React components+ * import for their types and enums, so this module lands in the client graph+ * even though every caller is server-side. A Node built-in there breaks the+ * browser bundle, and `crypto.subtle` is async, which would make every capture+ * site await a hash. Forty lines and one RFC test vector is the cheaper trade.+ *+ * SHA-1 is broken for signatures. This is a namespacing hash, never a security+ * boundary — RFC 4122 v5 specifies exactly this.+ */+function sha1(message: Uint8Array): Uint8Array {+ let h0 = 0x67452301;+ let h1 = 0xefcdab89;+ let h2 = 0x98badcfe;+ let h3 = 0x10325476;+ let h4 = 0xc3d2e1f0;++ const bitLength = message.length * 8;+ // One byte for the 0x80 terminator plus eight for the length, rounded up to+ // a whole 64-byte block.+ const paddedLength = Math.ceil((message.length + 9) / 64) * 64;+ const block = new Uint8Array(paddedLength);+ block.set(message);+ block[message.length] = 0x80;++ const view = new DataView(block.buffer);+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 0x100000000), false);+ view.setUint32(paddedLength - 4, bitLength >>> 0, false);++ const w = new Uint32Array(80);++ for (let offset = 0; offset < paddedLength; offset += 64) {+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);+ for (let i = 16; i < 80; i++) {+ const x = w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!;+ w[i] = ((x << 1) | (x >>> 31)) >>> 0;+ }++ let a = h0;+ let b = h1;+ let c = h2;+ let d = h3;+ let e = h4;++ for (let i = 0; i < 80; i++) {+ let f: number;+ let k: number;+ if (i < 20) {+ f = (b & c) | (~b & d);+ k = 0x5a827999;+ } else if (i < 40) {+ f = b ^ c ^ d;+ k = 0x6ed9eba1;+ } else if (i < 60) {+ f = (b & c) | (b & d) | (c & d);+ k = 0x8f1bbcdc;+ } else {+ f = b ^ c ^ d;+ k = 0xca62c1d6;+ }++ const temp =+ ((((a << 5) | (a >>> 27)) >>> 0) + (f >>> 0) + e + k + w[i]!) >>> 0;+ e = d;+ d = c;+ c = ((b << 30) | (b >>> 2)) >>> 0;+ b = a;+ a = temp;+ }++ h0 = (h0 + a) >>> 0;+ h1 = (h1 + b) >>> 0;+ h2 = (h2 + c) >>> 0;+ h3 = (h3 + d) >>> 0;+ h4 = (h4 + e) >>> 0;+ }++ const digest = new Uint8Array(20);+ const digestView = new DataView(digest.buffer);+ digestView.setUint32(0, h0, false);+ digestView.setUint32(4, h1, false);+ digestView.setUint32(8, h2, false);+ digestView.setUint32(12, h3, false);+ digestView.setUint32(16, h4, false);+ return digest;+}++function uuidToBytes(uuid: string): Uint8Array {+ const hex = uuid.replace(/-/g, "");+ const bytes = new Uint8Array(16);+ for (let i = 0; i < 16; i++) {+ bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);+ }+ return bytes;+}++function toHex(bytes: Uint8Array): string {+ let out = "";+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");+ return out;+}++/** RFC 4122 v5 (SHA-1, name-based). `uuid` is not in the workspace. */+function uuidv5(name: string, namespace: string): string {+ const namespaceBytes = uuidToBytes(namespace);+ const nameBytes = new TextEncoder().encode(name);++ const input = new Uint8Array(namespaceBytes.length + nameBytes.length);+ input.set(namespaceBytes);+ input.set(nameBytes, namespaceBytes.length);++ const bytes = sha1(input).slice(0, 16);+ // Version 5.+ bytes[6] = ((bytes[6]! & 0x0f) | 0x50) >>> 0;+ // RFC 4122 variant.+ bytes[8] = ((bytes[8]! & 0x3f) | 0x80) >>> 0;++ const hex = toHex(bytes);+ return [+ hex.slice(0, 8),+ hex.slice(8, 12),+ hex.slice(12, 16),+ hex.slice(16, 20),+ hex.slice(20, 32)+ ].join("-");+}++/**+ * A stable event id for one real business occurrence.+ *+ * The same occurrence emitted twice — a retried request, a replayed Inngest+ * step, a double-clicked Post button — produces the same uuid, so the duplicate+ * collapses instead of inflating a count.+ *+ * PostHog's own de-duplication on `uuid` is eventual and explicitly not+ * guaranteed (https://posthog.com/docs/data/ingestion-warnings), so this id is+ * what the downstream warehouse de-duplicates on. Treat it as the primary key+ * of the occurrence, not as a hint.+ *+ * `parts` must be drawn only from values that are already fixed at the moment+ * the work happened. Never include a clock reading, a random id, or a value the+ * user can edit afterwards — any of those defeat the whole mechanism.+ */+export function workEventId(parts: {+ event: string;+ companyId: string;+ /** Primary key of the record the work happened to. */+ recordId: string;+ /**+ * Distinguishes repeatable work on one record — a line number, a sequence, a+ * target status. Omit when the event can only truly happen once per record.+ */+ discriminator?: string | number | null;+}): string {+ const discriminator =+ parts.discriminator === undefined || parts.discriminator === null+ ? ""+ : String(parts.discriminator);++ return uuidv5(+ [parts.companyId, parts.event, parts.recordId, discriminator].join(" "),+ CARBON_WORK_EVENT_NAMESPACE+ );+}++export const __testing = { uuidv5, sha1, toHex, CARBON_WORK_EVENT_NAMESPACE };diff --git a/packages/lib/vitest.config.ts b/packages/lib/vitest.config.tsnew file mode 100644index 0000000000..9a3c27eaed--- /dev/null+++ b/packages/lib/vitest.config.ts@@ -0,0 +1 @@+export { default } from "@carbon/config/vitest";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5b3c0fb93a..6d3422e9b5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -6,15 +6,237 @@ 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@@ -27,9 +249,36 @@ 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@@ -61,7 +310,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@@ -98,7 +347,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@@ -149,7 +398,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@@ -2475,6 +2724,9 @@ importers:typescript:specifier: 'catalog:'version: 5.8.3+ 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]))packages/locale:dependencies:@@ -11561,9 +11813,6 @@ packages:resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}- resolution: {integrity: sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==}-resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==}@@ -16928,7 +17177,7 @@ snapshots:'@babel/types': 7.29.0'@jridgewell/remapping': 2.3.5convert-source-map: 2.0.0- debug: 4.4.3+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17111,7 +17360,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -21862,7 +22111,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@@ -21892,7 +22141,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])@@ -21984,9 +22233,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])':+ '@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@@ -23108,7 +23357,7 @@ snapshots:'@types/phoenix': 1.6.7'@types/ws': 8.18.1tslib: 2.8.1- ws: 8.20.0+ ws: 8.21.0transitivePeerDependencies:- bufferutil- utf-8-validate@@ -23139,7 +23388,7 @@ snapshots:'@tailwindcss/[email protected]':dependencies:'@jridgewell/remapping': 2.3.5- enhanced-resolve: 5.21.6+ enhanced-resolve: 5.24.2jiti: 2.7.0lightningcss: 1.32.0magic-string: 0.30.21@@ -24252,6 +24501,14 @@ snapshots:optionalDependencies:vite: 7.3.2(@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@@ -25430,10 +25687,6 @@ snapshots:dependencies:ms: 2.1.3- dependencies:- ms: 2.1.3-dependencies:ms: 2.1.3@@ -25753,8 +26006,6 @@ snapshots:- [email protected]: {}-@@ -28108,7 +28359,7 @@ snapshots:dependencies:'@types/debug': 4.1.13- debug: 4.4.3+ debug: 4.4.3([email protected])decode-named-character-reference: 1.3.0devlop: 1.1.0micromark-core-commonmark: 2.0.3@@ -31140,14 +31391,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])+ vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -31213,7 +31464,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@@ -31222,14 +31473,14 @@ snapshots:tinyglobby: 0.2.17optionalDependencies:'@types/node': 20.19.39- 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@@ -31237,7 +31488,7 @@ snapshots:rolldown: 1.0.0-rc.17tinyglobby: 0.2.17optionalDependencies:- '@types/node': 22.19.7+ '@types/node': 20.19.39esbuild: 0.28.0fsevents: 2.3.3jiti: 2.7.0@@ -31245,7 +31496,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@@ -31253,8 +31504,8 @@ snapshots:rolldown: 1.0.0-rc.17tinyglobby: 0.2.17optionalDependencies:- '@types/node': 24.12.2- esbuild: 0.27.7+ '@types/node': 22.19.7+ esbuild: 0.28.0fsevents: 2.3.3jiti: 2.7.0terser: 5.48.0@@ -31318,7 +31569,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1@@ -31337,6 +31588,34 @@ 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.3.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': 20.19.39+ 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@@ -31346,7 +31625,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1@@ -31374,7 +31653,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1@@ -31402,7 +31681,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1@@ -31430,7 +31709,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1@@ -31458,7 +31737,7 @@ snapshots:'@vitest/snapshot': 4.1.6'@vitest/spy': 4.1.6'@vitest/utils': 4.1.6- es-module-lexer: 2.0.0+ es-module-lexer: 2.3.0expect-type: 1.3.0magic-string: 0.30.21obug: 2.1.1