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.
paths: - "packages/planning/src/scheduling/" - "apps/erp/app/routes/x+/priority+/" - "apps/mes/app/routes/x+/operations.tsx" - "packages/database/supabase/migrations/schedul.sql"
Production Scheduling: data structures + flow
How job operations get sequenced onto work centers, scheduled with dates, and
displayed. The scheduling engine lives in
packages/planning/src/scheduling/ (relocated from the Supabase edge runtime)
and runs IN-PROCESS in Node — the ERP app (route actions,
production.service.ts) and @carbon/jobs (the replan wave, the recalculate
task) import runLocationSchedule / runExpediteWhatIf from
@carbon/planning and execute it in-process, eliminating the edge
cold-start + HTTP round-trip that made a regen take >2s on trivial data. The
schedule Deno edge function was DELETED — there is no remaining edge
wrapper; every caller goes through the in-process engine. Not MES,
not a DB function. The boards only read results and feed inputs. Migrations are
timestamp-ordered; newest wins and these functions/columns have been revised
many times — read the newest, not the first match.
Spec/plan: .ai/specs/2026-08-19-schedule-in-process-node.md +
.ai/plans/2026-08-19-schedule-in-process-node.md.
Capable-to-promise on a quote (quote-lead-time.ts,
runQuoteLeadTimeWhatIf): the pure WorkCenterSelector is driven with SYNTHETIC
ops built from a quote line's routing/BOM (buildQuoteSimulation), placed per
quantity against TWO buildFiniteContext snapshots — queued (excludeJobIds: []) and front-of-queue (whole batch excluded, like the expedite what-if). A
purchased/short-stock material sets the optional materialReadyAt floor on its
consuming op (never set on jobs, so live scheduling is unchanged). Persists
nothing; buildFiniteContext + loadAvailabilityWindows were lifted out of the
engine into finite-context.ts so the engine and this what-if cannot drift.
Spec/plan: .ai/specs/2026-09-22-quote-lead-time-prediction.md.
Where it lives
- Orchestration:
packages/planning/src/scheduling/run-schedule.ts(runLocationSchedule/runExpediteWhatIf) loads a whole LOCATION's open jobs and runsnew SchedulingEngine(...).run()once per job in one deterministic forward pass (§ Engine pipeline). Every Node caller goes through it — one orchestration, zero drift. It is exported via@carbon/planning; its shared edge-lib deps are reached through the@carbon/databasesubpath barrels (types →@carbon/database, postgres →@carbon/database/client). Modules inpackages/planning/src/scheduling/(scheduling-engine.ts,dependency-manager.ts,date-calculator.ts,need-by-calculator.ts,work-center-selector.ts,apply-work-center-selections.ts,priority-calculator.ts,material-manager.ts,duration-calculator.ts,assembly-handler.ts,master-data-provider.ts,machine-availability.ts,calendar-utils.ts,slot-allocator.ts,conflict-messages.ts,types.ts). All engine READS go through theMasterDataProviderinterface (KyselyMasterDataProvideris the live impl); writes stay on Kysely. The people reads (getPeopleAssignments/getPeopleAbsences) take the planttimeZonesopeopleAssignment.daterange bounds resolve on the plant's calendar, not UTC's.resource-manager.tswas dead code and has been deleted.machine-availability.ts/calendar-utils.ts/slot-allocator.ts/apply-work-center-selections.ts/duration-calculator.ts/date-utils.ts/operator-eligibility.ts/people-utils.ts/need-by-calculator.tsare pure and have unit tests (pnpm --filter @carbon/planning test, vitest — colocated*.test.ts), alongside the determinism + envelope suites.date-utils.toIsoDatenormalizes pg DATE columns (JS Date at local midnight) to "YYYY-MM-DD" — required before any lexicographic date comparison (operator expiry). - ERP authoring boards (
apps/erp/app/routes/x+/priority+/):operations.tsx(ops Kanban; drag →operations.update.tsx→api.production.reorderScheduleOperations, which writesjobOperation.workCenterId+priorityand, only when a card moved to another work center, callsnotifyScheduleInputsChanged(…, "work-center", …); a reorder within one column re-sequences the dispatch order and reschedules nothing — the board header carries a tooltip: "Reorders dispatch sequence and work center only — does not reschedule. Change dates on the Dates board.") anddates.tsx(jobs-by-due-date Kanban; drag →dates.update.tsx→api.production.moveScheduleJob, which writesjob.dueDate+priorityand, in the same UPDATE, the deadline type the date implies (deadlineTypeForDueDate: a dated No Deadline or ASAP job becomes Soft Deadline — the scheduler ignores an ASAP date that MRP would plan supply to — and an undated Hard / Soft Deadline job becomes No Deadline), then callsnotifyScheduleInputsChanged(…, "reorder", …)— which only stamps the jobs schedule-outdated; the debounced wave regenerates the whole location. There is no immediate single-job path).people.tsxis the People page with a segmented view switcher (?view=): the People board (manning board: drag employees onto work-center columns per date; Unassigned column isposition: sticky— needsmin-w-maxon the sharedBoardContainerrow andMeasuringStrategy.Alwayson the DndContext; mutations viapeople.update.tsx, which calls one people service function perintent(assignPerson,movePerson,markPersonAbsentRange, … inproduction.server.ts); each firesnotifyScheduleInputsChanged(…, "people", …, workCenterId)— a MOVE notifies BOTH the destination and the source work center (viamovePeopleAssignment'spreviousWorkCenterId), so the station the person left re-plans too instead of keeping a stale booking), a week matrix (PeopleMatrix.tsx: employee×day grid + assigned-vs-needed coverage as sub-tabs, department filter), and a week capacity board (PeopleCapacity.tsx). Both read each station's working windows:getWorkCenterWorkingWindows(the engine's ladder and holidays; a station's linked shifts at another location are loaded too,getShiftsWithTimesByIds) less the open offline maintenance outages (getWorkCenterOutages→downtimeOutages,@carbon/planning, the rule the engine uses). Capacity math: Demand = the hours each openjobOperationstill needs as the engine counts them (remainingWorkHours: setup + max(labor, machine), netted by quantity complete, setup dropped once a production event exists) by due date (Draft/Planned jobs excluded — released work only; overdue lands in a Past-due column); Scheduled =capacityReservation.workHourssplit across the days of the booking by the station's working time in each day, so a booking from Monday noon to Tuesday 11:30 puts its hours in shift time and none on the night or a weekend (no working time falls back to the clock-time share); Available = the working hours in each plant day (workingHoursByDay: 0 on a holiday, less maintenance downtime, and the real day length on a lights-out station, 23 or 25 hours across DST). Coverage (Matrix) needsceil(attended hours / person-day hours)people per station-day, where attended hours are the setup + labor share of each booking laid on the station's working time from the booking's start (attendedHoursByDay,getOperationAttendedShares); machine time and lights-out stations need nobody. On a shift tab only the hours inside that shift count (within,getShiftWorkingWindows), each on the day the shift STARTS: the roster puts Friday's night shift on Friday, so its hours past midnight are Friday's (a run longer than a day, back-to-back shifts merged into one window, is split by the clock). A shift id from the URL that is not one of the location's shifts reads as All shifts. Load renders as hours over/free (+Xh / Xh free), not %. Shift + location filters live in header popovers; the shift filter's "All shifts" option (shiftIdnull on drag) creates shift-less assignments that resolve hours via the ladder. The Board has Day | Week period tabs — Week rendersPeopleWeekBoard(drag once = assigned all week viaassign-week/unassign-week/move-week→assignPeopleWeeketc., one row per working day from the shift's weekday flags; matrix/capacity are week-only, no month range — removed on request). Header also has a Calendar date-jump popover (Calendar is exported from @carbon/react for this), copy previous day/week (copy/copy-week— day copy preserves splithours, overtime never copies), and a "Time off" range dialog (absent-range→setPeopleAbsenceRange). The route delegates its pieces toui/Schedule/People/:PeopleHeader(filters/tabs/date nav/copy/menu),OvertimeDialog+TimeOffDialog(conditionally mounted),PeopleCard+PeopleColumn(extracted fromPeopleBoard), with the shift-hours/time ladders shared viapeopleShared.ts; the Capacity view's demand/scheduled buckets are computed server-side bybuildPeopleCapacityBuckets(modules/production/production.service.ts). - MES display (
apps/mes/app/routes/x+/operations.tsx): the "Schedule" page is a Kanban (columns = work centers, cards = operations sorted bypriority), not a Gantt. Read-only re display; operators execute viaoperation.$operationId.tsx.apps/erp/app/routes/x+/scheduling+/gantt.tsxis a placeholder Gantt with hard-coded sampletracedata in its loader — not wired to the engine. MESdispatch.*.tsxroutes are maintenance dispatch (machine breakdowns), unrelated.
Batch pre-pass (Released operation batches schedule as ONE unit)
batch-scheduler.ts (placeReleasedBatches + pure planBatchPlacements, unit
tested). Runs inside runLocationSchedule AFTER loadOrderedBatch and BEFORE
the per-job loop; runExpediteWhatIf calls it with persist: false, which
REUSES the existing batch rows instead of recomputing (the sim must agree with
its own snapshot). A pre-pass throw degrades to per-member placement (logged),
never abandons the location run.
- Auto work-center selection: a Released batch with NO
workCenterIdgets one from the pre-pass — earliest finish across the process's ACTIVE work centers at the location (ties: fewer existing reservations, then id) — persisted to the batch AND its members in the placement txn (IS NULLguard defers to a human pick landing mid-wave). Release therefore never requires a work center; no candidates at all degrades to per-member placement. - What blocks a batch:
batchBlockingReservationsdecides which live reservations a batch is placed around. It keeps other jobs' bookings and other batches' rows. It drops this location's own batch rows, and every non-batch row of a job the run re-plans (orderedJobIds): the run replaces those bookings, so they must not push the batch later. Before this, the batch drifted later on every regen. A job that throws during the run is left out of the write, sopersistLocationWritesclears its stored bookings too (failedJobIds): otherwise the batch could sit on top of one. - One reservation per Released (
Active/Completing) batch, taggedcapacityReservation.jobOperationBatchId;operationId/jobIdstay NOT NULL by anchoring on the min member op id. Placeholder semantics mirror unplaceable ops (isPlaceholder = truewhen no slot; never blocks). A batch whose open members all carry ZERO time standards is a placeholder too, not a skip:NO_ESTIMATE_PLACEHOLDER_HOURS(1h) gives the forecast a drawable window (snapped forward to the WC's next working window vianextWorkingInstant, so it never draws on a weekend),workHoursstays 0, and members carrycomposeBatchNoEstimatesConflictnaming the data gap — a Released batch must never silently vanish (its reservation is its ONLY forecast surface, and zero-estimate ops are how the batch dropped off the forecast unnoticed). - Duration =
@carbon/utilsbatchDuration:setup(max, zero once any batch event exists) + Σ run(Sequential) or+ max run(Simultaneous) perprocess.batchType, run_i =max(labor, machine)net of remaining fraction. - Anchor =
max(now, member predecessors' PERSISTED projectedCompletionAt)(same-method lower-"order"ops; same-batch members never self-anchor). Stale-by-one-wave by design: a predecessor freshly placed past the batch start getscomposeBatchPredecessorConflicton the member and the next wave re-anchors. - Members pin to the window in
work-center-selector.ts(abatchPlacementsmap threaded engine→selector; the branch generalizes the pinned Outside-Processing path): no per-member placement, NO per-member reservation, successors chain after the batch end,priority: 0like OSP. - Three predicate rules keep the coalesced row alive: the per-job regen
delete adds
AND "jobOperationBatchId" IS NULL; the snapshot'sexcludeJobIdsfilter never excludes batch-tagged rows; and the snapshot's job-STATUS filter (capacityHoldingJobStatuses) also spares batch-tagged rows — a Released batch may legitimately anchor a Draft job (membership handoff pulls members ahead of their jobs).loadOrderedBatchwidens job loading with Released-batch member jobs so they regen in the same wave. Those sparing rules make the batch's OWN lifecycle the only retirement path, so a status trigger onjobOperationBatch(20260907155426_cleanup-reservations-on-batch-exit.sql, mirroring the terminal-job trigger) deletes the tagged rows on→ Completedand on unrelease (→ Planned) — without it a finished batch kept blocking the work center and an unreleased one double-booked it against the members' per-op placements. Dissolve needs no trigger: the FK's column-listSET NULLuntags the row and the anchor job's next regen sweeps it. Plannedbatches are NOT coalesced — members place per-op exactly as before release (bounded residual over-book, gone at release). Employee finiteness for batches is deliberately absent in v1 (WC reservation only).
Trigger chain (verified)
Rescheduling is no longer a single-job event — the old per-job reschedule
trigger, its Inngest task, and the direct-trigger service helpers were all removed.
Every scheduling input change now funnels through one thin emitter,
notifyScheduleInputsChanged(companyId, kind, reason, entityId?)
(production.service.ts) → trigger("schedule-inputs-changed", …) → Inngest event
carbon/schedule.inputs.changed. kind ∈
ability | shift | employee-shift | work-center | location | reorder | people.
Two Inngest functions listen on that event
(packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts):
- MARK (
markScheduleStaleFunction, immediate, concurrency 1 per company): stamps the affected jobs'scheduleOutdatedReason/scheduleOutdatedAt(scoped per kind — a qualification change in a shop with no gated ops stamps nothing;location/reorderstamp company-wide). Ashiftevent with a shift id also stamps every job with an open op on a work center whose hours come from that shift (workCentersOnShift,shift-work-centers.ts: the stations linked to it, plus the stations at its location with no link to an active shift; lights-out stations never count), or on a process those stations run (processesOfWorkCenters: an unstarted op can move onto them). An unknown shift id stamps company-wide.createShift,updateShiftanddeleteShiftsend the id; an update that moves the shift to another location sends kindlocationinstead, so the stations it left re-plan too. Changing a location's staffing requirement (updateProductionSettings) or its timezone (updateLocation, shifts are local times) also sends kindlocation, only when the value actually changed. Recomputes nothing. - WAVE (
scheduleReplanWaveFunction, debounce 30s / timeout 10m, concurrency 1 per company): loads the company's stale jobs, groups them by LOCATION, and callsrunLocationSchedule({ db: getJobDatabaseClient(), client: serviceRole, locationId, companyId, userId: "system" })IN-PROCESS once per location — a whole-location regen (wasserviceRole.functions.invoke("schedule", …)). Each engine run clears its own job's stale stamp (no wave-side flag-clearing). There is no pre-clear-reservations step, no batch slicing/chunking, and no chain-next-wave continuation. After the regens the wave sends one digestcarbon/notify(NotificationEvent.JobsProjectedLate,documentIds= the newly-late job ids) per assignee; unassigned newly-late jobs are skipped in v1.
nightly-replan.ts (cron 0 1 * * *) is the time-passing backstop, and it now
handles TWO staleness classes: (1) jobs still stamped schedule-outdated (the event
path dropped them), AND (2) aged schedules — a stamp-aged-schedules step
stamps any active job whose earliest open op startDate is before today (UTC-day
threshold), because a forward plan anchored to an earlier day's now keeps
DISPLAYING a past start until it re-anchors (placement itself always floors at
now — it never schedules in the past). Both are then drained the same way: one
carbon/schedule.inputs.changed (kind: "reorder", continuation: true) per
company; the wave fans that out to the affected locations. NOTE: in local dev the
Inngest worker (pnpm --filter @carbon/jobs dev:jobs) must be running or none of
the reactive/nightly replan fires — a common cause of "my schedule went stale" /
"my requiresAbility change didn't reschedule" locally (the change IS wired:
processes.$processId.tsx fires notifyScheduleInputsChanged("ability", …, abilityId)
on any requiresAbility flip, and the MARK function scopes to that ability's
process ops).
Terminal-job reservation cleanup (20260819050906_cleanup-reservations-on-terminal-job.sql):
an AFTER UPDATE OF status ON "job" trigger (delete_capacity_reservations_on_terminal_job,
SECURITY DEFINER) deletes a job's live (scenarioId IS NULL) capacityReservation
rows when it transitions to Cancelled/Completed/Closed. Reservations are a
materialized output for active jobs only; before this, a cancelled/completed job's
rows lingered as orphans (invisible to the forecast/capacity reads, which filter
terminal jobs, but resurfacing as past-dated bars for any read that forgot the
filter). The trigger is the one chokepoint every terminal path funnels through
(the status route's updateJobStatus, and complete_job_to_inventory for
Completed); SECURITY DEFINER because a cancel only holds production_update while
the DELETE policy needs production_delete.
Other whole-location regen callers run runLocationSchedule(...) IN-PROCESS
(no edge invoke): recalculateJobOperationDependencies (production.service.ts,
resolves the job's locationId first, takes the caller's db handle and
dynamic-imports @carbon/planning), releaseJobs (production.server.ts, once per
location after every status flip), scanKanban (inventory.server.ts, a Make card's
auto-release), api+/schedule.ts, and the jobs task tasks/recalculate.ts. The
expedite what-if uses runExpediteWhatIf. rescheduleJob (production.service.ts, the reschedule posting)
is a separate per-job backward re-plan, not a whole-location regen.
Engine pipeline (scheduling-engine.ts run())
initialize → assignMaterials → createDependencies → calculateDates → computeNeedBys → selectWorkCenters → calculatePriorities → buildWrites (the engine
writes nothing; the location run stores the result, the expedite what-if drops it). There is no backward
JIT pass in PLACEMENT and no initial/reschedule mode split — everything places
FORWARD-ASAP, and the projected finish IS the overdue forecast (slack is real). The
backward need-by pass (computeNeedBys, below) computes demand-anchored TARGETS
only; its output is read by nothing in the placement path (spec
.ai/specs/2026-08-15-dual-dates-due-vs-projected.md).
- Whole-location, deterministic run (
run-schedule.ts, called by every Node caller): onenowis captured once and shared across every job in the batch. The location's open jobs (Ready | In Progress | Paused) are ordered deadline class first (DEADLINE_PRIORITY: ASAP → Hard Deadline → Soft Deadline → No Deadline), thendueDate ASC NULLS LAST → job.priority ASC → createdAt ASC— so a no-due-date ASAP order claims capacity first. Each job's engine run excludes the jobs not yet run (itself + later) from the reservation snapshot, so it sees non-batch reservations plus the placements of already-run jobs → sequential capacity claiming, no pre-clear step. Nothing is written while the jobs run. The engine only computes:engine.getWrites()returns aJobWrites(run-overlay.ts),provider.recordJob(writes)makes that job's reservations and operation placements visible to the jobs after it (beginRunreads the live reservations once; the rules are the purevisibleReservations/mergeCrossJobOperations), andpersistLocationWrites(persist-location.ts) stores the whole location in ONE transaction at the end. A job that throws while computing is left out of the write and keeps its stored reservations visible to later jobs; a database error in the write rolls the location back andrunLocationSchedulethrows. This replaced a write per job (about 17 statements each, 500 for a 28-job location). - Sequencing (
dependency-manager.ts): thejobOperation."operationOrder"enum (methodOperationOrder='After Previous' | 'With Previous') decides serial vs parallel, plus assembly edges (a sub-make-method's last op feeds the parent's consuming op); dependency-free ops are stamped operation-statusReady. That is operation-level status only — the engine is status-neutral for JOB status and never flips a job to Ready (release is the app's job-status flow). - Dates (
date-calculator.ts→buildScheduledOperations): now just durations + pins —startDate/projectedCompletionAtstart null and forward-ASAP placement fills them for EVERY op, pinned included.dueDate(the backward need-by target) also starts null and is seeded from storage only for a pinned/manuallyScheduledop, whose value the need-by pass takes as-is. Duration =setup + max(labor, machine). - Backward need-by pass (
computeNeedBys()→computeNeedByDatesinneed-by-calculator.ts, pure): demand-anchored per-op TARGETS diff-written tojobOperation.dueDateevery regen. Walk = reverse topological order fromjob.dueDate(null due date ⇒ all-null targets); leaves are due on the job due date; an op with dependents is due at the earliest dependent constraint — the dependent's need-by START minus that dependent'soperationLeadTimeworking days. An assembly edge (a sub-make-method feeding its parent) subtracts NO item lead time: the subassembly's own ops are in the walk, so addingitemReplenishment.leadTime(default 7) counted the build twice per BOM level and put targets weeks before the job's start. "With Previous" ops copy their partner's target dates; a pinned op's storeddueDateis taken as-is AND propagates upstream. Day math runs on real calendars viacalendarAdaptersover the SAME availability-ladder windows placement uses (one sharedloadAvailabilityWindows()fetch):calendarHoursPerDay(wc)sizes duration-in-days,workingDayTestskips that calendar's zero-hour days. HARD RULE: targets are outputs, never placement constraints — placement never floors/delays onop.dueDate(comments at the floor sites inwork-center-selector.ts;determinism.test.tspins placement invariance with/without the need-by pass; the one remaining read is the pinned OUTSIDE-PROCESSING passthrough, which keeps its stored window and chains successors after the pinned end). The pass also produces no conflict flags. - Finite placement (
work-center-selector.ts): ops are placed in a deterministic topological order (topologicalPlacementOrder, Kahn's algorithm over the dependency edges; the ready set is ordered byjobOperation."order"then id). Each op is placed forward frommax(now, placed-dependency-ends)— no backward-pass floor — into the first feasible span. Two finite resources gate it: the work center (capacity 1 — one op at a time, decided by actualcapacityReservationintervals) AND, for ability-gated processes, ≥1 qualified employee on shift and unreserved. Only a started op is sticky (isOperationStarted,apply-work-center-selections.ts: status In Progress or Paused, orquantityComplete > 0): it stays on itsworkCenterId. An op that has not started gets earliest-finish selection across its process's work centers, even when it carries a work center (the stored one is the fallback when the process has no mapped centers).applyWorkCenterSelectionsthen puts the chosen work center on a placed op that has not started, andplacementWrites(run-overlay.ts) writes it, sojobOperation.workCenterIdand the op'scapacityReservationalways name the same station. A started op and a placeholder keep the stored one; an op with no work center gets one either way. Consequence: a card dragged to another column on the operations board can move back at the next regen when another station finishes it earlier. A placement past the job'sdueDatesetshasConflict/conflictReasonbut keeps the placement. - Machine availability windows come from the ladder resolved per work center in
machine-availability.ts(resolveWorkCenterWindows) — the provider'sgetWorkCenterAvailabilitydoes the reads andbuildFiniteContextsets each WC'swindows: (1)workCenter.alwaysOn= one continuous 24×7 window (lights-out); (2) explicitworkCenterShiftrows; (3) the union of the work center's LOCATION'sshiftrows; (4) the stock Mon–Fri 08:00–16:00 (8h) week in the location tz (STOCK_WEEK_SHIFTSincalendar-utils.ts). Machine downtime is subtracted (calendar-utils.subtractIntervals) from those windows, derived from open maintenance dispatches flaggedmaintenanceDispatch.takesWorkCenterOffline(status not Completed/Cancelled; outage[actualStartTime ?? plannedStartTime ?? createdAt, actualEndTime ?? plannedEndTime ?? horizon)on the dispatch'sworkCenterId+ itsmaintenanceDispatchWorkCenterrows) — no separate downtime table; completing the dispatch restores the hours at the next regen. People with noemployeeShiftrows now default to the job LOCATION's calendar (rung 3/4 viagetLocationCalendarWindows), not 24×7. - Company holidays close the plant. The provider reads the company's
holidaydates once per run (getHolidayDates).closeHolidays(machine-availability.ts) removes each holiday's whole day, in the plant timezone, from every work center that is notalwaysOn; a lights-out station keeps running.loadLocationCalendarWindowsremoves them from the location calendar, andbuildFiniteContextadds each holiday as an absence for every person (withHolidays,people-utils.ts). The ERP reads the same dates (getHolidayDates,production.service.ts): the Forecast shades a holiday as closed, and the Capacity view shows 0 Available on it. Each Forecast lane is shaded and its bars split on its OWN station's hours (getWorkCenterNonWorkingIntervals→ the Gantt'snonWorkingIntervalsByRow; rows under a lane inherit it, the location rollup is not split, operator-pool lanes keep the plant calendar,getForecastNonWorkingIntervals), so a lights-out station is never shaded.createHoliday,updateHolidayanddeleteHoliday(people.server.ts) notify kindlocation. - A qualification ends at its expiry.
isEligibleOperatortests an operator at the op's earliest start only.clipToQualification(operator-eligibility.ts) then cuts the operator's windows at the start of theexpiresAtday in the plant timezone, andbuildEligibleMembersdrops an operator with no window left. Without the clip, an op that waited for its machine could be booked on a day after the qualification expired. The People board treats the expiry day as expired too (expiresAt <= date). - Attended-window labor model is UNCHANGED (
slot-allocator.ts): ability gating, manning-board / team mode, attended windows, wait attribution, absence subtraction (peopleAbsence), overtime extension (peopleAssignment.overtimeHours), split-day budgets (peopleAssignment.hours), and manual pins behave exactly as before — a team still runs one op at a time with labor parallelized across present members, setup and machine time never compressed. Machine calendars only refine the model: member windows are clipped to the machine windows viaintersectWindows, and the unattended remainder accumulates on the machine windows viaaddWorkingTime. A blank people board is byte-identical to pre-people behavior. One deliberate change: the gated any-qualified fallback (pass 2 inwork-center-selector.ts) now treats a manning assignment as a whole-horizon COMMITMENT — the fallback relay may only draw on true FLOATERS: qualified people with NO board assignment anywhere in the horizon (assignmentsByEmployee.has(id), built frompeopleByWorkCenter; on the finite context). A person manned ANYWHERE is spoken for and is never pulled to a station they weren't assigned to. So moving your only qualified operator off a station makes that station's op an in-window unschedulable placeholder (surfaced on the Forecast), rather than double-booking the operator OR shoving the op onto the unmanned nights/weekends a per-date clip would leave open (the bug an earlier per-date version caused — the op landed on a future Saturday and fell out of the current-week view). Blank board => every qualified person is a floater => fallback unchanged. When people ARE qualified but every one is on the board elsewhere, the reason says so (composeNoFreeOperator: "No free operator for X: … assigned to other stations on the manning board"), the Forecast detail lists who is qualified and the stations the board has them at (getQualifiedPeopleByProcess), and the ability page warns how many operations of its process can't be scheduled (getAbilityScheduleImpact). - Require-staffing policy (
location.requiresStaffing,20260820151847_location-requires-staffing.sql; per-location, default false; edited on the Production settings page): when ON, the finite scheduler places work ONLY where an operator is manned.buildFiniteContextreads it (provider.getLocationRequiresStaffing) + the set of lights-out stations (provider.getAlwaysOnWorkCenterIds) and putsrequiresStaffingon the context +alwaysOnon eachcapacity.workCenter. Two gates inwork-center-selector.ts: a gated op's any-qualified floater fallback is skipped entirely (pass 1 assigned+qualified only); an ungated op's machine-only fallback is skipped too — EXCEPT onalwaysOn(lights-out) stations, which keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder on the Forecast. This is exactly how "route everything to the one staffed work center, nothing to the unstaffed ones during staffed periods" falls out — an unstaffed non-lights-out station has no way to place, so earliest-finish selection naturally routes to the staffed candidate. OFF => the fallbacks stay (pre-setting behavior, byte-identical). "Staffing defined for a period" is derived purely from manning-board presence — there is no separate resource-plan status entity. - Remaining-work netting (
duration-calculator.remainingFractions): a started op reserves only the work left — labor + machine scaled by(1 − quantityComplete/operationQuantity)(clamped ≥ 0), setup counted done once anyproductionEventexists on the op — anchored atnow. - Priority = per-work-center dispatch sequence number (
priority-calculator.ts): ops grouped byworkCenterId, sorted by placed start date ascending (nulls last), tie-broken byjob.prioritythen deadline type, then numbered 1, 2, 3…. The dispatch sequence IS the forward-ASAP placement order — one source of truth for what runs next. Boards sort bypriorityascending. (Job-leveljob.priorityis a separate fractional index set at job creation bycalculateJobPriority.) There is no configurable dispatch-sequencing policy — the old per-work-center policy table, its rule enum, and the FIFO/EDD/SPT/… comparators were all removed; placement order is the only sequence. persistLocationWrites(one transaction per location run; the expedite what-if never calls it) writes, for every op whose values changed (anis distinct fromguard in the UPDATE, so a quiet regen writes nojobOperationorjobrow and queues no audit/search event), the forward placement's results —startDate(projected start, business day) +jobOperation.projectedCompletionAt(exact placed-end instant, timestamptz) +priority+workCenterId+ conflict flags.dueDateis the backward need-by and is DIFF-written: only when the computed target differs from the stored value (a quiet regen touches zerodueDates), and never for amanuallyScheduledop — a human owns that target. It rebuilds the jobs'capacityReservationrows (one delete for all the run's jobs wherescenarioId IS NULL, then bulk insert — a materialized OUTPUT,WorkCenter/Employeekinds); and writesjob.projectedCompletionAt(= the max placed end, the forecast finish) while clearingscheduleOutdatedReason/scheduleOutdatedAtfor each job. The engine'sbuildWritesalso computes the newly-late flag (was on-time-or-unforecast before, now projected pastdueDateon the location calendar) for the wave's digest. Every due-date judgement — need-by targets, lateness conflicts, newly-late, the behind-target sentence — readscommittedDueDate(priority-calculator.ts): only a Hard or Soft Deadline job has one; the date left on an ASAP or No Deadline job (the job form hides it) is ignored.- Behind-target attribution (informational only): when the JOB's verdict is late,
getCause()appendscomposeBehindTarget(conflict-messages.ts) — "First behind target: {op} (due X, projected Y)", the first op in topological order whose projected finish passes its need-by. It rides the job-level cause sentence (expedite dialog) and NEVER sets per-ophasConflict; the UI's amber behind-target states (BOP rows, ops-boardItemCard, MES operation detail) are computed from the two dates, not from conflicts. - Expedite what-if (
expediteJobId): runs only the target job first with the WHOLE batch excluded from the snapshot (it claims capacity as if first),persist: false, and returns{ projectedCompletionAt, cause }without touching the database.
Manual scheduling
jobOperation."manuallyScheduled" BOOLEAN NOT NULL DEFAULT false
(20260525143721_manual-scheduling.sql — adds only this column). Under dual dates a
pin means a human owns the need-by TARGET, not the placement: the backward pass
takes the pinned op's stored dueDate as-is and derives upstream ops' targets from
it (the pin propagates), and the location write never includes dueDate for a pinned
op. Forward placement schedules pinned ops normally — the old frozen-window
branch (reserve the pinned span, skip placement) was REMOVED with the dual-dates
split, so a pinned op's startDate/projectedCompletionAt are re-projected every
regen and may differ from its pin. The one exception is a pinned OUTSIDE-PROCESSING
op, which skips placement and keeps its stored window (successors chain after the
pinned end). Pins are set via setJobOperationDueDate (production.server.ts,
sets manuallyScheduled) from OperationDueDatePicker on the BOP.
Conflict detection
jobOperation."hasConflict" BOOLEAN DEFAULT false + "conflictReason" TEXT
(20251123000001_job-operation-conflicts.sql, plus index
idx_job_operation_wc_priority on ("workCenterId","priority","status")). Conflicts
come only from forward-ASAP finite placement: no feasible
slot (machine capacity exhaustion, a work center with no resolved availability
windows, missing/expired operator qualification, or calendar exhaustion —
conflictReason names the cause), or a placement that finishes after the job's
dueDate (the overdue verdict; jobDueDate is passed into the selector — the
per-op need-by targets are NOT a lateness input and NEVER set hasConflict; an op
behind its target only gets the informational amber state). Conflicts
surface; scheduling never hard-fails. The read RPCs roll it up per job with
BOOL_OR(...) so the board shows a red flag.
Unplaceable ops leave a placeholder (work-center-selector.ts best === null
branch). An op that could not be placed at all (no qualified operator, no
feasible slot, horizon-exhausted) has hasConflict/conflictReason stamped and a
fallback work center — and now also emits a non-binding placeholder
capacityReservation (isPlaceholder = true, 20260818044654_…): pinned at the
op's earliest start (snapped forward to the fallback WC's next working window via
nextWorkingInstant, so the marker never draws on a night/weekend the now
anchor happened to fall in) for its work-content duration in calendar time, on
the fallback WC. It exists so the Forecast (which is 100% reservation-driven)
shows the op instead of the job silently ending after its last placeable op, and
so job.projectedCompletionAt extends to it and successors chain after it
(placedEndByOperation). It is deliberately NOT added to the in-run
capacity.reservations blocking set, and getLiveReservations filters
isPlaceholder IS NOT true, so it never holds the machine against other jobs or
the next regen. The Forecast surfaces it with a red "can't be scheduled" alert
(LuBan) in the TREE status column — via GanttEvent.data.isUnschedulable, set
on BOTH the work-center lane (any unplaceable child) and the operation row, so it
reports at the work-center level AND per operation (in a Compact lane the
placeholders get their own bottom strip, overlapping ones merged into one
"N can't be scheduled" chip, groupOverlaps); clicking either row opens the
detail sidebar ("Unschedulable" chip + reason + "where it would run"
explanation). Plus a separate "{n} can't be scheduled" header count. (Placed-but
-LATE ops keep a real reservation, show the generic isError triangle, and are
the "conflict" count.)
Read RPCs (display only; do not compute schedules)
get_active_job_operations_by_location(location_id, work_center_ids[])
Newest: 20261006021134_mes-hide-outside-processing.sql (excludes
operationType = 'Outside Processing'; prior revisions:
20260905132037_job-operation-batching.sql added the batch columns and the
membership-handoff floor rule, 20260818031629_dual-dates.sql added
projectedCompletionAt TIMESTAMPTZ, 20260720121629_capacity-planning.sql added
hasConflict/conflictReason, 20260531084723_rework-serial-flow.sql
added quantityReworked/reworkId, 20260304000000 added operationDueDate).
It feeds the MES Work Centers board, the ERP Priority board and the API tool
production_getActiveJobOperationsByLocation. Outside Processing is filtered by
TYPE, not by a null workCenterId: both boards' columns are work centers, so an
outside operation holding a stale work center (left over from an in-house type)
otherwise lands in that column for an operator to start. Pinned by
supabase/tests/outside-processing-off-the-floor.test.sql.
TS wrappers (identical): apps/mes/app/services/operations.service.ts
getActiveJobOperationsByLocation and
apps/erp/app/modules/production/production.service.ts. Returns 44 cols incl.:
id, jobId, jobMakeMethodId, operationOrder (← jo."order"), priority, processId, workCenterId, description, setup/labor/machineTime+Unit, operationOrderType (←
jo."operationOrder", serial/parallel enum), jobReadableId, jobStatus, jobDueDate, jobDeadlineType, jobCustomerId, customerName, parentMaterialId, itemReadableId, itemDescription, operationStatus ('Paused' if job paused), targetQuantity, operationQuantity, quantityComplete, quantityReworked, quantityScrapped, salesOrderId/LineId/ReadableId, assignee, tags, thumbnailPath, operationDueDate
(← jo."dueDate", the need-by target), reworkId, hasConflict (COALESCEd, never null), conflictReason, projectedCompletionAt (← jo."projectedCompletionAt", the projected finish
instant), processBatchable, jobOperationBatchId, batchReadableId. The ERP ops board
(priority+/operations.tsx → ItemCard) and MES schedule loader map
hasConflict/conflictReason onto Kanban items (red border + triangle tooltip on
the ERP card); the dual dates drive the amber behind-target state (projected day >
need-by). The same dual-dates migration also forks get_job_operation_by_id
(newest was 20260721004140_operation-type-consolidation.sql) to add
projectedCompletionAt for the MES operation detail.
get_jobs_by_date_range(location_id, start_date, end_date)
Newest: 20260720121629_capacity-planning.sql (PL/pgSQL RETURNS TABLE,
not a view). TS wrapper getJobsByDateRange in
apps/erp/app/modules/production/production.service.ts, consumed by
apps/erp/app/routes/x+/priority+/dates.tsx loader. Filters jobs with non-null dueDate
in range and status != 'Cancelled', ordered by dueDate. Returns 27 cols:
id, jobId, status, dueDate, completedDate, deadlineType, customerId, customerName, salesOrderReadableId, salesOrderId, salesOrderLineId, itemId, itemReadableId, itemDescription, quantity, quantityComplete, quantityShipped, priority, assignee, tags, thumbnailPath, operationCount, completedOperationCount, hasConflict, jobMakeMethodId, scheduleOutdatedReason, projectedCompletionAt — the last two are new in the
capacity-planning migration and drive the dates board's forecast/stale surfaces.
Key types / enums
methodOperationOrder:'After Previous' | 'With Previous'(20240619095417_methods.sql).jobOperationStatus:Canceled | Done | In Progress | Paused | Ready | Todo | Waiting.deadlineType:No Deadline | ASAP | Soft Deadline | Hard Deadline.- Engine types (
packages/planning/src/scheduling/types.ts):enum SchedulingStrategy { PriorityLeastTime, LeastTime, Random }. TheSchedulingDirection/SchedulingModetypes and theinitial/reschedule/backward/forwardplumbing are deleted — one uniform forward-ASAP rule. - ERP scheduling zod validators (
apps/erp/app/modules/production/production.models.ts):scheduleOperationUpdateValidator,scheduleJobUpdateValidator.
Gotchas
- The engine is forward-ASAP only — no backward pass, no Infinite mode.
Every work center is finite (one op at a time) with real operating hours
from the machine-availability ladder (
workCenterShift→ the location's shifts → stock Mon–Fri 8h, oralwaysOn= 24×7), minus maintenance-dispatch downtime. Qualified people's shifts only additionally gate ability-gated ops. The old "no work-center calendar / availability comes from people's shifts" claim is wrong now. So is the old "manually scheduled ops keep their window" claim: pinned ops are placed normally every regen (the pin owns only the need-by target; see § Manual scheduling). jobOperation."order"(topo position) vs"operationOrder"(serial/parallel enum) are distinct columns — easy to confuse; the RPC surfaces them asoperationOrderandoperationOrderTyperespectively.- There is no
scheduleStatusenum/column and noscheduledStart/estimatedEndcolumns. Dual dates (20260818031629_dual-dates.sql): the forward projection goes intojobOperation.startDate(projected start day) +jobOperation.projectedCompletionAt(projected finish instant, timestamptz);jobOperation.dueDateis the backward demand-anchored need-by target (DATE, stable — changes only when the job due date, routing, or lead times change; a pinned op's is human-owned). The job-level forecast finish isjob.projectedCompletionAt. Consumers that key urgency on opdueDate(MES queue sort, the People Capacity view's Demand buckets,get_picking_scheduleordering) are deliberately unchanged — they now honestly read "when work is needed", not the sim's last forecast. The MES operation view's "Due" header, Due Date card and overdue flag read the JOB'sjobDueDate; the op target is shown under it as "Operation needed by …" and only drives the behind-target projection badge. Labelling the op target "Due" with the job's deadline icon read as the job being due weeks early. The MES Work Centers board cards follow the same rule:Item.dueDateisjobDueDate, so the "Due …" line, the overdue flag, the urgency border (getDueUrgency) and a collapsed batch's earliest member deadline all read the job's date, against the location'stodayfrom the loader rather than the device's day. The ERP Priority board still mapsoperationDueDate, since its card carries the behind-target badge. The urgency classifiers and both boards' batch reductions ignore an ASAP or No Deadline due date — only Hard and Soft Deadline carry one (deadlineRequiresDueDate), but an ASAP job can still hold a stale date.getJobPromiseDatereturnsjob.projectedCompletionAtor null (its old max-op-dueDate fallback would now just echo the job due date and was removed). - Editing the ERP ops board (
operations.update.tsx,reorderScheduleOperations) does NOT re-run the engine: it re-sequencesworkCenterId+priority, and notifies (notifyScheduleInputsChanged, kindwork-center) only when a card changed work center. The dates board always notifies, and the debounced wave regenerates the whole location. A failed notify is logged and never fails the write. The MES board is display/drag-only. - The selector MUTATES each context's reservation arrays as it places, so the quote
what-if runs every simulation on a
cloneFiniteContextcopy (quote-lead-time.ts) — reusing one context across quantities/scenarios would let earlier runs' placements bleed into later ones. OneWorkCenterSelectorinstance is fine (it resetsplannedReservationsper call), but the CONTEXT must be cloned per run.