Skip to content

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

Merge remote-tracking branch 'origin/main' into naveenkash/strict-backflush

naveenkash2bd3d65d8669
diff --cc .ai/runs/2026-10-14-strict-backflush.md
index 74597b3842,0000000000..713355810e
mode 100644,000000..100644
--- a/.ai/runs/2026-10-14-strict-backflush.md
+++ b/.ai/runs/2026-10-14-strict-backflush.md
@@@ -1,32 -1,0 +1,32 @@@
+# Feature run: Strict backflush
+
+- Date: 2026-10-14
+- Mode: fully-autonomous
+- Request: "sounds good write the spec and implement it" (after the design and decisions 1–7 in the chat)
+- Phase plan: research [skip — the user resolved every decision in the chat] · spec [run] · plan [run] · execute [run] · test [skip — the user did not ask for a browser test] · self-review [run]
+
+## Decisions
+
+- Spec gate: every open question has a human answer from the chat ("sounds good" to recommendations 1–7). No autonomous resolution was necessary for the 7 questions. — 2026-10-14
+- Spec, autonomous detail: the Pull From requirement covers Purchase to Order lines too. The BoM editor labels them "Pull From" and the backflush consumes them from a bin. — 2026-10-14
+- Spec, autonomous detail: MES records the production quantity before it issues material. A strict refusal at that point would leave produced units with no consumption. The MES routes run the issue as a dry run first, only when strict backflush is on. — 2026-10-14
+- Plan gate: plan approved autonomously after the STE-80 pass. — 2026-10-14
+- Execute: no commits. The user's standing rule is "ask before every commit". The execute skill's per-task commit is replaced by per-task verification. — 2026-10-14
+
+- Execute: the strict-backflush docs went into `apps/erp/app/modules/production/AGENTS.md`, not `.claude/rules/inventory-system.md`. The production module owns backflush, and rules document committed code only. — 2026-10-14
+- Self-review: added a transaction-scoped advisory lock on (company, bin, item) to the TypeScript and SQL bin checks, against two completions overdrawing one bin. The migration file changed after `pnpm db:migrate` applied it locally, so the local `backflush_job_materials` has no lock until it is re-applied. — 2026-10-14
+- Self-review: the DB-backed regression file `packages/server-functions/src/strict-backflush.test.ts` was not run. It creates and deletes a scratch company, and the user asks before any database write. — 2026-10-14
+
+- Browser test (user request 2026-10-15): ran through the UI as the dev user. The user asked for the test, so the UI writes (settings, BoM edits, 2 jobs, releases, picks, completions, inventory adjustments) are part of it. A script error put 1 PCB-BARE-REV3 and 1 MAT-CONFCOAT into the unassigned bin; both were set back to 0 through the same form. The migration's function was re-applied locally (`psql -f`) to test the SQL fix. — 2026-10-15
+
+## Phase log
+
+- spec: `.ai/specs/2026-10-14-strict-backflush.md` — STE-80 pass done
+- plan: `.ai/plans/2026-10-14-strict-backflush.md` — STE-80 pass done, all 12 tasks checked
+- execute: typecheck green (`@carbon/database`, `@carbon/server-functions`, `erp`, `mes`); tests green (ERP 2054, MES 69, server functions 365, database 476, checks 305); Biome clean; clobbers clean
+- self-review: lock added (above); no other must-fix
+- browser test: 6 bugs found and fixed (see the spec changelog, 2026-10-15); playbook `.ai/playbooks/strict-backflush.md`; gates green again (ERP 2057, MES 69, server functions 365, database 476, checks 305)
+
+## Outcome
+
- - Committed and pushed on the user's request (2026-10-15), PR opened. The branch was fast-forwarded to origin/main first; the migration moved to `20261015151804_strict-backflush.sql` so it is newer than main's latest. Translations filled by `/translate` (120 strings + 14 re-translated where the glossary term was dropped).
++- Committed and pushed on the user's request (2026-10-15), PR opened. The branch was fast-forwarded to origin/main first; the migration moved to `20261015163040_strict-backflush.sql` so it is newer than main's latest. Translations filled by `/translate` (120 strings + 14 re-translated where the glossary term was dropped).
diff --cc apps/erp/app/modules/production/AGENTS.md
index 60dd950bd7,223be5668c..b7106d4849
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@@ -18,17 -18,6 +18,17 @@@ Work orders (jobs), scheduling, routing
- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly; the engine lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.
+### Strict backflush
+
+`companySettings.requireBackflushStorageUnit` (Settings → Items → Strict Backflush, off by default; spec `.ai/specs/2026-10-14-strict-backflush.md`). When it is on, a stocked material is consumed only from its own storage unit, and a missing or short bin refuses the work instead of drawing from another bin:
+
+- **Which lines.** `needsPullFrom` (`@carbon/database/strict-backflush`): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are `getPullFromLocations` — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name, so requiring one there would block activation for good). Activation, release and the settings card all read these two.
+- **Activation.** `convert` `methodVersionToActive` calls `assertMethodHasPullFrom` (`packages/server-functions/src/lib/strict-backflush.ts`) and refuses a version with a line missing a Pull From at one of those locations.
+- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part); `jobReleaseProblems`, the Release dialog route and `BatchReleaseModal` refuse on it. `JobStartModal` runs the same function before submit, lists the parts and disables Release Job. The BoM editor and the job BoM editor show a red "No storage unit" badge on such a line.
- - **Backflush.** `issueJobOperationMaterials` and `partToOperation` (planned material, consuming issue) consume what no pick covered from `jobMaterial.storageUnitId` only, through `assertBinCovers` (409, names the part, the bin, need and have; it first takes `pg_advisory_xact_lock` on `strict-backflush:<companyId>:<bin>:<item>`, the same key the SQL takes). Picked and unclaimed lineside stock is still drawn first. `issueJobOperationMaterials` collects every shortfall (`binCoverProblem`) and refuses once; the SQL does the same. A refusal is a toast, so every strict message goes through `summarizeList` (`@carbon/database/strict-backflush`): the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). The Release dialog shows the full list in a scroll box; collapsed BoM and job BoM rows carry the red "No storage unit" badge (`MaterialRowTitle` `missingPullFrom`). SQL `backflush_job_materials` (`20261015151804_strict-backflush.sql`) raises the same refusal at job completion.
++- **Backflush.** `issueJobOperationMaterials` and `partToOperation` (planned material, consuming issue) consume what no pick covered from `jobMaterial.storageUnitId` only, through `assertBinCovers` (409, names the part, the bin, need and have; it first takes `pg_advisory_xact_lock` on `strict-backflush:<companyId>:<bin>:<item>`, the same key the SQL takes). Picked and unclaimed lineside stock is still drawn first. `issueJobOperationMaterials` collects every shortfall (`binCoverProblem`) and refuses once; the SQL does the same. A refusal is a toast, so every strict message goes through `summarizeList` (`@carbon/database/strict-backflush`): the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). The Release dialog shows the full list in a scroll box; collapsed BoM and job BoM rows carry the red "No storage unit" badge (`MaterialRowTitle` `missingPullFrom`). SQL `backflush_job_materials` (`20261015163040_strict-backflush.sql`) raises the same refusal at job completion.
+- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` — MES `complete.tsx`, `end.$operationId.tsx`, `quality.server.ts` `postBulkCompletion`, ERP `completeOperation`, `batch-operations` `complete` — first invoke `issue` `jobOperation` with `dryRun: true` (a rolled-back run; a no-op when the setting is off).
+- **Existing Active methods are never changed** when the setting turns on; `getActiveMethodsMissingPullFrom` lists them on the settings card.
+
### Job completion
`complete_job_to_inventory` (SQL, newest `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), before it `20261009010412_job-costing-always-post.sql` and `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.sql`) is the single choke point: the ERP complete route, the API/MCP `completeJob` tool and the `sync_finish_job_operation` trigger interceptor all go through it.
diff --cc packages/database/supabase/migrations/20261015163040_strict-backflush.sql
index 6c1f2b137b,0000000000..6c1f2b137b
mode 100644,000000..100644
--- a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql
+++ b/packages/database/supabase/migrations/20261015163040_strict-backflush.sql
diff --cc packages/jobs/manifests/schema.json
index 2e8ab009bb,3b4662c266..a54565822c
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@@ -1,11 -1,11 +1,11 @@@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261015151804",
- "schemaVersion": "20261015161847",
++ "schemaVersion": "20261015163040",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-15T15:21:55.530Z",
- "exportedAt": "2026-10-15T15:58:36.181Z",
++ "exportedAt": "2026-10-15T16:34:01.599Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",