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
fix(production): release checks on every path to Ready
naveenkash1799acffadbc
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 90f1788cf5..c7d845a506 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3729,3 +3729,23 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Rule:** Pass a plain, named variable to `Plural`, `t` and `Trans` placeholders, and keep the name when refactoring. If extract drops translations by mistake, restore the catalogs from git (`git checkout HEAD -- packages/locale/locales`), fix the name, and extract again.**Applies to:** every `Plural` / `t\`…${x}\`` / `<Trans>` with an interpolation.++## Guard a state by listing everything that writes it, not by who calls the check++**Context:** Strict backflush (2026-10-17). Release had to refuse a job with a line that had no storage unit. The check was added where the release check already ran: the Release dialog, bulk release, batch release.++**Problem:** Two more paths set a job to Ready without any check. The kanban scan with auto-release wrote `status: "Ready"` straight to the job with the service role. The MCP / API tool `production_updateJobStatus` wrote any status. A search for callers of the release function cannot find a direct write. A self-review on a fixed file list did not look outside it, and the docs then claimed "every release path".++**Rule:** To guard a state change, first list every writer of that state: grep for the value being written (`status: "Ready"`, `SET status = 'Ready'` in SQL) and for every caller of the write function, including MCP tools. Put the check where all writers meet, or give each writer the check. Keep the unchecked write out of the API (no `@mcp` tag). Do not claim "every path" without that list.++**Applies to:** release, completion, posting, cancellation — any status a check must gate.++## A flash returned with `data()` from a page loader never shows++**Context:** The kanban scan (2026-10-19) returned `data(result, await flash(request, error(…)))` from its loader, and its page then navigated to the job with `window.location`.++**Problem:** The message never appeared. The root's `flashMiddleware` reads and clears the flash on every request. It ran on the scan's own document request and cleared the cookie the loader had just set. Typecheck and unit tests cannot see this; only the browser did.++**Rule:** To carry a message to another page, throw `redirect(path, await flash(request, …))` from the loader or action, as every other route does. Do not return a flash with `data()` from a page loader and expect a later page to show it.++**Applies to:** any loader or action that sets a flash for the page it sends the user to.diff --git a/.ai/plans/2026-10-17-release-checks-every-path.md b/.ai/plans/2026-10-17-release-checks-every-path.mdnew file mode 100644index 0000000000..101bdadbcb--- /dev/null+++ b/.ai/plans/2026-10-17-release-checks-every-path.md@@ -0,0 +1,67 @@+# Plan: the release checks on every path to Ready++- Date: 2026-10-17+- Spec: `.ai/specs/2026-10-14-strict-backflush.md`+- Request: "implement in the Kanban and verify all the places … rigorous testing" (user, 2026-10-17).+- Rule: no commit and no push until the user asks.++## Every path that sets a job to Ready++| Path | Before this plan |+|---|---|+| Release dialog / status post (`x+/job+/$jobId.status.tsx`) | `getJobReleaseReadiness`, then `releaseJobs` |+| Bulk release (`x+/job+/release.tsx`) | `getJobReleaseReadiness` + `jobReleaseProblems`, then `releaseJobs` |+| Batch release (`releaseBatchMemberJobs`) | `getJobReleaseReadiness` + `jobReleaseProblems`, then `releaseJobs` |+| Kanban scan with `autoRelease` (`api+/kanban.$id.tsx`) | none: writes `status: "Ready"` directly |+| MCP / API tool `production_updateJobStatus` | none: `updateJobStatus` writes any status |++No SQL function sets a job to Ready. The SQL writes of `'Ready'` are on `jobOperation`.++## Decisions++| # | Decision | Reason |+|---|----------|--------|+| D1 | `updateJobStatus` (the MCP / API tool) refuses a move from Draft or Planned to Ready while `jobReleaseProblems` or "nothing to make" applies. | It is the one function every caller outside the app reaches. A refusal there covers the API and any later caller. |+| D2 | `writeJobStatus` (no `@mcp` tag) is the unguarded write. `releaseJobs` and the status route call it, after their own check. | They already ran the check. A second run per job would double the reads of a bulk release. The API cannot reach a function with no `@mcp` tag. |+| D3 | The kanban scan with `autoRelease` runs `jobReleaseBlockers`, then `releaseJobs`, then one schedule run. Its outside operations go on the supplier's newest Draft PO, else a new one. | Bulk release is the closest path with no dialog: same checks, same release (requirements, MRP, Ready, outside operation purchase orders, release date). Bulk release also refuses a supplier with a Draft PO, so a planner can choose one; no one at a kanban card can, so the scan reuses it (found in the browser test). |+| D4 | A kanban job that fails the checks stays Draft and stays linked to the kanban. The scan goes to the job page with a message that names the problems. MES is not opened. | The scan is not lost, and the planner sees what to fix. Opening MES for a job that is not released would start work on it. |+| D5 | With strict backflush on at the job's location, job creation gives a line the BoM's Pull From, else the item's default storage unit (`pickMethod`). It never takes the fullest bin. | The fullest bin is a guess, not a choice. With no Pull From and no default, the line has no storage unit, so release refuses it. |++## Tasks++- [x] T1. `production.service.ts`: split `updateJobStatus` into the guarded MCP function (D1) and `writeJobStatus` (D2).+- [x] T2. Point `releaseJobs`, `planDraftJob` and the status route at `writeJobStatus`.+- [x] T3. `api+/kanban.$id.tsx`: checks, `releaseJobs`, schedule, flash message (D3, D4).+- [x] T4. `get-method`: no fullest-bin fallback under strict backflush (D5), in both places that pick a line's bin.+- [x] T5. Tests: the guard (unit), the kanban decision (unit), get-method under strict (live database).+- [x] T6. Browser: a kanban scan with a missing storage unit, with everything set, and with `autoStartJob`; the job status route; the API tool.+- [x] T7. Docs: production `AGENTS.md`, kanban rule, spec, PR description; lesson on guarding a state by its writers.+- [x] T8. Gates: Biome, typecheck (database, server-functions, erp, mes), tests, translations.++## Browser test (2026-10-19)++Stack on this worktree's own localhost ports (the portless proxy needs sudo, and another worktree held the shared ports). Company: Carbon Development, strict backflush and Prevent negative stock on.++| # | Case | Result |+|---|------|--------|+| 1 | Kanban scan, BUS-STR-001, every line has a bin | J000027 Ready, release date set, scheduled, outside operation on a new Draft PO; scan opened the operation in MES |+| 2 | Same kanban again | Collision page; no second job |+| 3 | Kanban scan, STRESS-BOM (no operations), auto-release + auto-start | J000028–J000031, J000036 stay Draft and linked; scan lands on the job, not MES |+| 4 | Kanban scan with BRG-6201's default storage unit cleared | J000033 Draft with one line without a bin; toast names BRG-6201 |+| 5 | Kanban scan after the default was restored | J000034 Ready; its outside operation went on the existing Draft PO000019 |+| 6 | Kanban scan with auto-start | J000035 started (In Progress) and opened in MES |+| 7 | Release dialog, J000033 | "Missing Storage Units: BRG-6201", Release Job disabled |+| 8 | Bulk release, J000033 | "Could not release 1: J000033 (set a Pull From storage unit on BRG-6201; …)" |+| 9 | Plain status post Ready, J000033 | Refused, stays Draft (the toast of a hand-built HTML form post was not seen) |+| 10 | API `updateJobStatus` Ready, J000033 | HTTP 400 `RELEASE_REFUSED`, names BRG-6201 |+| 11 | API `updateJobStatus` Ready, J000032 (clean) | HTTP 200, Ready |+| 12 | API Paused → Ready, J000005 | HTTP 200 (a resume is not a release); set back to Paused |+| 13 | Pause, then Resume in the job header, J000035 | Paused, then Ready |++Bugs found and fixed:+- The refusal toast never showed: `data(…, flash)` from the kanban loader was cleared by the root's `flashMiddleware`. Now `throw redirect(jobPage, flash)`.+- After the first kanban release created a Draft PO for the outside operation supplier, every later scan was refused with "choose a purchase order". The kanban release now reuses the supplier's newest Draft PO.+- Kanban collision "Remove Job" said "Job cancelled" but only unlinks the job. The copy now says "Job removed from the kanban".+- `crbn up --no-hibernate` left a stale `asleep` marker in place, and the dev servers held every request for 120 s. `crbn up` now clears it for its own stack.++Noted, not changed: an API key without Purchasing view gets "has no supplier" for an outside operation, because the check reads with the caller's permissions.diff --git a/.ai/specs/2026-10-14-strict-backflush.md b/.ai/specs/2026-10-14-strict-backflush.mdindex 2eaa6c6ccf..b6bf43827c 100644--- a/.ai/specs/2026-10-14-strict-backflush.md+++ b/.ai/specs/2026-10-14-strict-backflush.md@@ -56,6 +56,8 @@ Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and| 3 | Which locations need a Pull From | Each location that has at least one active work center and at least one active storage unit. | Pull From is stored per location (`methodMaterial.storageUnitIds`). A location with no work center builds nothing. A location with no storage unit has no bin a line could name, so a Pull From there can never be set. || 4 | Draft methods | Release refuses a job whose pulled line has no `storageUnitId`. | A job can come from a Draft method, so the activation check alone has a gap. || 5 | Picked stock | The material's picks and unclaimed lineside stock are consumed first, as today. The strict rule applies to the remainder, against the line's Pull From. After a pick, the Pull From is the source bin of the line's oldest pick line into its current bin (`pullFromStorageUnit`). Job completion (SQL) draws a picked line from its lineside bin first, up to what the bin holds, then the rest from the Pull From. | A pick moves stock out of the Pull From bin with a transfer, so the records stay correct. Picking also moves `jobMaterial.storageUnitId` to the lineside bin, so that column no longer names the Pull From. The pick line keeps it. A later picking list takes the fullest bin, so only the oldest pick line names the Pull From. |+| 4a | Every path to Ready | Each path that sets a job to Ready runs the release checks: the Release dialog, a plain status post, bulk release, batch release, a kanban scan with auto-release, and the API tool `production_updateJobStatus`. A kanban job that fails them stays Draft and stays linked; the scan lands on the job with the reason. | A check on some paths only is a check a user can step around. The kanban scan and the API wrote the status directly. |+| 4b | Job creation under strict backflush | A job line gets the BoM's Pull From, else the item's default storage unit. It never takes the fullest bin. A line with neither has no storage unit, and release refuses the job. | The fullest bin is a guess that depends on where the stock is. It let a job built from a BoM with no Pull From pass release. || 5a | Locations without a pull-from bin | Strict backflush applies only at a location from decision 3. Elsewhere the backflush, release and the badges behave as with the setting off. | Activation asks for no Pull From there, so a refusal there could never be fixed. || 6a | Negative stock under strict bins | A second switch, `companySettings.preventNegativeBackflush` ("Prevent negative stock", default `true`), nested under Strict Backflush and only active while it is on. Off: the material is still drawn only from its own storage unit, and that storage unit may go below zero. A missing storage unit is refused either way. | A company can want strict bins (accurate per-location stock) without the hard stop on a short bin. Default `true` keeps the behavior the setting shipped with. || 6 | Where a shortage stops the work | At operation completion (MES and ERP), at job completion, and at manual issue of a planned material. | If only job completion stopped, the operation would take stock from another bin first. |@@ -166,6 +168,8 @@ No new table. No RLS change.## Changelog- 2026-10-14: Created from the backflush rules design discussion.+- 2026-10-19: Browser test of every path to Ready. A kanban release reuses the supplier's newest Draft PO for outside operations (no one at a scan can choose one), and a refused scan shows its reason on the job page.+- 2026-10-17: Every path to Ready now runs the release checks: the kanban scan with auto-release (through `releaseJobs`) and the API tool `updateJobStatus` were missed (decision 4a). Job creation under strict backflush no longer takes the fullest bin (decision 4b). Plan `.ai/plans/2026-10-17-release-checks-every-path.md`.- 2026-10-16: Self-review fixes (plan `.ai/plans/2026-10-16-strict-backflush-review-fixes.md`): after a partial pick, the rest now comes from the Pull From, not lineside (decision 5, TypeScript and SQL); strict backflush skips a location with no pull-from bin (decision 5a); both paths lock every (bin, item) pair in one order before the first draw; SQL compares rounded quantities and counts a refused need; the dry run stops at the strict check; the inspection lot is checked before it closes; the New Version route checks activation; every release path checks storage units; the card counts with SQL and the jobs list holds only lines a backflush would refuse (decision 8); the BoM badges use the pull-from locations.- 2026-10-16: The settings card counts open jobs with a material that has no storage unit, and both counts open a searchable drawer instead of an inline list (user request).- 2026-10-16: The drawers show locations as pills. A materials cell shows 3 part IDs, and "+N more" opens the full list in a popover that scrolls (user request).diff --git a/.claude/rules/kanban-system.md b/.claude/rules/kanban-system.mdindex 4c443811c6..961e786555 100644--- a/.claude/rules/kanban-system.md+++ b/.claude/rules/kanban-system.md@@ -76,11 +76,13 @@ RLS: SELECT = any employee role; INSERT/UPDATE/DELETE = `inventory_create`/`inveAPI routes in `apps/erp/app/routes/api+/`: `kanban.$id.tsx`, `kanban.collision.$id.tsx`, `kanban.start.$id.tsx`, `kanban.complete.$id.tsx`, `kanban.link.$id.tsx`.`kanban.$id.tsx` (the "order"/create scan) branches on `replenishmentSystem`:-- **Make** — if a job is already linked (`jobReadableId`) it redirects to the collision route (no duplicate job); otherwise creates a job from the item, links it (`updateKanbanJob`), then `autoRelease` runs MRP + schedules and `autoStartJob` redirects into MES to start the first operation.+- **Make** — if a job is already linked (`jobReadableId`) it redirects to the collision route (no duplicate job); otherwise creates a job from the item and links it (`updateKanbanJob`). With `autoRelease`, `releaseKanbanJob` runs the bulk release checks (`jobReleaseBlockers` — nothing to make, manufacturing blocked, assemblies without operations, outside operations without a supplier, strict backflush lines with no storage unit), then `releaseJobs` (recalculate, MRP, Ready, outside-operation POs, release date; telemetry `source: "kanban"`), then `runLocationSchedule` once the job is Ready. Unlike bulk release, a supplier's Draft PO is not a blocker — no one at a kanban card can choose one — so the outside operations go on the supplier's newest Draft PO (highest `purchaseOrderId`), else a new one; otherwise the first scan's PO blocked every later scan. A job that fails the checks stays Draft, stays linked, and the loader throws `redirect(jobPage, flash(…))` naming the problems. Returning the flash with `data()` does not work: the root's `flashMiddleware` clears it on the same request. Only a released job sends the scanner to MES: `autoStartJob` opens its first operation's start, else the operation. See `apps/erp/app/modules/production/AGENTS.md` → "Every path to Ready".- **Buy** — reuses an existing draft/planned PO for the supplier (or creates one), adds a PO line with the kanban qty (applying `conversionFactor`/`purchaseUnitOfMeasureCode`/storage unit), redirects to the PO.- **Transfer** — calls the `kanban-replenish` server function with `mode: "scan"`, which writes a Released stock transfer with one line: `itemId`, `fromStorageUnitId` → `storageUnitId` (to), `quantity`, and serial/batch flags from `item.itemTrackingType` (a serial line of qty > 1 splits into qty-1 lines, `expandSerialTrackedLines`). The transfer carries `stockTransfer.kanbanId` and a Tiptap note "Kanban replenishment — … Signal: scan by <user>." Redirects to the stock transfer, where the qty can be **partially picked** at pick time. Each scan makes a new transfer, with no level test. Storage rules are NOT evaluated (a QR scan can't show the acknowledge dialog the interactive wizard uses). The route calls it with `serverFns.as` (the scanner's client): scan mode needs `create: "inventory"`, the same check the `stockTransfer` RLS rule made when the route inserted directly. Never switch this call to `serverFns.system` — that lets any employee create transfers. The server function re-checks that both bins belong to the company and the kanban's location (CWE-639).- **Buy and Make** — not a kanban option (the enum has no such value).+The collision page's "Remove Job" only unlinks the job (`jobId: null`; the job is unchanged) and redirects to the scan, which creates the next job.+`start`/`complete` resolve the linked job's active operation and redirect to the MES operation start/complete endpoints; `link` navigates to the job/operation.## Level signal (Transfer kanbans with `replenishmentLevel`)diff --git a/apps/erp/app/hooks/usePullFromLocationIds.ts b/apps/erp/app/hooks/usePullFromLocationIds.tsindex 1e9708d85d..f35f72509a 100644--- a/apps/erp/app/hooks/usePullFromLocationIds.ts+++ b/apps/erp/app/hooks/usePullFromLocationIds.ts@@ -7,11 +7,7 @@ import type { loader } from "~/routes/api+/items.pull-from-locations";import { path } from "~/utils/path";import { useCompanySettings } from "./useCompanySettings";-/**- * Strict backflush: the locations a pulled line needs a Pull From at, or null- * while the setting is off or the list is still loading (a badge shows- * nothing until it is known).- */+/** Null while strict backflush is off or the list is loading. */export function usePullFromLocationIds(): string[] | null {const companySettings = useCompanySettings();const strict = companySettings?.requireBackflushStorageUnit === true;diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsxindex 373adbdeff..bf5fe1cd74 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx@@ -261,8 +261,6 @@ const BillOfMaterial = ({configurationRules?.map((rule) => [rule.field, rule]) ?? []);- // Strict backflush: mark collapsed rows with no Pull From at a location- // that needs one — the test activation refuses on (`convert`).const pullFromLocationIds = usePullFromLocationIds();const missingPullFrom = (material: Material) =>pullFromLocationIds !== null &&@@ -716,10 +714,6 @@ function MaterialForm({item.data.item?.replenishmentSystem ?? replenishmentSystem ?? "Buy"});- // Strict backflush: a pulled, stocked line must name the storage unit it is- // backflushed from, at the selected location when that location needs one,- // before its method version can be made active. A changed item's tracking- // type comes from `onItemChange`, keyed by the item it was read for.const pullFromLocationIds = usePullFromLocationIds();const [changedItemTracking, setChangedItemTracking] = useState<{itemId: string;diff --git a/apps/erp/app/modules/items/ui/Item/MethodRow.tsx b/apps/erp/app/modules/items/ui/Item/MethodRow.tsxindex f0b5a32fae..c197e7d619 100644--- a/apps/erp/app/modules/items/ui/Item/MethodRow.tsx+++ b/apps/erp/app/modules/items/ui/Item/MethodRow.tsx@@ -98,9 +98,6 @@ export function MaterialRowTitle({itemType?: string | null;supersessionMode?: Parameters<typeof ItemLifecycleBadge>[0]["mode"];hasRules?: boolean;- /** Strict backflush: the line has no storage unit to backflush from. Shown- * on the collapsed row so a long BoM's gaps are found without opening- * every line. */missingPullFrom?: boolean;}) {return (diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 4a47169244..6572990ec9 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -24,7 +24,8 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Which lines, which locations.** `needsPullFrom` (`@carbon/database/strict-backflush`): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are `getPullFromLocations` / `isPullFromLocation` — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name). Strict backflush does not apply anywhere else: activation, release, the backflush, the badges and the settings card all skip such a location.- **Activation.** `getMethodPartsMissingPullFrom` + `activationRefusalMessage` (`@carbon/database/strict-backflush`). `convert` `methodVersionToActive` refuses through `assertMethodHasPullFrom` (`packages/server-functions/src/lib/strict-backflush.ts`); the New Version route (`x+/items+/methods+/version.new.tsx`), which makes a single Draft version Active, refuses the same way before it writes. The change-notice draft (`createChangeNoticeDraftMethod`) freezes a Draft base as Active without the check: that is a side effect of opening the notice, and release still refuses the jobs.-- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part; jobs at other locations are skipped). `$jobId.status.tsx` refuses on it for every move to Ready from Draft or Planned (the dialog, a plain post, the API); resuming a Paused job is not a release. `jobReleaseProblems` and `BatchReleaseModal` refuse on it too. `JobStartModal` lists the parts and disables Release Job; while the pull-from locations load it assumes the job's location needs them, and a failed read shows an error and disables Release.+- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part; jobs at other locations are skipped), and every path that sets a job to Ready refuses on it — see "Every path to Ready" under `releaseJobs` below. `JobStartModal` lists the parts and disables Release Job; while the pull-from locations load it assumes the job's location needs them, and a failed read shows an error and disables Release.+- **Job creation.** With strict backflush on at the job's location, `get-method` gives a line the BoM's Pull From, else the item's default storage unit (`pickMethod`), and never the fullest bin (`withFullestBin` in `itemToJob`, the same gate in `createItemDefaults`). A line with neither stays without a storage unit, so the job shows in the settings drawer and release refuses it. With the setting off, the fullest bin is still the last fallback.- **Backflush.** `issueJobOperationMaterials` and `partToOperation` (planned material, consuming issue) take picked and unclaimed lineside stock first, then what no pick covered from the line's Pull From only (`assertBinCovers` / `binCoverProblem`: 409, names the part, the bin, need and have). A pick points `jobMaterial.storageUnitId` at lineside (`pointJobMaterialAtLineside`), so the Pull From is resolved by `resolvePullFromStorageUnits` → `pullFromStorageUnit`: the source bin of the line's OLDEST pick line into its current bin, else the line's own bin. Before the first draw, `lockStrictBins` takes `pg_advisory_xact_lock(hashtextextended('strict-backflush:<companyId>:<bin>:<item>', 0))` for every (Pull From, item) pair in key-hash order; SQL locks the same keys in the same order, so two completions cannot deadlock. Every shortfall is collected and refused once; a refused material still counts its need against the bin, so the refusal names the whole shortfall. A refusal is a toast, so every strict message goes through `summarizeList`: the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). SQL `backflush_job_materials` (`20261015163040_strict-backflush.sql`) does the same at job completion: a picked line is drawn from lineside first (up to its on-hand), the rest from the Pull From; quantities compare at `round(…, 5)`.- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` first invoke `issue` `jobOperation` with `dryRun: true`; `issueJobOperationMaterials` throws `DryRunRollback` right after the strict check, before any ledger, cost or journal row, and the call is a no-op when the setting is off. MES callers go through `checkStrictBackflush` (`apps/mes/app/services/quality.server.ts`): `complete.tsx`, `end.$operationId.tsx`, `inspection-lot.$id.complete-passed.tsx`, and `inspection-lot.$id.disposition.tsx`, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERP `completeOperation` and `batch-operations` `complete` dry-run too; batch phase 2 keeps a refusal's 409. The dry run narrows the race, it does not close it (its lock ends with its rollback), so a failure after the units are recorded says "Units completed, but …" — the operator must not record them again.- **Existing Active methods and released jobs are never changed** when the setting turns on. Settings → Items counts both gaps with `getStrictBackflushGapCounts` (`settings.server.ts`, two `count(DISTINCT …)` statements; a failed count shows an error line, never a clean card) and each count's Review button opens a route drawer (`settings+/items.methods-missing-pull-from.tsx`, `items.jobs-missing-storage-unit.tsx`) over `getActiveMethodsMissingPullFrom` / `getOpenJobsMissingStorageUnit` (`settings.server.ts`). Each count and its list share one query builder (`methodLinesMissingPullFrom`, `jobLinesMissingStorageUnit`, the SQL form of `needsPullFrom`), so they cannot disagree. The jobs list holds only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue, at a pull-from location. The drawers page in memory with `pageInMemory` (`~/utils/query`) in a searchable, paged `Table` (`ui/StrictBackflush/StrictBackflushTables.tsx`); a failed read flashes an error and returns to the page. A long list never goes in the card itself. Locations render as `Enumerable` pills; a materials cell shows 3 part IDs and a "+N more" popover with all of them, which stops wheel and touch propagation so it scrolls inside the drawer (`conventions-ui.md`, "Popovers inside Drawers").@@ -106,7 +107,18 @@ pnpm --filter @carbon/erp test- `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured- `getJob` / `getJobs` / `getJobMethodTree` / `getJobMethodTreeArray` — job reads with method hierarchy-- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`+- **Every path to Ready.** A job reaches Ready only through these, and each refuses a job that fails the release checks:++ | Path | Checks |+ |---|---|+ | Release dialog / status post (`$jobId.status.tsx`) | `getJobReleaseReadiness` (missing assemblies, storage units), then `releaseJobs`; a plain post of Ready also goes through `updateJobStatus` |+ | Bulk release (`x+/job+/release.tsx`) | `jobReleaseBlockers` + a supplier with Draft POs, then `releaseJobs` |+ | Batch release (`releaseBatchMemberJobs`) | `jobReleaseProblems`, then `releaseJobs` |+ | Kanban scan with `autoRelease` (`api+/kanban.$id.tsx` → `releaseKanbanJob`) | `jobReleaseBlockers`, then `releaseJobs` (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft, stays linked to the kanban, and the loader throws `redirect` to the job page with a flash naming the problems; MES is not opened |+ | MCP / API tool `production_updateJobStatus` | `updateJobStatus` refuses Draft or Planned → Ready while `jobReleaseBlockers` finds anything (HTTP 400, `RELEASE_REFUSED`, the message names the job and the problems). A failed read refuses too. The check reads with the caller's client: a key without Purchasing view cannot see supplier processes, so an outside operation reads as "has no supplier". A release here is the status write only (no recalculation, MRP or purchase orders), as before |++ `jobReleaseBlockers` (`job-release-logic.ts`) is "nothing to make" plus `jobReleaseProblems`. `writeJobStatus` is the unchecked write, with no `@mcp` tag so the API cannot reach it; only a caller that has already checked (`releaseJobs`, `planDraftJob`, `cancelJob`) uses it. No SQL function sets a job to Ready (the SQL writes of `'Ready'` are on `jobOperation`). A new path to Ready must use `releaseJobs` after the checks, or `updateJobStatus`.+- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `writeJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation- `getJobOrderStatusMap` — procurement status indicators per materialdiff --git a/apps/erp/app/modules/production/production.server.test.ts b/apps/erp/app/modules/production/production.server.test.tsindex fad20bdc0f..da6e769e33 100644--- a/apps/erp/app/modules/production/production.server.test.ts+++ b/apps/erp/app/modules/production/production.server.test.ts@@ -26,14 +26,14 @@ vi.mock("./production.service", () => ({recalculateJobRequirements: vi.fn(),returnPickedRemaindersForJob: vi.fn(),runMRP: vi.fn(),- updateJobStatus: vi.fn()+ writeJobStatus: vi.fn()}));import { cancelOpenPickingListsForJob } from "~/modules/inventory/inventory.service";import { cancelJob } from "./production.server";import {returnPickedRemaindersForJob,- updateJobStatus+ writeJobStatus} from "./production.service";// cancelJob is the one cancel path (the job status route and planning's@@ -60,8 +60,8 @@ describe("cancelJob", () => {events.push("cancelOpenPickingLists");return { error: null };}) as never);- vi.mocked(updateJobStatus).mockImplementation((async () => {- events.push("updateJobStatus");+ vi.mocked(writeJobStatus).mockImplementation((async () => {+ events.push("writeJobStatus");return { data: null, error: null, updated: true };}) as never);});@@ -72,7 +72,7 @@ describe("cancelJob", () => {expect(events).toEqual(["returnPickedRemainders","cancelOpenPickingLists",- "updateJobStatus"+ "writeJobStatus"]);expect(returnPickedRemaindersForJob).toHaveBeenCalledWith(expect.anything(),@@ -84,7 +84,7 @@ describe("cancelJob", () => {companyId: "company-1",userId: "user-1"});- expect(updateJobStatus).toHaveBeenCalledWith(args.client, {+ expect(writeJobStatus).toHaveBeenCalledWith(args.client, {id: "job-1",companyId: "company-1",status: "Cancelled",@@ -104,7 +104,7 @@ describe("cancelJob", () => {"Cancel aborted: returning picked material failed");expect(cancelOpenPickingListsForJob).not.toHaveBeenCalled();- expect(updateJobStatus).not.toHaveBeenCalled();+ expect(writeJobStatus).not.toHaveBeenCalled();});it("stops before the status when the picking lists cannot be closed", async () => {@@ -118,12 +118,12 @@ describe("cancelJob", () => {"Cancel aborted: its picking lists could not be closed");expect(returnPickedRemaindersForJob).toHaveBeenCalledOnce();- expect(updateJobStatus).not.toHaveBeenCalled();+ expect(writeJobStatus).not.toHaveBeenCalled();});it("reports a failed status update", async () => {- vi.mocked(updateJobStatus).mockImplementationOnce((async () => {- events.push("updateJobStatus");+ vi.mocked(writeJobStatus).mockImplementationOnce((async () => {+ events.push("writeJobStatus");return { data: null, error: new Error("update failed"), updated: false };}) as never);@@ -133,7 +133,7 @@ describe("cancelJob", () => {expect(events).toEqual(["returnPickedRemainders","cancelOpenPickingLists",- "updateJobStatus"+ "writeJobStatus"]);});@@ -173,17 +173,17 @@ describe("cancelJob", () => {expect(events).toEqual(["returnPickedRemainders","cancelOpenPickingLists",- "updateJobStatus"+ "writeJobStatus"]);- expect(updateJobStatus).toHaveBeenCalledWith(+ expect(writeJobStatus).toHaveBeenCalledWith(client,expect.objectContaining({ fromStatuses: ["Draft", "Planned"] }));});it("refuses when the job moves on between the check and the write", async () => {- vi.mocked(updateJobStatus).mockImplementationOnce((async () => {- events.push("updateJobStatus");+ vi.mocked(writeJobStatus).mockImplementationOnce((async () => {+ events.push("writeJobStatus");return { data: [], error: null, updated: false };}) as never);diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 0113eb9fec..004fe0f442 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -6,6 +6,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { ASSEMBLER_SERVICE_URL } from "@carbon/env";+import type { JobSource } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";import { datetime, getErrorMessage } from "@carbon/utils";@@ -18,7 +19,7 @@ import {recalculateJobRequirements,returnPickedRemaindersForJob,runMRP,- updateJobStatus+ writeJobStatus} from "./production.service";import { jobReleaseProblems } from "./ui/Jobs/job-release-logic";@@ -156,7 +157,7 @@ export async function planDraftJob({};}- const flipped = await updateJobStatus(client, {+ const flipped = await writeJobStatus(client, {id: jobId,companyId,status: "Planned",@@ -200,7 +201,8 @@ export async function releaseJobs({jobIds,companyId,userId,- purchaseOrdersBySupplierId+ purchaseOrdersBySupplierId,+ source = "erp"}: {client: SupabaseClient<Database>;db: Kysely<KyselyDatabase>;@@ -208,6 +210,7 @@ export async function releaseJobs({companyId: string;userId: string;purchaseOrdersBySupplierId: Record<string, string>;+ source?: JobSource;}): Promise<{error: string | null;purchaseOrdersBySupplierId: Record<string, string>;@@ -249,13 +252,17 @@ export async function releaseJobs({// Only a job still waiting for release flips: the caller checked the// status before the recalculation and MRP above, and someone may have// cancelled or released it since.- const update = await updateJobStatus(client, {- id,- companyId,- status: "Ready",- updatedBy: userId,- fromStatuses: ["Draft", "Planned"]- });+ const update = await writeJobStatus(+ client,+ {+ id,+ companyId,+ status: "Ready",+ updatedBy: userId,+ fromStatuses: ["Draft", "Planned"]+ },+ { source }+ );if (update.error) return fail("The job could not be released");if (!update.updated) {return fail("The job is no longer Draft or Planned");@@ -378,7 +385,7 @@ export async function cancelJob({};}- const update = await updateJobStatus(client, {+ const update = await writeJobStatus(client, {id: jobId,companyId,status: "Cancelled",diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex ca429fd109..f44a35a3be 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -46,7 +46,8 @@ import {} from "@carbon/viewer";import { isPlanFlagged } from "@carbon/viewer/steps";import { parseDate } from "@internationalized/date";-import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";+import type { SupabaseClient } from "@supabase/supabase-js";+import { PostgrestError } from "@supabase/supabase-js";import type { ExpressionBuilder } from "kysely";import { sql } from "kysely";import { nanoid } from "nanoid";@@ -124,6 +125,7 @@ import type {JobMaterialSupplyJobLine} from "./types";import {+ jobReleaseBlockers,makeMethodsMissingOperations,materialsWithoutStorageUnit,outsideOperationsNeedingPurchaseOrders,@@ -2971,8 +2973,6 @@ export type JobReleaseReadiness = {}[];// The suppliers this job's outside operations go on a purchase order for.supplierIds: string[];- // Strict backflush: pulled, stocked lines with no storage unit to- // backflush from. Always empty while the setting is off.materialsWithoutStorageUnit: { id: string; description: string }[];}[];// Suppliers whose outside operations release will put on a purchase order,@@ -2983,11 +2983,6 @@ export type JobReleaseReadiness = {}[];};-// Strict backflush (companySettings.requireBackflushStorageUnit): a job may not-// be released while a pulled, stocked line has no storage unit, because its-// backflush would be refused. Keyed by job id; empty while the setting is off,-// and for a job at a location strict backflush skips (no active work center or-// no active storage unit — `getPullFromLocations`).async function getMaterialsWithoutStorageUnit(client: SupabaseClient<Database>,jobIds: string[],@@ -3025,8 +3020,6 @@ async function getMaterialsWithoutStorageUnit())];- // The same test as getPullFromLocations, for these jobs' locations only:- // one row per location that has an active work center and storage unit.const pullFromLocations =jobLocationIds.length === 0? { data: [], error: null }@@ -3286,21 +3279,80 @@ export async function getJobReleaseReadiness(};}+type JobStatusUpdate = {+ id: string;+ companyId: string;+ status: (typeof jobStatus)[number];+ assignee?: string | null;+ updatedBy: string;+ // Flip only from one of these statuses. A release reads the status, then+ // runs for a while (recalculate, MRP) before it writes; a job someone+ // cancelled in between must not come back as Ready. `updated` is false+ // when the row no longer matched.+ fromStatuses?: (typeof jobStatus)[number][];+};++/** Refuses a Draft or Planned → Ready release that fails `jobReleaseBlockers`,+ * so the API cannot release a job the app would not. *//** @mcp update */export async function updateJobStatus(client: SupabaseClient<Database>,- params: {- id: string;- companyId: string;- status: (typeof jobStatus)[number];- assignee?: string | null;- updatedBy: string;- // Flip only from one of these statuses. A release reads the status, then- // runs for a while (recalculate, MRP) before it writes; a job someone- // cancelled in between must not come back as Ready. `updated` is false- // when the row no longer matched.- fromStatuses?: (typeof jobStatus)[number][];+ params: JobStatusUpdate+) {+ if (params.status === "Ready") {+ const refusal = await jobReleaseRefusal(+ client,+ params.id,+ params.companyId+ );+ if (refusal) {+ return {+ data: null,+ error: new PostgrestError({+ message: refusal,+ details: "",+ hint: "",+ code: "RELEASE_REFUSED"+ }),+ updated: false+ };+ }}+ return writeJobStatus(client, params);+}++async function jobReleaseRefusal(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+): Promise<string | null> {+ const job = await client+ .from("job")+ .select("jobId, status, quantity, scrapQuantity")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+ if (job.error) return "The job could not be checked for release";+ if (!job.data) return null;+ if (job.data.status !== "Draft" && job.data.status !== "Planned") return null;++ const readiness = await getJobReleaseReadiness(client, [id], companyId);+ const ready = readiness.data?.jobs[0];+ if (readiness.error || !ready)+ return "The job could not be checked for release";++ const blockers = jobReleaseBlockers(job.data, ready);+ return blockers.length > 0+ ? `${job.data.jobId} cannot be released: ${blockers.join("; ")}`+ : null;+}++/** The status write with no release check, for a caller that already checked.+ * Not an MCP tool: the API must go through `updateJobStatus`. */+export async function writeJobStatus(+ client: SupabaseClient<Database>,+ params: JobStatusUpdate,+ { source = "erp" }: { source?: JobSource } = {}) {const { id, companyId, status, assignee, updatedBy, fromStatuses } = params;@@ -3349,7 +3401,7 @@ export async function updateJobStatus(userId: updatedBy,jobId: id,priorStatus: prior.data.status,- source: "erp"+ source});} else if (status === "Paused") {await raiseMoment("production.jobHeld", {@@ -11017,9 +11069,6 @@ export async function completeOperation(}}- // Strict backflush: refuse before the production quantity is recorded, so a- // short storage unit never leaves units completed with no material- // consumed. A no-op when strict backflush is off.const check = await serverFns.as({ client, db, companyId, userId }).invoke("issue", {diff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsxindex 2164ce1b95..ab42c94577 100644--- a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx@@ -46,8 +46,7 @@ export function BatchReleaseModal({onClose: () => void;}) {const { t } = useLingui();- // The first few parts, then a count — a whole translated sentence either- // way, so the "and N more" is translated too.+ // A whole translated sentence, so "and N more" is translated too.const storageUnitReason = (materials: { description: string }[]) => {const names = materials.slice(0, MESSAGE_LIST_LIMIT)diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsxindex 4044cfc034..c20fb8d499 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx@@ -294,8 +294,6 @@ const JobBillOfMaterial = ({const [storeItems] = useItems();const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));- // Strict backflush: mark collapsed rows with no storage unit to backflush- // from, when the job's location needs one — the test release refuses on.const pullFromLocationIds = usePullFromLocationIds();const jobLocationId = jobData?.job?.locationId;const missingPullFrom = (material: Material) =>@@ -757,10 +755,6 @@ function MaterialForm({const locationId = routeData?.job?.locationId ?? undefined;const storageUnits = useStorageUnits(locationId);- // Strict backflush: a pulled, stocked line is backflushed only from its own- // storage unit, so "Default Storage Unit" would hide a line that will be- // refused at release and at backflush. A changed item's tracking type comes- // from `onItemChange`, keyed by the item it was read for.const pullFromLocationIds = usePullFromLocationIds();const itemTrackingType =changedItemTracking?.itemId === itemData.itemIddiff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex f230dbd0d7..41782ecc0c 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -631,10 +631,8 @@ export function JobStartModal({const companySettings = useCompanySettings();const strictBackflush = companySettings?.requireBackflushStorageUnit === true;const [loading, setLoading] = useState(true);- // Strict backflush: lines whose backflush would be refused. The release- // route refuses them too; showing them here saves a failed submit. They- // count only at a location that needs a Pull From — assumed while that list- // loads, so the dialog never offers a release the route refuses.+ // Assumed to apply while the locations load, so the dialog never offers a+ // release the route refuses.const pullFromLocationIds = usePullFromLocationIds();const strictAtJobLocation =strictBackflush &&diff --git a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.tsindex e0f8edecd8..cc29861039 100644--- a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts+++ b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts@@ -120,7 +120,6 @@ export function jobReleaseProblems(job: {? `choose a supplier for ${op.description} on the job`: `${op.description} has no supplier`),- // Strict backflush: these lines' backflush would be refused....(job.materialsWithoutStorageUnit.length > 0? [`set a Pull From storage unit on ${summarizeList(@@ -131,6 +130,19 @@ export function jobReleaseProblems(job: {];}+// Refuses a release that has no dialog: bulk release, a kanban scan, the API.+export function jobReleaseBlockers(+ job: { quantity: number | null; scrapQuantity: number | null },+ readiness: Parameters<typeof jobReleaseProblems>[0]+): string[] {+ return [+ ...(Number(job.quantity ?? 0) === 0 && Number(job.scrapQuantity ?? 0) === 0+ ? ["nothing to make"]+ : []),+ ...jobReleaseProblems(readiness)+ ];+}+export type StorageUnitLine = {id: string;description: string;@@ -143,9 +155,6 @@ export type StorageUnitLine = {} | null;};-// Strict backflush: the pulled, stocked lines with no storage unit to-// backflush from, one entry per part — a part used on two lines needs the-// same fix, so naming it twice only lengthens the message.export function materialsWithoutStorageUnit(lines: StorageUnitLine[]): { id: string; description: string }[] {diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex 5378308f51..81a29f4453 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -880,15 +880,9 @@ export async function getSyncOperationReadableIds(return Object.fromEntries(results.flat());}-// Strict backflush leaves Active methods and released jobs as they are. The-// Settings → Items card counts the ones with a gap, and its drawers list them.-// Both read the same query, so a count and its drawer cannot disagree. The-// filters are the SQL form of `needsPullFrom` (@carbon/database/strict-backflush;-// a null tracking type counts as stocked there too), so a count is one-// statement — the card re-runs on every drawer search, sort and page. Kysely,-// not PostgREST: a company's lines can pass the 1000-row cap.--// Active BoM lines with no Pull From at one of `locationIds`.+// Strict backflush gaps. Each count and its drawer list share one query, the+// SQL form of `needsPullFrom`, so they cannot disagree.+function methodLinesMissingPullFrom(db: Kysely<KyselyDatabase>,companyId: string,@@ -918,9 +912,6 @@ function methodLinesMissingPullFrom();}-// Lines on open jobs that the job's next backflush would refuse: no storage-// unit, stocked, not batch or serial (their issue flow is unchanged), still-// something to issue, at a location where strict backflush applies.function jobLinesMissingStorageUnit(db: Kysely<KyselyDatabase>,companyId: string,diff --git a/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx b/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsxindex 0eddc2dac0..f4c5bc4dbd 100644--- a/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx+++ b/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx@@ -27,8 +27,6 @@ import JobStatus from "~/modules/production/ui/Jobs/JobStatus";import { path } from "~/utils/path";import type { JobMissingStorageUnit, MethodMissingPullFrom } from "../../types";-// The make-method page of a method's item, by item type. Only Parts, Tools and-// Services carry make methods with their own route.export function makeMethodPath(method: {itemId: string;itemType: string;@@ -48,9 +46,6 @@ export function makeMethodPath(method: {const PARTS_SHOWN = 3;-// A list of part IDs in one cell. An ID never breaks across lines. Past the-// first few, "+N more" opens the whole list in a scrolling popover (a sheet on-// a phone). The drawer's search and the CSV download cover every ID too.function PartList({ parts, label }: { parts: string[]; label: string }) {const { t } = useLingui();const { isPhone } = useViewport();@@ -71,9 +66,8 @@ function PartList({ parts, label }: { parts: string[]; label: string }) {{t`+${more} more`}</Button></PopoverTrigger>- {/* Rendered outside the drawer, whose scroll lock swallows the- wheel and touch events: stop them here, or the list cannot- scroll (conventions-ui.md, "Popovers inside Drawers"). */}+ {/* Portaled outside the drawer: stop the events its scroll lock+ would swallow. */}<PopoverContentalign="start"collisionPadding={8}diff --git a/apps/erp/app/routes/api+/items.pull-from-locations.ts b/apps/erp/app/routes/api+/items.pull-from-locations.tsindex 57edabc75f..a83ec18bae 100644--- a/apps/erp/app/routes/api+/items.pull-from-locations.ts+++ b/apps/erp/app/routes/api+/items.pull-from-locations.ts@@ -11,9 +11,6 @@ import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "items-pull-from-locations");-// Strict backflush: the locations a pulled line needs a Pull From at (an-// active work center and an active storage unit). The BoM badges read it, so-// they mark the same lines activation refuses.export async function loader({ request }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {});try {diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex e21286da86..370acc9a65 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -2,19 +2,18 @@// 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 { notFound } from "@carbon/auth";+import { error, notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";+import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import { convertUnitPrice } from "@carbon/database/supplier-part-price";-import { trigger } from "@carbon/jobs";-import { trackWorkEvent } from "@carbon/lib/telemetry";import { getLogger } from "@carbon/logger";import { runLocationSchedule } from "@carbon/planning";import { Loading } from "@carbon/react";import { serverFns } from "@carbon/server-functions";-import { datetime } from "@carbon/utils";+import { datetime, redirect } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { Suspense } from "react";import type { LoaderFunctionArgs } from "react-router";@@ -24,11 +23,13 @@ import { getDefaultStorageUnitForJob, getKanban } from "~/modules/inventory";import { getItemReplenishment, getSupplierPartPricing } from "~/modules/items";import {getActiveJobOperationByJobId,+ getJobReleaseReadiness,insertJob,- runMRP,updateKanbanJob,upsertJobMethod} from "~/modules/production";+import { releaseJobs } from "~/modules/production/production.server";+import { jobReleaseBlockers } from "~/modules/production/ui/Jobs/job-release-logic";import {insertPurchaseOrder,upsertPurchaseOrderLine@@ -43,6 +44,99 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "kanban");+async function releaseKanbanJob({+ client,+ jobId,+ locationId,+ companyId,+ userId+}: {+ client: SupabaseClient<Database>;+ jobId: string;+ locationId: string;+ companyId: string;+ userId: string;+}): Promise<{ released: boolean; message: string | null }> {+ const job = await client+ .from("job")+ .select("jobId, quantity, scrapQuantity")+ .eq("id", jobId)+ .eq("companyId", companyId)+ .single();+ const readiness = await getJobReleaseReadiness(client, [jobId], companyId);+ const ready = readiness.data?.jobs[0];+ if (job.error || readiness.error || !ready) {+ logger.error("Failed to check a kanban job for release", {+ companyId,+ jobId,+ error: job.error ?? readiness.error+ });+ return {+ released: false,+ message: `${job.data?.jobId ?? "The job"} was created but could not be checked for release. Release it from the job.`+ };+ }++ // No one at a kanban card can choose a purchase order, so unlike bulk+ // release a supplier's Draft PO is reused rather than a blocker.+ const blockers = jobReleaseBlockers(job.data, ready);+ if (blockers.length > 0) {+ return {+ released: false,+ message: `${job.data.jobId} was created but not released: ${blockers.join("; ")}`+ };+ }++ const result = await releaseJobs({+ client,+ db: getDatabaseClient(),+ jobIds: [jobId],+ companyId,+ userId,+ purchaseOrdersBySupplierId: Object.fromEntries(+ (readiness.data?.suppliers ?? []).map((supplier) => [+ supplier.supplierId,+ [...supplier.draftPurchaseOrders].sort((a, b) =>+ b.purchaseOrderId.localeCompare(a.purchaseOrderId)+ )[0]?.id ?? "new"+ ])+ ),+ source: "kanban"+ });+ const released = result.releasedJobIds.includes(jobId);+ if (result.error) {+ logger.error("Failed to release a kanban job", {+ companyId,+ jobId,+ error: result.error+ });+ }++ // After the status is persisted: the scheduler only places released jobs.+ if (released) {+ try {+ await runLocationSchedule({+ db: getDatabaseClient(),+ client,+ locationId,+ companyId,+ userId+ });+ } catch (error) {+ logger.error("Failed to schedule a kanban job", {+ companyId,+ jobId,+ error+ });+ }+ }++ return {+ released,+ message: result.error ? `${job.data.jobId}: ${result.error}` : null+ };+}+async function handleKanban({client,companyId,@@ -55,7 +149,10 @@ async function handleKanban({companyGroupId: string;userId: string;id: string;-}): Promise<{ data: string; error: null } | { data: null; error: string }> {+}): Promise<+ | { data: string; error: null; message?: string }+ | { data: null; error: string }+> {const kanban = await getKanban(client, id, companyId);if (kanban.error || !kanban.data) {@@ -156,49 +253,21 @@ async function handleKanban({};}- if (!upsertMethod.error && kanban.data.autoRelease) {- await Promise.all([- trigger("recalculate", {- type: "jobRequirements",- id,- companyId,- userId- }),- runMRP(serviceRole, getDatabaseClient(), {- type: "job",- id,- companyId,- userId- }),- runLocationSchedule({- db: getDatabaseClient(),- client: serviceRole,- locationId: kanban.data.locationId!,- companyId,- userId- }),- serviceRole- .from("job")- .update({- status: "Ready" as const- })- .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) {+ if (upsertMethod.error) {logger.error("Kanban operation failed", { error: upsertMethod.error });}+ const release =+ !upsertMethod.error && kanban.data.autoRelease+ ? await releaseKanbanJob({+ client: serviceRole,+ jobId: id,+ locationId: kanban.data.locationId!,+ companyId,+ userId+ })+ : { released: false, message: null };+const jobId = id;let redirectUrl = path.to.job(jobId);@@ -208,7 +277,11 @@ async function handleKanban({companyId);- if (operation && kanban.data.autoRelease) {+ if (release.message) {+ return { data: redirectUrl, error: null, message: release.message };+ }++ if (operation && release.released) {let operationId = operation.id;if (kanban.data.autoStartJob) {let setupTime = operation.setupTime;@@ -432,7 +505,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw notFound("id not found");- return await handleKanban({ client, companyId, companyGroupId, userId, id });+ const result = await handleKanban({+ client,+ companyId,+ companyGroupId,+ userId,+ id+ });+ // A redirect, not data(): the root's flash middleware clears a flash set on+ // this request.+ if ("message" in result && result.message && result.data) {+ throw redirect(+ result.data,+ await flash(request, error(null, result.message))+ );+ }+ return result;}export default function KanbanRedirectRoute() {diff --git a/apps/erp/app/routes/api+/kanban.collision.$id.tsx b/apps/erp/app/routes/api+/kanban.collision.$id.tsxindex ee2309e464..c11b06c3e2 100644--- a/apps/erp/app/routes/api+/kanban.collision.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.collision.$id.tsx@@ -64,13 +64,16 @@ export async function action({ request, params }: ActionFunctionArgs) {if (kanbanUpdate.error) {return data({ success: false },- await flash(request, error("Failed to cancel job"))+ await flash(+ request,+ error(kanbanUpdate.error, "Failed to remove the job from the kanban")+ ));}return redirect(path.to.api.kanban(id),- await flash(request, success("Job cancelled"))+ await flash(request, success("Job removed from the kanban")));}diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 423e408dc9..c48847e5db 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -809,7 +809,7 @@{"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},{"name":"production_updateJobOperationStatus","classification":"WRITE","paramCount":2,"schema":"b22654081076","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},{"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobStatus","classification":"WRITE","paramCount":4,"schema":"458fa5786030","response":"8394fbabd845","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJobStatus","classification":"WRITE","paramCount":1,"schema":"b740cf9803af","response":"8394fbabd845","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateKanbanJob","classification":"WRITE","paramCount":2,"schema":"2c22838be2d2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},{"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},diff --git a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx b/apps/erp/app/routes/x+/items+/methods+/version.new.tsxindex 1e470ae6ca..fc1c5d32c1 100644--- a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx@@ -42,9 +42,8 @@ export async function action({ request, params }: ActionFunctionArgs) {// spinning fresh method versions at Done and never stages/reserves a pending// revision, so there is nothing for an open CO to lock against.- // A single Draft version becomes Active as the new one is created. Strict- // backflush refuses that activation the way the Activate action does- // (`convert` methodVersionToActive), before anything is written.+ // Making the current version Active is an activation: refuse it as `convert`+ // does.if (validation.data.activeVersionId) {const db = getDatabaseClient();const { strict } = await getStrictBackflushSettings(db, companyId);diff --git a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsxindex ab9e5f9d42..d7e9d25783 100644--- a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx@@ -96,8 +96,6 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId,error: update.error});- // A refusal the user can fix (strict backflush: a line with no Pull From)- // carries its own message; a data-layer failure arrives with none.return {success: false,message: update.error.message || "Failed to activate method version"diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex 92fb0a3767..562dcc6bee 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -108,9 +108,6 @@ export async function action({ request, params }: ActionFunctionArgs) {}}- // Releasing (the dialog, or a plain post of Ready on a Draft or Planned- // job — the API and MCP path): strict backflush refuses a pulled line with- // no storage unit on every path. Resuming a Paused job is not a release.if (shouldSchedule ||data?.status === "Draft" ||@@ -268,7 +265,15 @@ export async function action({ request, params }: ActionFunctionArgs) {if (update.error) {throw redirect(requestReferrer(request) ?? path.to.job(id),- await flash(request, error(update.error, "Failed to update job status"))+ await flash(+ request,+ error(+ update.error,+ update.error.code === "RELEASE_REFUSED"+ ? update.error.message+ : "Failed to update job status"+ )+ ));}}diff --git a/apps/erp/app/routes/x+/job+/release.tsx b/apps/erp/app/routes/x+/job+/release.tsxindex 4268b601cc..6b926d4bdc 100644--- a/apps/erp/app/routes/x+/job+/release.tsx+++ b/apps/erp/app/routes/x+/job+/release.tsx@@ -12,7 +12,7 @@ import type { ActionFunctionArgs } from "react-router";import { z } from "zod";import { getJobReleaseReadiness } from "~/modules/production";import { releaseJobs } from "~/modules/production/production.server";-import { jobReleaseProblems } from "~/modules/production/ui/Jobs/job-release-logic";+import { jobReleaseBlockers } from "~/modules/production/ui/Jobs/job-release-logic";import { getDatabaseClient } from "~/services/database.server";const logger = getLogger("erp", "job-release");@@ -107,11 +107,7 @@ export async function action({ request }: ActionFunctionArgs) {const ready = readinessByJobId.get(job.id);const problems = ready? [- // The job page disables Release for the same job.- ...(job.quantity === 0 && job.scrapQuantity === 0- ? ["nothing to make"]- : []),- ...jobReleaseProblems(ready),+ ...jobReleaseBlockers(job, ready),...(ready.supplierIds.some((id) =>suppliersWithDraftPurchaseOrders.has(id))diff --git a/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx b/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsxindex b470cfae31..d5d3a222ee 100644--- a/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx+++ b/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx@@ -25,8 +25,6 @@ import { pageInMemory } from "~/utils/query";const logger = getLogger("erp", "settings-items");-// Strict backflush: every open job with a material that has no storage unit,-// searchable and paged — the settings card only counts them.export async function loader({ request }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {view: "settings"diff --git a/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx b/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsxindex 77b13281e8..1d6f59f415 100644--- a/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx+++ b/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx@@ -25,8 +25,6 @@ import { pageInMemory } from "~/utils/query";const logger = getLogger("erp", "settings-items");-// Strict backflush: every Active method with a material that has no Pull From,-// searchable and paged — the settings card only counts them.export async function loader({ request }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {view: "settings"diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsxindex 7cf9cae091..0c6678824f 100644--- a/apps/erp/app/routes/x+/settings+/items.tsx+++ b/apps/erp/app/routes/x+/settings+/items.tsx@@ -70,10 +70,6 @@ export async function loader({ request }: LoaderFunctionArgs) {));- // Strict backflush leaves Active methods and released jobs as they are; the- // card counts the ones with a gap and links to a drawer listing them all.- // `gaps` is null while the setting is off; `gapsError` says the count failed,- // so the card never reads as clean when it could not look.let gaps: { methods: number; jobs: number } | null = null;let gapsError = false;if (companySettings.data.requireBackflushStorageUnit) {@@ -466,9 +462,6 @@ export default function ItemsSettingsRoute() {disabled={isToggling}/></HStack>- {/* Only meaningful under strict backflush: without it a short- bin falls back to another storage unit and never goes- negative from a backflush. */}<HStack className="justify-between items-center w-full border-t pt-4"><VStack className="items-start" spacing={1}><span className="font-medium">@@ -638,8 +631,6 @@ export default function ItemsSettingsRoute() {);}-// One gap in strict backflush coverage: the count, what it means, and a way to-// see every entry (a searchable drawer — a long list does not fit a card).function GapRow({to,label,diff --git a/apps/erp/app/utils/page-in-memory.test.ts b/apps/erp/app/utils/page-in-memory.test.tsindex c3dcb363e7..d2500c4cc5 100644--- a/apps/erp/app/utils/page-in-memory.test.ts+++ b/apps/erp/app/utils/page-in-memory.test.ts@@ -4,8 +4,7 @@import { describe, expect, it, vi } from "vitest";-// @carbon/auth's barrel pulls in a Lingui macro plain vitest cannot run (see-// query.test.ts). Only the URL number parser is used here, so stand it in.+// @carbon/auth's barrel runs a Lingui macro plain vitest cannot (query.test.ts).vi.mock("@carbon/auth", () => ({badRequest: vi.fn(),parseNumberFromUrlParam: (diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.tsindex 8f2f98ba34..28bbf7d20c 100644--- a/apps/erp/app/utils/query.ts+++ b/apps/erp/app/utils/query.ts@@ -259,12 +259,7 @@ export const filterOperatorLabels = Object.entries(filterOperators).map(}));-/**- * Search, sort and page a list held in memory, honouring the shared `Table`'s- * URL parameters (`search`, `sort`, `limit`, `offset`). For lists computed in- * TypeScript from a whole-company read (the strict backflush drawers), where- * PostgREST cannot do the paging. Array values sort by their first entry.- */+// Array values sort by their first entry.export function pageInMemory<T extends Record<string, unknown>>(rows: T[],searchParams: URLSearchParams,diff --git a/apps/erp/test/job-release-logic.test.ts b/apps/erp/test/job-release-logic.test.tsindex 88ed3667ee..d8b6bf5662 100644--- a/apps/erp/test/job-release-logic.test.ts+++ b/apps/erp/test/job-release-logic.test.ts@@ -4,6 +4,7 @@import { describe, expect, it } from "vitest";import {+ jobReleaseBlockers,jobReleaseProblems,materialsWithoutStorageUnit,makeMethodsMissingOperations,@@ -144,6 +145,48 @@ describe("jobReleaseProblems", () => {});});+describe("jobReleaseBlockers", () => {+ const ready = {+ manufacturingBlocked: false,+ missingAssemblies: [],+ outsideOperationsWithoutSupplier: [],+ materialsWithoutStorageUnit: []+ };++ it("lets a job with something to make and nothing to fix through", () => {+ expect(jobReleaseBlockers({ quantity: 30, scrapQuantity: 0 }, ready)).toEqual(+ []+ );+ });++ it("refuses a job with nothing to make", () => {+ expect(jobReleaseBlockers({ quantity: 0, scrapQuantity: 0 }, ready)).toEqual([+ "nothing to make"+ ]);+ expect(+ jobReleaseBlockers({ quantity: null, scrapQuantity: null }, ready)+ ).toEqual(["nothing to make"]);+ });++ it("lets a scrap-only job through", () => {+ expect(jobReleaseBlockers({ quantity: 0, scrapQuantity: 2 }, ready)).toEqual(+ []+ );+ });++ it("adds every release problem after it, including a missing storage unit", () => {+ expect(+ jobReleaseBlockers(+ { quantity: 0, scrapQuantity: 0 },+ { ...ready, materialsWithoutStorageUnit: [{ description: "MAT-KAPTON" }] }+ )+ ).toEqual([+ "nothing to make",+ "set a Pull From storage unit on MAT-KAPTON"+ ]);+ });+});+describe("jobReleaseProblems with a long BoM", () => {it("names the first five parts and counts the rest", () => {expect(diff --git a/apps/erp/test/job-release-readiness.test.ts b/apps/erp/test/job-release-readiness.test.tsindex 5a87fcfad8..ee2575b5c0 100644--- a/apps/erp/test/job-release-readiness.test.ts+++ b/apps/erp/test/job-release-readiness.test.ts@@ -128,9 +128,7 @@ describe("getJobReleaseReadiness", () => {]);});- // `location` holds the locations the client returns as pull-from locations- // (an active work center and storage unit); the stand-in does not evaluate- // the embedded filters, so the table lists only those.+ // `location`: the pull-from locations (the stand-in ignores embed filters).function strictReadinessTables(pullFromLocationIds: string[]) {const line = {jobId: "job-1",@@ -165,7 +163,6 @@ describe("getJobReleaseReadiness", () => {readableIdWithRevision: "BOLT-10"}},- // Built in the job, not pulled.{...line,id: "jm-sub",@@ -173,7 +170,6 @@ describe("getJobReleaseReadiness", () => {description: "Bracket",item: { itemTrackingType: "Inventory", readableIdWithRevision: "B-1" }},- // Holds no stock, so nothing is backflushed.{...line,id: "jm-labor",@@ -203,7 +199,6 @@ describe("getJobReleaseReadiness", () => {});it("skips a job at a location with no active work center or storage unit", async () => {- // Activation never asked for a Pull From there, so release must not.const { client } = cappedClient(strictReadinessTables([]));const { data, error } = await getJobReleaseReadiness(diff --git a/apps/erp/test/job-status-guard.test.ts b/apps/erp/test/job-status-guard.test.tsindex ff574e3b10..34cc04e5ea 100644--- a/apps/erp/test/job-status-guard.test.ts+++ b/apps/erp/test/job-status-guard.test.ts@@ -15,7 +15,7 @@ vi.mock("@carbon/lib/telemetry", () => ({}));import { raiseMoment } from "@carbon/lib/workflows";-import { updateJobStatus } from "../app/modules/production/production.service";+import { writeJobStatus } from "../app/modules/production/production.service";// A job row behind a chainable client stand-in. The UPDATE applies its `in`// filter on the status, as the database would, and returns the rows it changed.@@ -46,7 +46,7 @@ function clientWith(job: { id: string; status: string }) {}const release = (client: any) =>- updateJobStatus(client, {+ writeJobStatus(client, {id: "job-1",companyId: "company-1",status: "Ready",@@ -56,7 +56,7 @@ const release = (client: any) =>beforeEach(() => vi.clearAllMocks());-describe("updateJobStatus with fromStatuses", () => {+describe("writeJobStatus with fromStatuses", () => {it("flips a job that is still waiting for release", async () => {const { client, calls } = clientWith({ id: "job-1", status: "Planned" });const result = await release(client);@@ -75,7 +75,7 @@ describe("updateJobStatus with fromStatuses", () => {it("flips without a guard when no statuses are given", async () => {const { client, calls } = clientWith({ id: "job-1", status: "Cancelled" });- const result = await updateJobStatus(client, {+ const result = await writeJobStatus(client, {id: "job-1",companyId: "company-1",status: "Ready",diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.tsindex 4f3e2182c0..2c9d5a39c8 100644--- a/apps/erp/test/release-jobs.test.ts+++ b/apps/erp/test/release-jobs.test.ts@@ -32,13 +32,13 @@ vi.mock("../app/modules/production/production.service", () => ({getJobReleaseReadiness: vi.fn(),recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),runMRP: vi.fn(async () => ({ data: null, error: null })),- updateJobStatus: vi.fn(async () => ({ error: null, updated: true }))+ writeJobStatus: vi.fn(async () => ({ error: null, updated: true }))}));import {recalculateJobRequirements,runMRP,- updateJobStatus+ writeJobStatus} from "../app/modules/production/production.service";import {planDraftJob,@@ -81,7 +81,7 @@ describe("releaseJobs", () => {});it("flips only a job still Draft or Planned, and stops when it is not", async () => {- vi.mocked(updateJobStatus).mockResolvedValueOnce({+ vi.mocked(writeJobStatus).mockResolvedValueOnce({error: null,updated: false} as any);@@ -89,7 +89,7 @@ describe("releaseJobs", () => {"job-1","job-2"]);- expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({+ expect(vi.mocked(writeJobStatus).mock.calls[0]?.[1]).toMatchObject({status: "Ready",fromStatuses: ["Draft", "Planned"]});@@ -130,7 +130,7 @@ describe("planDraftJob", () => {order.push("recalculate");return { data: null, error: null } as any;});- vi.mocked(updateJobStatus).mockImplementationOnce(async () => {+ vi.mocked(writeJobStatus).mockImplementationOnce(async () => {order.push("flip");return { error: null, updated: true } as any;});@@ -141,7 +141,7 @@ describe("planDraftJob", () => {expect(await plan()).toEqual({ updated: true });expect(order).toEqual(["recalculate", "flip", "mrp"]);- expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({+ expect(vi.mocked(writeJobStatus).mock.calls[0]?.[1]).toMatchObject({status: "Planned",fromStatuses: ["Draft"]});@@ -156,12 +156,12 @@ describe("planDraftJob", () => {const result = await plan();expect(result.updated).toBe(false);expect(result.error).toBeTruthy();- expect(updateJobStatus).not.toHaveBeenCalled();+ expect(writeJobStatus).not.toHaveBeenCalled();expect(runMRP).not.toHaveBeenCalled();});it("runs no MRP when the job is no longer Draft", async () => {- vi.mocked(updateJobStatus).mockResolvedValueOnce({+ vi.mocked(writeJobStatus).mockResolvedValueOnce({error: null,updated: false} as any);diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsxindex 68ef7371e9..d3ba3e0542 100644--- a/apps/mes/app/routes/x+/complete.tsx+++ b/apps/mes/app/routes/x+/complete.tsx@@ -191,8 +191,6 @@ export async function action({ request }: ActionFunctionArgs) {const newTrackedEntityId = response.data?.newTrackedEntityId as| string| undefined;- // A refused completion (a strict backflush shortfall) rolled back: print- // nothing for it.if (response.error) {return data({},@@ -335,9 +333,6 @@ export async function action({ request }: ActionFunctionArgs) {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migrationconst { trackedEntityId, trackingType, ...d } = validation.data;- // Strict backflush: refuse before the production quantity is recorded, so- // a short storage unit never leaves units completed with no material- // consumed. A no-op when strict backflush is off.const check = await checkStrictBackflush({jobOperationId: validation.data.jobOperationId,quantity: validation.data.quantity,@@ -383,8 +378,6 @@ export async function action({ request }: ActionFunctionArgs) {});if (issued.error) {- // The units are recorded: say so, or the operator retries and records- // them twice.return data({},await flash(request, {diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxindex c7b119bb22..36c48faaa5 100644--- a/apps/mes/app/routes/x+/end.$operationId.tsx+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -296,9 +296,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}} else {- // Strict backflush: refuse before the production quantity is recorded,- // so a short storage unit never leaves units completed with no material- // consumed. A no-op when strict backflush is off.const check = await checkStrictBackflush({jobOperationId: operationId,quantity: quantityToComplete,@@ -350,8 +347,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {});if (issued.error) {- // The units are recorded: say so, or the operator retries and records- // them twice.return redirect(path.to.operation(operationId),await flash(request, {diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsxindex e3829a17f0..76e017ba96 100644--- a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx@@ -107,8 +107,6 @@ export async function action({ request, params }: ActionFunctionArgs) {`Passed units (${candidates.length}) exceed the operation's remaining quantity (${state.opRemaining}) — quantities were already recorded from the actions menu`);}- // Strict backflush: refuse before the first unit completes, not after- // some of them.const backflushCheck = await checkStrictBackflush({jobOperationId: state.jobOperationId,quantity: candidates.length,@@ -157,7 +155,6 @@ export async function action({ request, params }: ActionFunctionArgs) {return fail(null, "No passed units to complete");}- // Strict backflush: refuse before the production quantity is recorded.const backflushCheck = await checkStrictBackflush({jobOperationId: state.jobOperationId,quantity,diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsxindex 4d73b41f29..4bdfba6640 100644--- a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx+++ b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx@@ -208,9 +208,8 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- // Strict backflush: completion and scrap both backflush the operation's- // materials. Refuse before the lot closes — a closed lot cannot be- // dispositioned again, so a refusal after it would strand the units.+ // Strict backflush: refuse before the lot closes; a closed lot cannot be+ // dispositioned again.const backflushCheck = await checkStrictBackflush({jobOperationId: state.jobOperationId,quantity: completionQuantity + (scrapReasonId ? scrapTotal : 0),diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex fd34aa16be..4d7d4851ac 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -1551,8 +1551,6 @@ export async function backflushUntrackedMaterialsOnStepRecord(quantity: delta,adjustmentType: "Negative Adjmt."});- // The server's refusal (strict backflush names the part and the storage- // unit) says more than the bare item id.if (issued.error) failures.push(issued.error.message || material.itemId);}diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.tsindex 59b7636493..53853069d5 100644--- a/apps/mes/app/services/quality.server.ts+++ b/apps/mes/app/services/quality.server.ts@@ -608,8 +608,6 @@ export async function postBulkCompletion(quantity: args.quantity});if (issued.error) {- // The units are recorded: say so, or the operator retries and records- // them twice.return {error: issued.error,message: `Units completed, but ${issued.error.message || "failed to issue materials"}`@@ -619,13 +617,8 @@ export async function postBulkCompletion(return { error: null, message: null };}-/**- * Strict backflush: whether the operation's materials can be backflushed for- * `quantity` units — a dry run of `issue` `jobOperation`, rolled back. Call it- * before the first write of a completion (closing a lot, recording units), so a- * short storage unit refuses the whole action instead of leaving it half done.- * A no-op when strict backflush is off.- */+/** Strict backflush dry run of the operation's backflush. Call it before a+ * completion's first write; a no-op when the setting is off. */export async function checkStrictBackflush(args: {jobOperationId: string;quantity: number;diff --git a/packages/database/src/strict-backflush.test.ts b/packages/database/src/strict-backflush.test.tsindex e764cc22a5..1ea29557f7 100644--- a/packages/database/src/strict-backflush.test.ts+++ b/packages/database/src/strict-backflush.test.ts@@ -177,7 +177,6 @@ describe("pullFromStorageUnit", () => {describe("strictBackflushLockKey", () => {it("is the key SQL backflush_job_materials builds", () => {- // 'strict-backflush:' || company || ':' || bin || ':' || itemexpect(strictBackflushLockKey("CO", "BIN", "ITEM")).toBe("strict-backflush:CO:BIN:ITEM");diff --git a/packages/database/src/strict-backflush.ts b/packages/database/src/strict-backflush.tsindex 1ed5fefe90..51fc67285d 100644--- a/packages/database/src/strict-backflush.ts+++ b/packages/database/src/strict-backflush.ts@@ -2,18 +2,9 @@// 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.-// Strict backflush (companySettings.requireBackflushStorageUnit,-// .ai/specs/2026-10-14-strict-backflush.md). One rule for "which material-// lines must name a Pull From storage unit", read by method activation-// (`convert`), job release and the Settings → Items card, so the three can-// never disagree about which lines count. The backflush reads the location-// test, the Pull From of a picked line and the lock key from here too.-import type { Kysely, KyselyDatabase } from "./client.ts";import { round } from "./precision.ts";-// The item types a backflush consumes (`issueJobOperationMaterials`, SQL-// `backflush_job_materials`). Tools and services are never consumed.export const PULLED_ITEM_TYPES = ["Material", "Part", "Consumable"] as const;export type PullFromLine = {@@ -22,11 +13,7 @@ export type PullFromLine = {itemTrackingType: string | null;};-// A line is pulled from a bin when it is not built in the job (Make to Order)-// and its item holds stock. Purchase to Order lines count: the goods are-// received into a bin and backflushed from it. Batch and serial lines count-// too — the operator scans the unit, but planning and picking still read the-// line's bin.+// Purchase to Order, batch and serial lines count: each is consumed from a bin.export function needsPullFrom(line: PullFromLine): boolean {if (line.methodType === "Make to Order") return false;if (@@ -38,9 +25,7 @@ export function needsPullFrom(line: PullFromLine): boolean {return line.itemTrackingType !== "Non-Inventory";}-// `methodMaterial.storageUnitIds` maps locationId → storageUnitId. An empty-// string is what the BoM editor writes when a bin is cleared, so it counts as-// missing.+// The BoM editor writes an empty string when a bin is cleared.export function missingPullFromLocations(storageUnitIds: unknown,locationIds: readonly string[]@@ -55,11 +40,8 @@ export function missingPullFromLocations(});}-// The locations a pulled line needs a Pull From at: each one with an active-// work center AND an active storage unit. A location with no work center-// builds nothing; one with no storage unit has no bin a line could name (a-// test lab at head office), so requiring one there would block activation-// for good.+// An active work center AND an active storage unit: a location with no storage+// unit has no bin a line could name.function pullFromLocations(db: Kysely<KyselyDatabase>, companyId: string) {return db.selectFrom("location")@@ -96,9 +78,6 @@ export async function getPullFromLocations(.execute();}-// Whether strict backflush applies at a job's location. Activation exempts-// the other locations, so a backflush there must not refuse a line for a bin-// it could never name.export async function isPullFromLocation(db: Kysely<KyselyDatabase>,companyId: string,@@ -113,16 +92,11 @@ export async function isPullFromLocation(export type StrictBackflushSettings = {strict: boolean;- /** Only meaningful while `strict`: refuse a short bin instead of letting it- * go negative. */preventNegative: boolean;};-/**- * The company's strict backflush settings. With `locationId`, `strict` is also- * false at a location `getPullFromLocations` leaves out (no active work center- * or no active storage unit): activation never asked for a Pull From there.- */+/** With `locationId`, `strict` is false at a location `getPullFromLocations`+ * leaves out. */export async function getStrictBackflushSettings(db: Kysely<KyselyDatabase>,companyId: string,@@ -142,20 +116,14 @@ export async function getStrictBackflushSettings(};}-/**- * The parts of a make method that block its activation: pulled, stocked lines- * with no Pull From at one of `getPullFromLocations`. One entry per part — the- * refusal names what to fix, not where. Read by the `convert` activation and- * the New Version route.- */export async function getMethodPartsMissingPullFrom(db: Kysely<KyselyDatabase>,args: { makeMethodId: string; companyId: string }): Promise<string[]> {const { makeMethodId, companyId } = args;- // Two awaits, not `inOrder`: this module is bundled for the browser (the BoM- // badges read `needsPullFrom`), and `./rows` brings the Kysely runtime.+ // Not `inOrder`: this module is bundled for the browser, and `./rows` brings+ // the Kysely runtime.const lines = await db.selectFrom("methodMaterial").innerJoin("item", "item.id", "methodMaterial.itemId")@@ -199,13 +167,9 @@ export type PickLineBins = {toStorageUnitId: string | null;};-// The Pull From of a job material line. Posting a pick points the line at the-// lineside bin it was picked to (`pointJobMaterialAtLineside`), so after a pick-// `storageUnitId` no longer names the Pull From. The pick line still holds it:-// the picking list generator sources a line from its Pull From. `pickLines`-// must be oldest first — a later list for the same line is generated after the-// pointer moved, and sources from the fullest warehouse bin instead. SQL-// `backflush_job_materials` resolves the same way.+// A pick points the line at lineside, so its Pull From is the source of its+// oldest pick line into that bin (a later list sources from the fullest bin).+// `pickLines` must be oldest first. SQL `backflush_job_materials` matches.export function pullFromStorageUnit(storageUnitId: string | null,pickLines: readonly PickLineBins[]@@ -220,9 +184,7 @@ export function pullFromStorageUnit(return pick?.storageUnitId ?? storageUnitId;}-// The advisory lock key for strict draws on one bin and item. SQL-// `backflush_job_materials` builds the same string; both lock with-// `pg_advisory_xact_lock(hashtextextended(key, 0))`.+// SQL `backflush_job_materials` builds the same key.export function strictBackflushLockKey(companyId: string,storageUnitId: string,@@ -231,9 +193,6 @@ export function strictBackflushLockKey(return `strict-backflush:${companyId}:${storageUnitId}:${itemId}`;}-// A refusal is shown as a toast, so it names only the first `limit` entries and-// counts the rest. A 20-line BoM otherwise produced a 900-character toast that-// ran off the screen and faded before it could be read.export const MESSAGE_LIST_LIMIT = 5;export function summarizeList(@@ -244,9 +203,7 @@ export function summarizeList(return `${entries.slice(0, limit).join("; ")}; and ${entries.length - limit} more`;}-// What the bin cannot cover. `alreadyDrawn` is what earlier rows of the same-// backflush take from this bin before they are written, so two materials of-// one operation sharing a bin cannot both count the same stock.+// `alreadyDrawn`: what earlier, unwritten rows of this backflush take from the bin.export function binShortfall({onHand,alreadyDrawn,diff --git a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql b/packages/database/supabase/migrations/20261015163040_strict-backflush.sqlindex f2e469a237..93d1abfb77 100644--- a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql+++ b/packages/database/supabase/migrations/20261015163040_strict-backflush.sql@@ -1,16 +1,8 @@-- Strict backflush (.ai/specs/2026-10-14-strict-backflush.md).----- companySettings.requireBackflushStorageUnit turns it on (off by default).--- companySettings.preventNegativeBackflush (on by default) decides what a--- short bin does under it: refuse, or let the bin go negative.--- backflush_job_materials is copied from its live definition--- (20261009010412_job-costing-always-post.sql) with one change: when strict--- backflush is on at the job's location, a stocked material is consumed only--- from its Pull From — a missing bin raises, and a short bin raises only while--- preventNegativeBackflush is on — instead of falling back to the pick--- method's bin or the fullest bin. A picked line is drawn from its lineside--- bin first and the rest from its Pull From. With strict backflush off the--- function is unchanged.+-- backflush_job_materials is copied from+-- 20261009010412_job-costing-always-post.sql; with strict backflush off it is+-- unchanged.ALTER TABLE "companySettings"ADD COLUMN IF NOT EXISTS "requireBackflushStorageUnit" BOOLEAN NOT NULL DEFAULT false;@@ -93,10 +85,6 @@ BEGINv_ratio := p_quantity_complete / v_job_quantity;- -- Strict backflush (.ai/specs/2026-10-14-strict-backflush.md): a stocked- -- material is consumed only from its own storage unit. A short bin refuses- -- the whole completion while preventNegativeBackflush is on; with it off the- -- bin is drawn below zero instead of drawing from another bin.SELECT COALESCE("requireBackflushStorageUnit", false),COALESCE("preventNegativeBackflush", true)INTO v_strict, v_prevent_negative@@ -105,9 +93,7 @@ BEGINv_strict := COALESCE(v_strict, false);v_prevent_negative := COALESCE(v_prevent_negative, true);- -- Strict backflush applies only where activation asks for a Pull From: a- -- location with an active work center and an active storage unit- -- (getPullFromLocations in @carbon/database/strict-backflush).+ -- Only where activation asks for a Pull From (getPullFromLocations).v_strict := v_strictAND EXISTS (SELECT 1 FROM "workCenter"@@ -122,10 +108,8 @@ BEGINAND active = true);- -- Lock every Pull From this completion may draw, in one order (by key hash),- -- before the first draw: two completions drawing the same bins then cannot- -- deadlock. lockStrictBins in @carbon/server-functions locks in the same- -- order with the same keys.+ -- Lock in key-hash order before the first draw, as lockStrictBins does, so+ -- two completions cannot deadlock.IF v_strict AND v_prevent_negative THENFOR v_lock_key INSELECT DISTINCT hashtextextended(@@ -187,8 +171,6 @@ BEGINIF v_strict AND COALESCE(v_material."itemTrackingType", 'Inventory') <> 'Non-Inventory' THENv_issue_total := v_material_qty_to_issue;- -- Every material the bins cannot cover is collected and refused together- -- after the loop, so the material controller sees them all at once.IF v_material."storageUnitId" IS NULL THENv_strict_problems := v_strict_problems || format('%s has no Pull From storage unit on job %s',@@ -197,9 +179,8 @@ BEGINCONTINUE;END IF;- -- A pick points the line at the lineside bin it was picked to. The- -- oldest pick line into that bin still names the Pull From- -- (pullFromStorageUnit in @carbon/database/strict-backflush).+ -- A pick points the line at lineside; the oldest pick line into it names+ -- the Pull From (pullFromStorageUnit).v_pull_from := COALESCE((SELECT pll."storageUnitId"FROM "pickingListLine" pll@@ -212,8 +193,6 @@ BEGINLIMIT 1), v_material."storageUnitId");- -- A picked line: what was picked is drawn from lineside first, up to- -- what the bin holds.IF v_pull_from <> v_material."storageUnitId" THENSELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_handFROM "itemLedger"@@ -243,12 +222,8 @@ BEGINEND IF;END IF;- -- The rest comes from the Pull From only. A short Pull From is refused- -- only while negative stock is prevented; with it allowed, the material- -- is drawn from its Pull From even below zero. A refused material still- -- writes its row below (the function raises before anything commits),- -- so a later material on the same bin counts this need too. The lock- -- was taken before the loop.+ -- A refused material still writes its row (the function raises before+ -- commit), so a later material on the bin counts this need.v_material_storage_unit_id := v_pull_from;IF v_material_qty_to_issue > 0 AND v_prevent_negative THEN@@ -276,7 +251,7 @@ BEGINEND IF;END IF;ELSE- -- Resolve storage unit (strict backflush off: the pre-existing fallbacks)+ -- Resolve storage unitv_material_storage_unit_id := v_material."storageUnitId";IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN@@ -329,7 +304,6 @@ BEGINv_issue_total := v_material_qty_to_issue;END IF;- -- Strict: a picked line can be covered by lineside alone.IF v_material_qty_to_issue > 0 THENINSERT INTO "itemLedger" ("entryType", "documentType", "documentId", "companyId",@@ -350,9 +324,6 @@ BEGINWHERE id = v_material.id;END LOOP;- -- The refusal is shown as a toast: name the first three shortfalls and- -- count the rest (strictBackflushRefusal in @carbon/server-functions does- -- the same), so a long BoM cannot produce a wall of text.IF array_length(v_strict_problems, 1) > 3 THENRAISE EXCEPTION '%; and % more',array_to_string(v_strict_problems[1:3], '; '),diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex b186cb625c..f08c0e9e2e 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -2,7 +2,7 @@// 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 { writeFileSync } from "node:fs";+import { rmSync, writeFileSync } from "node:fs";import { box, intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { type ExecaChildProcess, execa } from "execa";@@ -43,6 +43,7 @@ import {} from "../services/compose.js";import {activityFile,+ asleepFile,stackStateDir,startWaker,watchIdle@@ -323,6 +324,9 @@ export async function up(opts: UpOpts = {}) {// one under --borrow, whose own `crbn up` does the hibernating.const stateDir = stackStateDir(borrowSlug ?? slug);process.env.CRBN_STACK_STATE = stateDir;+ // The stack is awake. `--no-hibernate` never runs `watchIdle`, which clears a+ // stale marker that would hold every request for 120 s.+ if (!borrowSlug) rmSync(asleepFile(stateDir), { force: true });const idleMinutes = Number(process.env.CRBN_IDLE_MINUTES ?? 30);const hibernates =opts.hibernate !== false &&diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex b4a92c8afd..ad6932127b 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -5,7 +5,7 @@"sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-16T06:58:25.255Z",+ "exportedAt": "2026-10-18T19:57:20.747Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",diff --git a/packages/server-functions/src/batch-operations/index.ts b/packages/server-functions/src/batch-operations/index.tsindex 193e06293c..d14a38b986 100644--- a/packages/server-functions/src/batch-operations/index.ts+++ b/packages/server-functions/src/batch-operations/index.ts@@ -457,13 +457,9 @@ async function completeBatch(// inside the transaction: freshly sliced on the first attempt, re-loaded on resume.let glEvents: { id: string; postedToGL: boolean }[] = [];- // Strict backflush: phase 2 issues each member's materials after phase 1 has- // committed, so a short storage unit is refused here first, before anything- // is written. Each member is checked on its own; two members drawing the- // same bin can still fail in phase 2, which leaves the batch resumable.- // A no-op when strict backflush is off.- // A completed batch skips the check, so a retry still gets the- // "already completed" answer from the transaction below.+ // Strict backflush: refuse before phase 1 writes, since phase 2 issues after+ // it commits. A completed batch skips this, so a retry still gets the+ // "already completed" answer.const batchStatus = await db.selectFrom("jobOperationBatch").select("status")@@ -743,9 +739,7 @@ async function completeBatch(quantity: m.quantity});if (issued.error) {- // Keep the refusal's status: a strict backflush shortfall is a 409 the- // operator fixes by stocking the bin and completing again (which- // resumes), not a server error.+ // Keep a strict backflush refusal's 409; completing again resumes.throw new ServerFnError(`Failed to issue materials for operation ${m.jobOperationId}: ${issued.error.message}`,issued.error instanceof ServerFnError ? issued.error.status : 500diff --git a/packages/server-functions/src/get-method/index.ts b/packages/server-functions/src/get-method/index.tsindex 28e00bc9c7..9c0f371c72 100644--- a/packages/server-functions/src/get-method/index.ts+++ b/packages/server-functions/src/get-method/index.ts@@ -31,6 +31,7 @@ import {getNextRevisionSequence,getNextSequence} from "@carbon/database/sequence";+import { getStrictBackflushSettings } from "@carbon/database/strict-backflush";import {buildConsumeFirstHops,buildConsumeFirstRules,@@ -623,6 +624,13 @@ const getMethod = defineServerFn({const scrapPercentageByItemId = new Map<string, number>();const defaultStorageUnitByItemId = new Map<string, string>();const jobLocationId = job.locationId;+ let fullestBinAllowed: boolean | undefined;+ async function withFullestBin(reader: typeof db) {+ fullestBinAllowed ??= !(+ await getStrictBackflushSettings(reader, companyId, jobLocationId)+ ).strict;+ return fullestBinAllowed;+ }const operationsByMakeMethodId = new Map<string,@@ -671,22 +679,24 @@ const getMethod = defineServerFn({// Default storage units at the job's location — two set-based// queries instead of up to two per material (getStorageUnitId):// pickMethod default wins, else the bin with the highest on-hand- // quantity.+ // quantity — never the fullest bin under strict backflush.if (jobLocationId) {- const ledgerTotals = await reader- .selectFrom("itemLedger")- .where("locationId", "=", jobLocationId)- .where("companyId", "=", companyId)- .where("itemId", "in", missing)- .where("storageUnitId", "is not", null)- .groupBy(["itemId", "storageUnitId"])- .select([- "itemId",- "storageUnitId",- (eb) => eb.fn.sum("quantity").as("totalQuantity")- ])- .having((eb) => eb.fn.sum("quantity"), ">", 0)- .execute();+ const ledgerTotals = !(await withFullestBin(reader))+ ? []+ : await reader+ .selectFrom("itemLedger")+ .where("locationId", "=", jobLocationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("storageUnitId", "is not", null)+ .groupBy(["itemId", "storageUnitId"])+ .select([+ "itemId",+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity")+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .execute();const bestQuantityByItemId = new Map<string, number>();for (const row of ledgerTotals) {@@ -8332,6 +8342,7 @@ function createItemDefaults(const scrapByItemId = new Map<string, number>();const binByItemId = new Map<string, string>();const loaded = new Set<string>();+ let fullestBinAllowed: boolean | undefined;async function load(reader: Kysely<KyselyDatabase>,@@ -8352,25 +8363,31 @@ function createItemDefaults(scrapByItemId.set(row.itemId, Number(row.scrapPercentage ?? 0));}- // The pick method's default bin wins, else the bin holding the most.+ // The pick method's default bin wins, else the bin holding the most (never+ // under strict backflush).if (locationId) {- const ledgerTotals = await reader- .selectFrom("itemLedger")- .where("locationId", "=", locationId)- .where("companyId", "=", companyId)- .where("itemId", "in", missing)- .where("storageUnitId", "is not", null)- .groupBy(["itemId", "storageUnitId"])- .select([- "itemId",- "storageUnitId",- (eb) => eb.fn.sum("quantity").as("totalQuantity")- ])- .having((eb) => eb.fn.sum("quantity"), ">", 0)- .orderBy("itemId")- .orderBy("totalQuantity", "desc")- .orderBy("storageUnitId")- .execute();+ fullestBinAllowed ??= !(+ await getStrictBackflushSettings(reader, companyId, locationId)+ ).strict;+ const ledgerTotals = !fullestBinAllowed+ ? []+ : await reader+ .selectFrom("itemLedger")+ .where("locationId", "=", locationId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", missing)+ .where("storageUnitId", "is not", null)+ .groupBy(["itemId", "storageUnitId"])+ .select([+ "itemId",+ "storageUnitId",+ (eb) => eb.fn.sum("quantity").as("totalQuantity")+ ])+ .having((eb) => eb.fn.sum("quantity"), ">", 0)+ .orderBy("itemId")+ .orderBy("totalQuantity", "desc")+ .orderBy("storageUnitId")+ .execute();for (const row of ledgerTotals) {// Ordered by quantity: the first row for an item is its fullest bin.if (row.storageUnitId && !binByItemId.has(row.itemId)) {diff --git a/packages/server-functions/src/issue/index.ts b/packages/server-functions/src/issue/index.tsindex 32f301a6e1..ab83a5b187 100644--- a/packages/server-functions/src/issue/index.ts+++ b/packages/server-functions/src/issue/index.ts@@ -149,8 +149,7 @@ async function issueJobOperationMaterials(accountDefaults: ConsumeAccountDefaults;dimensionMap: Map<string, string>;db: Kysely<KyselyDatabase>;- // Stop after the strict backflush check: throw DryRunRollback before any- // ledger, cost or journal row is built (the caller rolls back).+ // Throw DryRunRollback after the strict check, before any ledger row.dryRun?: boolean;}) {@@ -243,8 +242,6 @@ async function issueJobOperationMaterials(companyId,job.locationId);- // Strict backflush: what no pick covers comes from each material's Pull- // From, and every material the bins cannot cover is refused together.const pullFrom = strict? await resolvePullFromStorageUnits(trx, companyId, materialsToIssue): new Map<string, string | null>();@@ -314,9 +311,6 @@ async function issueJobOperationMaterials(}if (remaining > 0 && strict && itemIdIsTracked.get(material.itemId)) {- // Strict backflush: what no pick covered comes from the material's own- // storage unit only — no pick-method bin, no fullest bin — and a- // missing or short bin refuses the whole completion.const storageUnitId = pullFrom.get(material.id) ?? null;const problem = await binCoverProblem(trx, {companyId,@@ -329,8 +323,7 @@ async function issueJobOperationMaterials(jobReadableId: job.jobId});if (problem) strictProblems.push(problem);- // Kept even when refused: a later material on the same bin then counts- // this need, so the refusal names every shortfall at once.+ // Kept when refused, so a later material on the bin counts this need.itemLedgerInserts.push({entryType: "Consumption",documentType: "Job Consumption",@@ -434,8 +427,6 @@ async function issueJobOperationMaterials(.execute();}- // Nothing above is committed until the transaction ends, so throwing here- // rolls back every row this call wrote.if (strictProblems.length > 0) throw strictBackflushRefusal(strictProblems);if (dryRun) throw new DryRunRollback();@@ -973,7 +964,6 @@ const logger = getLogger("server-functions", "issue");type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];-// Thrown at the end of a dry-run transaction so Kysely rolls every write back.class DryRunRollback extends Error {}/** Each `type` adds its own fields (`newTrackedEntityId`, `readableId`, …). */@@ -998,9 +988,6 @@ export const issueInput = z.discriminatedUnion("type", [type: z.literal("jobOperation"),quantity: z.number(),id: z.string(),- // Strict backflush: run the issue and roll it back, so a caller that- // records the production quantity first can refuse before it writes- // anything. A no-op when strict backflush is off.dryRun: z.boolean().optional()}),z.object({@@ -3111,9 +3098,6 @@ const issue = defineServerFn({}}if (item?.itemTrackingType === "Inventory" && remaining !== 0) {- // Strict backflush: a consuming issue takes what no pick- // covered from the material's own storage unit only. A return- // keeps the bin chosen above.const strictSettings =adjustmentType !== "Positive Adjmt." && remaining > 0? await getStrictBackflushSettings(diff --git a/packages/server-functions/src/lib/strict-backflush.ts b/packages/server-functions/src/lib/strict-backflush.tsindex 5eebb7e8aa..de1edf9185 100644--- a/packages/server-functions/src/lib/strict-backflush.ts+++ b/packages/server-functions/src/lib/strict-backflush.ts@@ -2,12 +2,7 @@// 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.-// Strict backflush (companySettings.requireBackflushStorageUnit,-// .ai/specs/2026-10-14-strict-backflush.md): a stocked material is consumed-// only from its own storage unit, never another bin. A missing bin refuses the-// backflush; a short bin refuses it only while preventNegativeBackflush is on —-// with it off the bin is drawn below zero. The SQL job-completion backflush-// (`backflush_job_materials`) enforces the same rules.+// SQL `backflush_job_materials` mirrors these rules.import type { Database } from "@carbon/database";import type { KyselyDatabase as DB } from "@carbon/database/client";@@ -46,21 +41,13 @@ type BinCoverArgs = {companyId: string;itemId: string;locationId: string;- /** The material's Pull From (`resolvePullFromStorageUnits`). */storageUnitId: string | null | undefined;quantity: number;plannedRows: LedgerInsert[];- /** Refuse a short bin (true) or let it go negative (false). */preventNegative: boolean;- /** The job's readable id, for the missing-bin message. */jobReadableId: string;};-/**- * The Pull From of each material, by job material id. A pick points a line at- * lineside; `pullFromStorageUnit` recovers the bin it was picked from, so what- * no pick covered still comes from the Pull From.- */export async function resolvePullFromStorageUnits(db: Kysely<DB>,companyId: string,@@ -90,12 +77,8 @@ export async function resolvePullFromStorageUnits();}-/**- * Takes the strict lock of every (bin, item) pair for the rest of the- * caller's transaction, in one fixed order (by key hash), so two completions- * drawing the same pairs cannot deadlock. SQL `backflush_job_materials` locks- * in the same order. Locks are re-entrant, so taking one twice is harmless.- */+/** Locks every (bin, item) pair in key-hash order, as the SQL does, so two+ * completions cannot deadlock. */export async function lockStrictBins(db: Kysely<DB>,companyId: string,@@ -116,11 +99,7 @@ export async function lockStrictBins();}-/**- * Refuses (409) when `storageUnitId` is missing or cannot cover `quantity`.- * `plannedRows` are the ledger rows this backflush has built but not yet- * written — their draws on the same item and bin are subtracted first.- */+/** `plannedRows`: ledger rows built but not yet written. */export async function assertBinCovers(db: Kysely<DB>,args: BinCoverArgs@@ -129,13 +108,8 @@ export async function assertBinCovers(if (problem) throw strictBackflushRefusal([problem]);}-// A shortfall reads "Not enough X in BIN: need n, have m" — long enough that-// three of them fill a toast.const SHORTFALLS_SHOWN = 3;-/** One refusal for every material the backflush cannot cover, so the- * material controller fixes them all before the operator retries. The toast- * names the first few and counts the rest; the log keeps the full list. */export function strictBackflushRefusal(problems: string[]): ServerFnError {if (problems.length > SHORTFALLS_SHOWN) {logger.warn("Strict backflush refused", { problems });@@ -143,11 +117,6 @@ export function strictBackflushRefusal(problems: string[]): ServerFnError {return new ServerFnError(summarizeList(problems, SHORTFALLS_SHOWN), 409);}-/**- * Why `storageUnitId` cannot cover `quantity` — a missing bin, or a short one- * while `preventNegative` — or null when it can. Takes the bin's lock whenever- * it checks the quantity (see below).- */export async function binCoverProblem(db: Kysely<DB>,args: BinCoverArgs@@ -159,13 +128,10 @@ export async function binCoverProblem(return `${item} has no Pull From storage unit on job ${args.jobReadableId}`;}- // Negative stock allowed: the material is drawn from its own bin whatever- // that bin holds, so there is nothing to check or serialize.if (!args.preventNegative) return null;- // Serialize strict draws on this bin and item until the caller's transaction- // ends, so two completions cannot both pass the check and overdraw it.- // A caller drawing several pairs locks them all first (`lockStrictBins`).+ // Held until the caller's transaction ends, so two completions cannot both+ // pass the check and overdraw the bin.await lockStrictBins(db, companyId, [{ storageUnitId, itemId }]);const row = await db@@ -202,11 +168,6 @@ export async function binCoverProblem(return `Not enough ${item} in ${storageUnit?.name ?? storageUnitId}: need ${round(quantity)}, have ${have}`;}-/**- * Refuses (400) to activate a make method while a pulled, stocked line has no- * Pull From storage unit at one of `getPullFromLocations` (an active work- * center and an active storage unit).- */export async function assertMethodHasPullFrom(db: Kysely<DB>,args: { makeMethodId: string; companyId: string }diff --git a/packages/server-functions/src/strict-backflush.test.ts b/packages/server-functions/src/strict-backflush.test.tsindex 8dd2263251..df9074be97 100644--- a/packages/server-functions/src/strict-backflush.test.ts+++ b/packages/server-functions/src/strict-backflush.test.ts@@ -2,11 +2,6 @@// 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.-// Strict backflush against the live database-// (.ai/specs/2026-10-14-strict-backflush.md). With the setting on, a stocked-// material is consumed only from its own storage unit and a missing or short-// bin refuses the backflush; with it off, the old fallbacks still apply.-import { sql } from "kysely";import { expect } from "vitest";import {@@ -18,14 +13,14 @@ import {unwrap,workCenterFixture} from "./always-post-test-fixture";+import getMethod from "./get-method";import issue from "./issue";import { assertMethodHasPullFrom } from "./lib/strict-backflush";import { databaseTest } from "./local-database-test-fixture";import postInventoryAdjustment from "./post-inventory-adjustment";-// Strict backflush applies only at a location with an active work center and-// an active storage unit. Every test creates its storage units; turning the-// setting on adds the work center, unless the test is about its absence.+// Strict backflush needs an active work center at the location; tests create+// their own storage units.async function setStrict(f: Fixture,on: boolean,@@ -39,9 +34,6 @@ async function setStrict(if (on && withWorkCenter) await workCenterFixture(f);}-// Picks `quantity` of a job's material from `from` to `to` the way-// post-picking does: a live pick line, the transfer in the ledger, and the-// material pointed at the bin it was picked to.async function pick(f: Fixture,job: { jobId: string; materialId: string },@@ -193,7 +185,6 @@ databaseTest();expect(await consumption(f, job.jobId)).toEqual([]);- // Topped up, the same completion draws from Shelf A only.await stockBin(f, shelfA, 1);unwrap(await issue(f.ctx, {@@ -254,7 +245,6 @@ databaseTest(.where("id", "=", f.companyId).execute();- // Operation completion: all 2 from Shelf A (1 on hand → -1), none from B.unwrap(await issue(f.ctx, {type: "jobOperation",@@ -266,7 +256,6 @@ databaseTest({ storageUnitId: shelfA, quantity: -2 }]);- // A missing bin is still refused: strict bins stay strict.const second = await jobFixture(f, "2");const missing = await issue(f.ctx, {type: "jobOperation",@@ -277,7 +266,6 @@ databaseTest(`${f.prefix}-PART has no Pull From storage unit on job J-2`);- // Job completion (SQL) draws its own bin below zero too.const third = await jobFixture(f, "3");await setMaterialBin(f, third.materialId, shelfA);await sql`SELECT backflush_job_materials(${third.jobId}, 1, ${f.companyId}, ${USER})`.execute(@@ -328,7 +316,6 @@ databaseTest("a dry run reports the refusal and writes nothing", async () => {const job = await jobFixture(f);await setMaterialBin(f, job.materialId, shelfA);- // Off: a no-op, even though the bin is short.unwrap(await issue(f.ctx, {type: "jobOperation",@@ -347,7 +334,6 @@ databaseTest("a dry run reports the refusal and writes nothing", async () => {});expect(short.error?.status).toBe(409);- // Covered: the dry run succeeds and rolls every write back.await stockBin(f, shelfA, 1);unwrap(await issue(f.ctx, {@@ -468,7 +454,6 @@ databaseTest(.execute();});- // No location has a work center yet, so nothing needs a bin.await assertMethodHasPullFrom(f.db, {makeMethodId,companyId: f.companyId@@ -509,8 +494,6 @@ databaseTest(await stockBin(f, shelfA, 4);await setStrict(f, true);- // Operation completion: the picked 1 from lineside, the other 1 from- // Shelf A — the bin the line was picked from, not lineside again.const job = await jobFixture(f);await setMaterialBin(f, job.materialId, shelfA);await pick(f, job, shelfA, lineside, 1);@@ -528,7 +511,6 @@ databaseTest(]));- // Job completion (SQL): the same split.const second = await jobFixture(f, "2");await setMaterialBin(f, second.materialId, shelfA);await pick(f, second, shelfA, lineside, 1);@@ -552,9 +534,6 @@ databaseTest(async () => {const f = await alwaysPostFixture();try {- // Activation asks for no Pull From here, so the backflush must not- // refuse a line for missing one: the old fallback (the fullest bin)- // applies.const shelfB = await storageUnit(f, "Shelf B");await stockBin(f, shelfB, 10);await setStrict(f, true, { withWorkCenter: false });@@ -589,11 +568,8 @@ databaseTest(async () => {const f = await alwaysPostFixture();try {- // Two lines of 2 on one bin holding 1: both are refused, and the- // second sees the first's need already drawn ("have 0"), so the- // refusal states the bin's whole shortfall at once. Without that, the- // second would read "have 1" and the user would fix it in two rounds.- // Holds in either order the loop visits the lines.+ // Two lines of 2 on a bin holding 1: the second sees the first's need+ // ("have 0"), in either loop order.const shelfA = await storageUnit(f, "Shelf A");await stockBin(f, shelfA, 1);await setStrict(f, true);@@ -643,3 +619,102 @@ databaseTest(}});++async function jobLineBinFromBom(+ f: Fixture,+ key: string,+ storageUnitIds: Record<string, string>+): Promise<string | null> {+ const makeMethodId = `${f.prefix}-make-method-${key}`;+ const jobId = `${f.prefix}-bom-job-${key}`;+ await seed(f, async (trx) => {+ await trx+ .insertInto("makeMethod")+ .values({+ id: makeMethodId,+ itemId: f.assemblyId,+ version: 100 + Number(key),+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("methodMaterial")+ .values({+ makeMethodId,+ itemId: f.partId,+ itemType: "Part",+ methodType: "Pull from Inventory",+ quantity: 2,+ unitOfMeasureCode: "EA",+ storageUnitIds,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("job")+ .values({+ id: jobId,+ jobId: `J-BOM-${key}`,+ itemId: f.assemblyId,+ quantity: 1,+ unitOfMeasureCode: "EA",+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ });+ unwrap(+ await getMethod(f.ctx, {+ type: "itemToJob",+ sourceId: f.assemblyId,+ targetId: jobId,+ versionId: makeMethodId+ })+ );+ const line = await f.db+ .selectFrom("jobMaterial")+ .select("storageUnitId")+ .where("jobId", "=", jobId)+ .where("itemId", "=", f.partId)+ .where("companyId", "=", f.companyId)+ .executeTakeFirstOrThrow();+ return line.storageUnitId;+}++databaseTest(+ "under strict backflush, job creation never gives a line the fullest bin",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const shelfA = await storageUnit(f, "Shelf A");+ const shelfB = await storageUnit(f, "Shelf B");+ await stockBin(f, shelfB, 10);++ expect(await jobLineBinFromBom(f, "1", {})).toBe(shelfB);++ await setStrict(f, true);+ expect(await jobLineBinFromBom(f, "2", {})).toBeNull();++ await f.db+ .insertInto("pickMethod")+ .values({+ itemId: f.partId,+ locationId: f.locationId,+ defaultStorageUnitId: shelfA,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ expect(await jobLineBinFromBom(f, "3", {})).toBe(shelfA);++ expect(await jobLineBinFromBom(f, "4", { [f.locationId]: shelfB })).toBe(+ shelfB+ );+ } finally {+ await f.cleanup();+ }+ }+);