Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(checks): fail CI when a document counter is not kept ahead of saved numbers

aashu4135344aa400
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 7e0c953164..3dc1eac317 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3363,3 +3363,13 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Rule:** Never put an import attribute on a JSON import in code that also runs in the browser. Make the server bundle the package instead: add it to `ssrNoExternal` in each app's `vite.config.ts` (the ERP and MES lists apply to both `ssr.noExternal` and `environments.ssr.resolve.noExternal`). To check the browser side, fetch the module from the dev server (`curl $ERP_URL/@fs<absolute path>`) and confirm the `import()` call has no second argument.
**Applies to:** `packages/react/src/utils/generatedAvatar.ts`; any isomorphic code that imports JSON from a dependency.
+
+## A caller-supplied document number used to leave the counter behind
+
+**Context:** Documents take their number from `get_next_sequence` unless the caller supplies one: a custom ID typed into `SequenceOrCustomId`, or an MCP / API upsert (`upsertSalesOrder`, `upsertQuote`, `upsertPurchaseOrder`, `upsertJob`, …) whose create path requires the number.
+
+**Problem:** A supplied number never moved the `sequence` row. Once the counter reached a number an agent or a user had already used, every new document failed on the unique constraint ("Failed to insert sales order") until someone moved the counter by hand.
+
+**Rule:** The counter is kept ahead in the database, not in app code: the `sync_advance_document_sequence` after-interceptor moves `sequence.next` past any number saved in the sequence's format, on insert and on a number change. A new numbered table must be added to that interceptor's `CASE` and given the interceptor in `attachments.ts`; the `document-sequence-synced` conformance check fails CI for a new counter that is neither covered nor in its `EXEMPT_COUNTERS`. Never "fix" a collision by retrying `get_next_sequence`.
+
+**Applies to:** `packages/database/src/event-system/handlers/sync_advance_document_sequence.sql`, `util.document_sequence_pattern`, any table with a readable document number.
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 8b75b743ff..a47f12eeb8 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -43,6 +43,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requireCaller` / `requireServiceRole` — the gates each self-contained function defines for itself; a declaration alone does not count — because `verify_jwt` accepts the published anon key
- **Server-function shape** (`SERVER_FN_CHECKS`): `serverFnAuthorizesCaller` (`server-fn-authorizes-caller`) fails any `packages/server-functions/src/<name>/index.ts` not built with `defineServerFn`, whose required `permissions` field declares what the caller needs.
- **License headers** (own source, `sources/license-files.ts`: git-tracked `.ts/.tsx/.js/.jsx/.mjs/.cjs/.rs` under `apps`, `packages`, `crates`, `docs`, `ci`, `scripts` and the repo root): `spdxLicenseHeader` fails a file whose first lines are not its SPDX header — `AGPL-3.0-only`, or `LicenseRef-Carbon-Commercial` under `packages/ee/` and for any `.ee.` file name. The header text, the classification, the exclusions (each with its reason: generated files a generator would clobber — `generate:types`, `generate:swagger`, the workflow catalog, `sst-env.d.ts`, the notification preview fixtures — and third-party copies) and the insertion rules live in ONE module, `src/license-headers.ts`, shared with the fixer `pnpm --filter @carbon/checks license-headers` (`--check`, `--dry-run`, `--verbose`, optional paths; root alias `pnpm license:headers`), so the check fails exactly the files the fixer would change. The header goes after a shebang and above everything else (`"use client"`, `// @ts-nocheck`, `/// <reference>`, `biome-ignore-all`, `deno-lint-ignore-file`, Rust `//!`/`#![…]` all stay valid after a comment), then one blank line; the other license's header is swapped, CRLF is kept. A file with a third-party notice (foreign SPDX id, `@license`, copyright) is flagged and never rewritten — add it to `PATH_EXCLUSIONS`. When the header wording changes, move the old lines to `RETIRED_HEADER_LINES`. No baseline entries
+- **Document sequences** (built in `collectFindings`, cross-file): `findUnsyncedDocumentSequences` (`document-sequence-synced`, sources loaded by `sources/document-sequences.ts`) fails a counter in `packages/database/src/seed-data.ts` `sequences` whose table is not both attached to `sync_advance_document_sequence` in `attachments.ts` and named in that interceptor's `CASE`, unless `EXEMPT_COUNTERS` lists it with the reason no caller ever supplies its number. It also fails a table that is attached but missing from the `CASE`, or the reverse. Without the interceptor, a number typed by hand or sent through MCP/the API leaves the counter behind and later inserts fail on the unique constraint. `COUNTER_TABLES` maps counters named differently from their table (`journalEntry` → `journal`, `creditMemo`/`debitMemo` → `memo`). No baseline entries
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + snippet` (no line number, so edits above a baselined hit don't un-baseline it)
diff --git a/packages/checks/src/conformance/document-sequence-synced.test.ts b/packages/checks/src/conformance/document-sequence-synced.test.ts
new file mode 100644
index 0000000000..818f7d833d
--- /dev/null
+++ b/packages/checks/src/conformance/document-sequence-synced.test.ts
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { findUnsyncedDocumentSequences } from "./document-sequence-synced";
+
+const seedData = (...tables: string[]) => ({
+ file: "seed-data.ts",
+ contents: `export const sequences = [\n${tables
+ .map((t) => ` {\n table: "${t}",\n prefix: "X"\n },`)
+ .join("\n")}\n] as const;\n`
+});
+
+const attachments = (...tables: string[]) => ({
+ file: "attachments.ts",
+ contents: `export const attachments = {\n${tables
+ .map(
+ (t) =>
+ ` ${t}: { after: ["sync_advance_document_sequence"], events: true },`
+ )
+ .join("\n")}\n other: { events: true }\n} as const;\n`
+});
+
+const interceptor = (...tables: string[]) => ({
+ file: "sync_advance_document_sequence.sql",
+ contents: `v_column := CASE p_table\n${tables
+ .map((t) => ` WHEN '${t}' THEN '${t}Id'`)
+ .join("\n")}\n END;\n`
+});
+
+const messages = (
+ sources: Parameters<typeof findUnsyncedDocumentSequences>[0]
+) =>
+ findUnsyncedDocumentSequences(sources).map((v) => `${v.file}: ${v.snippet}`);
+
+describe("findUnsyncedDocumentSequences", () => {
+ it("accepts a counter whose table is attached and in the CASE", () => {
+ expect(
+ messages({
+ seedData: seedData("salesOrder"),
+ attachments: attachments("salesOrder"),
+ interceptor: interceptor("salesOrder")
+ })
+ ).toEqual([]);
+ });
+
+ it("flags a new counter that is neither covered nor exempt", () => {
+ expect(
+ messages({
+ seedData: seedData("salesOrder", "serviceOrder"),
+ attachments: attachments("salesOrder"),
+ interceptor: interceptor("salesOrder")
+ })
+ ).toEqual(['seed-data.ts: table: "serviceOrder"']);
+ });
+
+ it("accepts an exempt counter, and flags one that is also covered", () => {
+ expect(
+ messages({
+ seedData: seedData("inspection"),
+ attachments: attachments(),
+ interceptor: interceptor()
+ })
+ ).toEqual([]);
+ expect(
+ messages({
+ seedData: seedData("inspection"),
+ attachments: attachments("inspection"),
+ interceptor: interceptor("inspection")
+ })
+ ).toEqual(['seed-data.ts: table: "inspection"']);
+ });
+
+ it("maps counters named differently from their table", () => {
+ expect(
+ messages({
+ seedData: seedData("journalEntry", "creditMemo", "debitMemo"),
+ attachments: attachments("journal", "memo"),
+ interceptor: interceptor("journal", "memo")
+ })
+ ).toEqual([]);
+ });
+
+ it("flags a table attached but missing from the CASE, and the reverse", () => {
+ expect(
+ messages({
+ seedData: seedData(),
+ attachments: attachments("quote"),
+ interceptor: interceptor("job")
+ })
+ ).toEqual([
+ "attachments.ts: quote",
+ "sync_advance_document_sequence.sql: WHEN 'job'"
+ ]);
+ });
+});
diff --git a/packages/checks/src/conformance/document-sequence-synced.ts b/packages/checks/src/conformance/document-sequence-synced.ts
new file mode 100644
index 0000000000..b7980a4f2d
--- /dev/null
+++ b/packages/checks/src/conformance/document-sequence-synced.ts
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { SourceFile, Violation } from "../check";
+
+export const DOCUMENT_SEQUENCE_SYNCED = "document-sequence-synced";
+
+export const SEED_DATA_FILE = "packages/database/src/seed-data.ts";
+export const ATTACHMENTS_FILE =
+ "packages/database/src/event-system/attachments.ts";
+export const INTERCEPTOR_FILE =
+ "packages/database/src/event-system/handlers/sync_advance_document_sequence.sql";
+
+const INTERCEPTOR = "sync_advance_document_sequence";
+
+/** A counter named differently from the table whose numbers it issues. */
+const COUNTER_TABLES: Record<string, string> = {
+ journalEntry: "journal",
+ creditMemo: "memo",
+ debitMemo: "memo"
+};
+
+/**
+ * Counters whose numbers only ever come from get_next_sequence / getNextSequence:
+ * no form, MCP tool or API write takes the number from the caller (checked
+ * 2026-10-09). Everything else must be kept ahead of saved numbers by the
+ * interceptor, or a caller-chosen number leaves the counter behind and later
+ * inserts fail on the unique constraint.
+ */
+export const EXEMPT_COUNTERS: Record<string, string> = {
+ charge: "no form or API write takes chargeId",
+ fixedAssetTransfer:
+ "no form or API write takes its transferId (the transferId tools are warehouse transfers)",
+ inspection: "no form or API write takes inspectionId",
+ jobOperationBatch: "no form or API write takes a batch's readableId",
+ reimbursement:
+ "no form or API write takes reimbursementId (reimbursement lines only reference their parent)",
+ revenueRecognitionRun: "no form or API write takes runId"
+};
+
+type Entry = { name: string; line: number };
+
+function lineAt(contents: string, index: number): number {
+ return contents.slice(0, index).split("\n").length;
+}
+
+/** The `table:` of every counter in `export const sequences = [...]`. */
+function counters(seedData: string): Entry[] {
+ const start = seedData.indexOf("export const sequences = [");
+ if (start === -1) return [];
+ const end = seedData.indexOf("\n]", start);
+ const block = seedData.slice(start, end === -1 ? undefined : end);
+ return [...block.matchAll(/table: "(\w+)"/g)].map((m) => ({
+ name: m[1] as string,
+ line: lineAt(seedData, start + (m.index ?? 0))
+ }));
+}
+
+function attachedTables(attachments: string): Entry[] {
+ const keys = [...attachments.matchAll(/^ {2}(\w+): \{/gm)];
+ return keys.flatMap((m, i) => {
+ const from = m.index ?? 0;
+ const to = keys[i + 1]?.index ?? attachments.length;
+ return attachments.slice(from, to).includes(`"${INTERCEPTOR}"`)
+ ? [{ name: m[1] as string, line: lineAt(attachments, from) }]
+ : [];
+ });
+}
+
+/** Tables named in the interceptor's `CASE p_table` (WHEN 'table' THEN 'column'). */
+function interceptedTables(interceptor: string): Entry[] {
+ return [...interceptor.matchAll(/WHEN '(\w+)' THEN '\w+'/g)].map((m) => ({
+ name: m[1] as string,
+ line: lineAt(interceptor, m.index ?? 0)
+ }));
+}
+
+/**
+ * Every counter is either kept ahead of saved numbers by
+ * sync_advance_document_sequence or exempt with a reason, and the interceptor's
+ * table list matches the tables it is attached to.
+ */
+export function findUnsyncedDocumentSequences(sources: {
+ seedData: SourceFile;
+ attachments: SourceFile;
+ interceptor: SourceFile;
+}): Violation[] {
+ const attached = attachedTables(sources.attachments.contents);
+ const intercepted = interceptedTables(sources.interceptor.contents);
+ const attachedNames = new Set(attached.map((t) => t.name));
+ const interceptedNames = new Set(intercepted.map((t) => t.name));
+ const out: Violation[] = [];
+
+ for (const counter of counters(sources.seedData.contents)) {
+ const table = COUNTER_TABLES[counter.name] ?? counter.name;
+ const covered = attachedNames.has(table) && interceptedNames.has(table);
+ const exempt = counter.name in EXEMPT_COUNTERS;
+ if (!covered && !exempt) {
+ out.push({
+ file: sources.seedData.file,
+ line: counter.line,
+ snippet: `table: "${counter.name}"`,
+ message: `Counter "${counter.name}" is not kept ahead of saved numbers. Add "${table}" to the CASE in ${INTERCEPTOR}.sql and give it the interceptor in attachments.ts, or add "${counter.name}" to EXEMPT_COUNTERS with the reason no caller ever supplies its number.`
+ });
+ }
+ if (covered && exempt) {
+ out.push({
+ file: sources.seedData.file,
+ line: counter.line,
+ snippet: `table: "${counter.name}"`,
+ message: `Counter "${counter.name}" is covered by ${INTERCEPTOR}; remove it from EXEMPT_COUNTERS.`
+ });
+ }
+ }
+
+ for (const table of attached) {
+ if (!interceptedNames.has(table.name)) {
+ out.push({
+ file: sources.attachments.file,
+ line: table.line,
+ snippet: table.name,
+ message: `"${table.name}" runs ${INTERCEPTOR} but is missing from its CASE, so the interceptor ignores it.`
+ });
+ }
+ }
+
+ for (const table of intercepted) {
+ if (!attachedNames.has(table.name)) {
+ out.push({
+ file: sources.interceptor.file,
+ line: table.line,
+ snippet: `WHEN '${table.name}'`,
+ message: `"${table.name}" is in the ${INTERCEPTOR} CASE but not attached in attachments.ts, so it never runs.`
+ });
+ }
+ }
+
+ return out;
+}
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index 91019ffa9c..27eccf014e 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -12,6 +12,10 @@ import type {
StructureCheck,
Violation
} from "./check";
+import {
+ DOCUMENT_SEQUENCE_SYNCED,
+ findUnsyncedDocumentSequences
+} from "./conformance/document-sequence-synced";
import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";
import { indexRedirectBeforeLoaders } from "./conformance/index-redirect-before-loaders";
import { moduleShape } from "./conformance/module-shape";
@@ -53,6 +57,7 @@ import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
import { serverFnAuthorizesCaller } from "./conformance/server-fn-authorizes-caller";
import { spdxLicenseHeader } from "./conformance/spdx-license-header";
import { loadDbTableColumns } from "./sources/db-columns";
+import { loadDocumentSequenceSources } from "./sources/document-sequences";
import {
loadEdgeFunctions,
loadServerFunctions
@@ -189,6 +194,9 @@ export function collectFindings(root: string = repoRoot()): Finding[] {
...scanAll(loadLicenseFiles(root), [spdxLicenseHeader]),
...findDuplicatedAppFiles(loadTypescriptFiles(root, SHARED_APP_DIRS)).map(
(violation) => ({ checkId: NO_DUPLICATED_APP_FILE, violation })
+ ),
+ ...findUnsyncedDocumentSequences(loadDocumentSequenceSources(root)).map(
+ (violation) => ({ checkId: DOCUMENT_SEQUENCE_SYNCED, violation })
)
];
}
diff --git a/packages/checks/src/sources/document-sequences.ts b/packages/checks/src/sources/document-sequences.ts
new file mode 100644
index 0000000000..5b10de0650
--- /dev/null
+++ b/packages/checks/src/sources/document-sequences.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { SourceFile } from "../check";
+import {
+ ATTACHMENTS_FILE,
+ INTERCEPTOR_FILE,
+ SEED_DATA_FILE
+} from "../conformance/document-sequence-synced";
+
+/** The three files `findUnsyncedDocumentSequences` compares. */
+export function loadDocumentSequenceSources(root: string): {
+ seedData: SourceFile;
+ attachments: SourceFile;
+ interceptor: SourceFile;
+} {
+ const load = (file: string): SourceFile => ({
+ file,
+ contents: readFileSync(join(root, file), "utf-8")
+ });
+ return {
+ seedData: load(SEED_DATA_FILE),
+ attachments: load(ATTACHMENTS_FILE),
+ interceptor: load(INTERCEPTOR_FILE)
+ };
+}