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.
Forecast-First Finite Scheduling — implementation plan (complete)
Status: complete — all tasks landed 2026-08-13. Spec: .ai/specs/implemented/2026-08-12-forecast-first-finite-scheduling.md (the single as-built spec for the whole capacity-planning feature) Branch: naveen/capacity-planning
Read the spec first. Core invariants that every task must respect (spec §2, §7):
the engine is a pure function of one pre-built input snapshot (no DB reads during
placement), deterministic (no Date.now()/Math.random() inside the engine —
now is an input), simulate and persist are separable, and machine availability
comes from the ladder: explicit workCenterShift rows (or workCenter.alwaysOn)
→ all shifts at the location → stock Mon–Fri 08:00–17:00 in the location tz.
Progress
- Task 1: Revise the capacity-planning migration in place (drop schedulingPolicy; add workCenterShift, alwaysOn, projectedCompletionAt)
- Task 2: Apply the schema delta to the local DB and regenerate types
- Task 3: Engine — machine-availability ladder in the provider and finite context
- Task 4: Engine — slot allocator honors machine windows for attended ops and the unattended remainder
- Task 5: Engine — forward-ASAP placement, topo order, single mode, priority = placement order, delete dispatch rules
- Task 6: Engine — remaining-work netting for started operations
- Task 7: Edge function — whole-location regeneration payload + expedite simulate-only + projectedCompletionAt persistence
- Task 8: Jobs layer — wave regenerates locations, 30s debounce, delete reschedule-job path, single dispatch from the dates board
- Task 9: Resources — workCenterShift service/validator/form + work-center schedule events
- Task 10: Job forecast surfaces — promise date from projectedCompletionAt, slack badges on JobHeader and dates-board JobCard
- Task 11: Expedite what-if — service, route, and "Best case" UI
- Task 12: Capacity view — Scheduled vs Available on one date basis
- Task 13: Engine determinism + performance-envelope Deno tests (at the selector level — see note)
- Task 17: Machine downtime derived from maintenance dispatches
- Task 18: Newly-late digest notification
- Task 14: Docs sync — scheduling rule + AGENTS.md files
- Task 15: i18n extraction for new UI strings
- Task 16: Browser verification via /test (scenarios a–c verified live; d–g covered by automated tests — see note)
Dependencies
- Task 2 needs Task 1 (migration file). Everything with types needs Task 2.
- Tasks 3→4→5→6 are sequential (same engine files).
- Task 7 needs Tasks 3–6. Task 8 needs Task 7.
- Task 9 needs Task 2 only — independent of Tasks 3–8 (parallel OK).
- Tasks 10, 11 need Task 7. Task 12 needs Tasks 2 and 9 (workCenterShift reads).
- Task 13 needs Tasks 3–7.
- Task 17 needs Tasks 2–3 (ladder subtraction); its form/emitter steps can run parallel with Tasks 4–8.
- Task 18 needs Tasks 7–8 (newlyLate response + wave).
- Tasks 14–16 last (14 covers 1–13 + 17–18); Task 16 needs a running stack (user boots it).
Task 1: Revise the capacity-planning migration in place
Depends on: none Files:
- Modify:
packages/database/supabase/migrations/20260720121629_capacity-planning.sql
This branch owns its entire schema delta vs main (precedent: spec 07-05 changelog 2026-07-13, "branch migrations rewritten in place (unmerged)"). Do NOT create a new migration file and do NOT touch any migration that exists on origin/main.
Steps:
- Delete from the migration: the
CREATE TYPE "schedulingDispatchRule"statement (L58), the entireL96–112), and theCREATE TABLE "schedulingPolicy"block with itsschedulingPolicy_company_wc_keyunique index and three other indexes (schedulingPolicyRLS block (ALTER TABLE ... ENABLE ROW LEVEL SECURITY+ four policies, ~L128–140). Keep the comment header of the section but reword it to "Capacity reservations" only. Verify nothing else in the file referencesschedulingPolicyafterward. - In the same file, after the
capacityReservationRLS block, add:
-- ============================================================================
-- Work center operating hours (availability ladder rung 1)
-- ============================================================================
-- Which shifts a work center operates. No rows = rung 2 (all shifts at the
-- work center's location); no shifts at the location = rung 3 (stock Mon-Fri
-- 08:00-17:00 in the location timezone). "alwaysOn" = lights-out, 24x7.
ALTER TABLE "workCenter" ADD COLUMN "alwaysOn" BOOLEAN NOT NULL DEFAULT false;
CREATE TABLE "workCenterShift" (
"id" TEXT NOT NULL DEFAULT id('wcsh'),
"companyId" TEXT NOT NULL,
"workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
"shiftId" TEXT NOT NULL REFERENCES "shift"("id") ON DELETE CASCADE,
"createdBy" TEXT NOT NULL REFERENCES "user"("id"),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT REFERENCES "user"("id"),
"updatedAt" TIMESTAMP WITH TIME ZONE,
PRIMARY KEY ("id", "companyId"),
FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE
);
CREATE INDEX "workCenterShift_companyId_idx" ON "workCenterShift" ("companyId");
CREATE INDEX "workCenterShift_workCenterId_idx" ON "workCenterShift" ("workCenterId");
CREATE INDEX "workCenterShift_shiftId_idx" ON "workCenterShift" ("shiftId");
CREATE INDEX "workCenterShift_createdBy_idx" ON "workCenterShift" ("createdBy");
ALTER TABLE "workCenterShift" ADD CONSTRAINT "workCenterShift_wc_shift_key"
UNIQUE ("workCenterId", "shiftId", "companyId");
ALTER TABLE "public"."workCenterShift" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "SELECT" ON "public"."workCenterShift" FOR SELECT USING (
"companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
);
CREATE POLICY "INSERT" ON "public"."workCenterShift" FOR INSERT WITH CHECK (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[])
);
CREATE POLICY "UPDATE" ON "public"."workCenterShift" FOR UPDATE USING (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[])
);
CREATE POLICY "DELETE" ON "public"."workCenterShift" FOR DELETE USING (
"companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[])
);
-- ============================================================================
-- Machine downtime via maintenance dispatches (derived windows, no new table)
-- ============================================================================
ALTER TABLE "maintenanceDispatch"
ADD COLUMN "takesWorkCenterOffline" BOOLEAN NOT NULL DEFAULT false;
COMMENT ON COLUMN "maintenanceDispatch"."takesWorkCenterOffline" IS
'While this dispatch is open, its work center(s) contribute no scheduling capacity between (actualStartTime ?? plannedStartTime ?? createdAt) and (actualEndTime ?? plannedEndTime ?? open-ended).';
-- ============================================================================
-- Forecast output on the job
-- ============================================================================
ALTER TABLE "job" ADD COLUMN "projectedCompletionAt" TIMESTAMP WITH TIME ZONE;
COMMENT ON COLUMN "job"."projectedCompletionAt" IS
'Simulated finish of the job''s last operation (forward-ASAP finite schedule). Null until first regen.';
- The
workCentersview must exposealwaysOn. Find the NEWEST definition of theworkCentersview:grep -rln 'CREATE OR REPLACE VIEW "workCenters"' packages/database/supabase/migrations/ | sort | tail -1. If it selects explicit columns (notwc.*), append aDROP VIEW IF EXISTS "workCenters"; CREATE OR REPLACE VIEW "workCenters" WITH(SECURITY_INVOKER=true) AS ...block at the end of20260720121629_capacity-planning.sql, forked verbatim from that newest definition withwc."alwaysOn"added (lesson: fork from the newest definition, never an older one). If the newest definition already useswc.*(orSELECT *), no view change is needed. Do the same check forworkCentersWithBlockingStatus. - Confirm the later branch migrations (
20260723212028_people-assignments.sql,20260731124240_people-overtime.sql,20260731192616_people-split-hours.sql,20260812153418_simplify-employee-ability.sql) contain no reference toschedulingPolicy:grep -l schedulingPolicy packages/database/supabase/migrations/*.sqlmust list only files you already edited (expect zero matches after step 1).
Verify:
grep -c "schedulingPolicy\|schedulingDispatchRule" packages/database/supabase/migrations/20260720121629_capacity-planning.sql
# Expected: 0
grep -c "workCenterShift" packages/database/supabase/migrations/20260720121629_capacity-planning.sql
# Expected: >= 10 (table + indexes + policies)
Out of scope: any migration file that exists on origin/main; seed data (none references schedulingPolicy — verified).
Task 2: Apply the schema delta to the local DB and regenerate types
Depends on: Task 1 Files:
- Modify:
packages/database/src/types.ts(generated — via command only, never by hand)
The local dev DB already has the OLD version of 20260720121629 applied, so
pnpm db:migrate will not re-run it. Apply the delta directly, then reload the
PostgREST schema cache (lesson: direct psql DDL requires NOTIFY pgrst).
Never rebuild/reset the database — the delta below is sufficient.
Steps:
- Read
PORT_DBfrom.env.localat the repo root. If the DB is not reachable at127.0.0.1:$PORT_DB, STOP and report — do not start or reset the stack yourself. - Write the delta to a temp file
/tmp/ffs-delta.sqlcontaining, in order:DROP TABLE IF EXISTS "schedulingPolicy";,DROP TYPE IF EXISTS "schedulingDispatchRule";, then the full ADD/CREATE block from Task 1 step 2 verbatim, then the view recreation from Task 1 step 3 if one was needed, thenNOTIFY pgrst, 'reload schema';. - Apply:
psql "postgresql://postgres:[email protected]:${PORT_DB}/postgres" -v ON_ERROR_STOP=1 -f /tmp/ffs-delta.sql. If authentication fails, retry with usersupabase_admin. If both fail, STOP and report. pnpm run generate:typespnpm exec turbo run typecheck --filter=@carbon/database
Verify:
grep -c "workCenterShift" packages/database/src/types.ts
# Expected: >= 1
grep -c "schedulingPolicy" packages/database/src/types.ts
# Expected: 0
grep -c "projectedCompletionAt" packages/database/src/types.ts
# Expected: >= 1
Out of scope: fixing unrelated typecheck errors in other packages (expected at this point — engine code still references schedulingPolicy until Task 5).
Task 3: Engine — machine-availability ladder in the provider and finite context
Depends on: Task 2 Files:
- Modify:
packages/database/supabase/functions/lib/scheduling/master-data-provider.ts - Modify:
packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts—buildFiniteContext - Modify:
packages/database/supabase/functions/lib/scheduling/calendar-utils.ts— addintersectWindows,stockWeekShifts - Create:
packages/database/supabase/functions/lib/scheduling/machine-availability.test.ts
Steps:
- In
calendar-utils.tsadd two pure exports:export function intersectWindows(a: CalendarWindow[], b: CalendarWindow[]): CalendarWindow[]— pairwise interval intersection of two disjoint sorted lists (walk both lists; standard two-pointer). Update the file's header comment: work centers are no longer "always open" — availability comes from the machine-availability ladder; people windows refine it.export const STOCK_WEEK_SHIFTS: CalendarShiftRow[]— Mon–Fri (dayOfWeek1–5),startTime "08:00",endTime "17:00"(rung 3; the 9-hour wall span matches the UI's 8h + 1h break convention — use exactly these times).
- In
master-data-provider.tsadd to theMasterDataProviderinterface andKyselyMasterDataProvider:
Implementation (one query set, no per-WC loops — N+1 rule): a. LoadgetWorkCenterAvailability( workCenterIds: string[], rangeStart: Date, rangeEnd: Date ): Promise<Map<string, CalendarWindow[]>>workCenterrows for the ids:id,alwaysOn,locationId. b. Load allworkCenterShiftrows for the ids joined toshift(s.startTime,s.endTime, weekday booleans,s.active = true) and tolocationfortimezone— mirror the exact join/select shape ofgetEmployeeShiftWindows(same file, ~L556). c. Load all activeshiftrows for the distinctlocationIds (rung 2), with the location timezone. d. Per work center resolve:alwaysOn→[{start: rangeStart, end: rangeEnd}]; else if it hasworkCenterShiftrows →expandCalendar(itsShiftRows, rangeStart, rangeEnd, tz), unioning multiple shifts viaunionWindows; else if its location has shifts → same over the location's shifts; else →expandCalendar(STOCK_WEEK_SHIFTS, rangeStart, rangeEnd, tz)wheretzis the location timezone (fall back to"UTC"only if the location has no timezone). - In
scheduling-engine.tsbuildFiniteContext(~L503–520): replacewindows: [{ start: rangeStart, end: rangeEnd }]with the ladder result — callthis.provider.getWorkCenterAvailability([...workCenterIds], rangeStart, rangeEnd)alongside the existingPromise.allreads, and set eachcapacityByWorkCenterentry'swindowsfrom the map. Update the comment ("capacity 1, open per the availability ladder"). - Same function, people fallback (~L561–567 and the
employeesByAbilityfallback ~L612): replace the always-available default[{ start: rangeStart, end: rangeEnd }]with the job location's calendar — compute once:locationDefaultWindows= rung 2/3 result for the job's location (reuse the same location-shift data; add a small provider methodgetLocationCalendarWindows(locationId, rangeStart, rangeEnd)if cleaner). Both fallback sites must use it. A person withemployeeShiftrows keeps their expanded shift windows exactly as today. - Write
machine-availability.test.ts(Deno) against a fixture provider or the pure pieces: rung 1 (two shifts on one WC unions), rung 2 (no WC rows → location shifts), rung 3 (no shifts anywhere → Mon–Fri 08:00–17:00 windows, zero-width on Sat/Sun),alwaysOn(single continuous window), andintersectWindows(overlap, containment, disjoint → empty).
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/machine-availability.test.ts lib/scheduling/calendar-utils.test.ts
# Expected: all tests pass
Out of scope: slot-allocator behavior (Task 4); removing the 24×7 semantics of expandCalendar([], ...) itself — that pure function keeps its contract; callers change instead.
Task 4: Engine — slot allocator honors machine windows
Depends on: Task 3 Files:
- Modify:
packages/database/supabase/functions/lib/scheduling/slot-allocator.ts - Modify:
packages/database/supabase/functions/lib/scheduling/slot-allocator.test.ts - Modify:
packages/database/supabase/functions/lib/scheduling/work-center-selector.ts— member-window clipping
allocateOperation (ungated) already accumulates across capacity.windows via
findSlot — it needs no change and becomes hours-bounded automatically. Two
gaps remain:
Steps:
allocateAttendedOperation: the unattended remainder currently extends flat calendar time (end = attendedEnd + unattendedMs, ~L505–508). Replace with accumulation across the machine's windows: add a pure helper incalendar-utils.ts—export function addWorkingTime(from: Date, durationMs: number, windows: CalendarWindow[]): Date | null(walk windows fromfrom, count only in-window time, return the finish instant; null if the windows run out) — and computeend = addWorkingTime(sim.attendedEnd, unattendedMs, capacity.windows); a null result is the existingexhaustedconflict. WhenunattendedMs === 0,end === sim.attendedEndmust hold exactly.- Attended simulation must not book people while the machine is closed: in
work-center-selector.ts, at each of the fourallocateAttendedOperationcall sites (gated pass 1 ~L488, gated pass 2 ~L506, manned ungated ~L547 — and the corresponding member-list constructions), intersect every member's windows with the machine's windows viaintersectWindows(memberWindows, capacity.windows)before passingmembers. Do this at the selector level (per candidate WC), not inside the allocator. - Also intersect the
earliestStartwalk implicitly: no change needed —simulateAttended/simulateAttendedTeamonly accumulate inside member windows, which are now machine-clipped. - Update
slot-allocator.test.ts: existing lights-out tests that assume a 24×7 machine must constructcapacity.windowsas one full-range window explicitly (representingalwaysOn) — assert unchanged behavior. Add: (a) an 8h-window machine with a 10h ungated op spans two days; (b) an attended op whose 4h unattended remainder starts 1h before window close finishes 3h into the next window; (c) a member on a 24×7 personal window clipped by an 8h machine window accumulates only 8h/day.
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/slot-allocator.test.ts lib/scheduling/calendar-utils.test.ts
# Expected: all tests pass, including the three new cases
Out of scope: team-mode rate math, wait attribution logic, machineIsFree.
Task 5: Engine — forward-ASAP, topo order, single mode, priority = placement order
Depends on: Task 4 Files:
- Modify:
packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts - Modify:
packages/database/supabase/functions/lib/scheduling/work-center-selector.ts - Modify:
packages/database/supabase/functions/lib/scheduling/priority-calculator.ts - Modify:
packages/database/supabase/functions/lib/scheduling/date-calculator.ts(reduce) - Modify:
packages/database/supabase/functions/lib/scheduling/types.ts - Modify:
packages/database/supabase/functions/lib/scheduling/master-data-provider.ts— deletegetSchedulingPolicies/loadSchedulingPolicies/SchedulingPolicyRow - Modify:
packages/database/supabase/functions/lib/scheduling/apply-work-center-selections.ts+ its test - Delete:
packages/database/supabase/functions/lib/scheduling/date-calculator.test.ts(backward-pass tests)
Steps:
- Remove the backward floor. In
work-center-selector.tsselectWorkCentersForOperations: delete theif (op.startDate) { backwardMs... }block (~L394–399).earliestMs = max(ctx.now, placed dependency ends)only. Keep the manual-pin and outside-processing branches exactly as they are. - Topological placement order. Replace the sort-by-
startDate(~L271–276) with a deterministic topological order overctx.dependencies(Kahn's algorithm; ready set ordered byjobOperation.orderthen id). Pinned and outside ops participate in the same order. - Reduce the date pass. In
scheduling-engine.tscalculateDates(): stop callingcalculateOperationDatesfor backward targeting. It must still producethis.scheduledOperations(the working map with durations, pins, flags) — extract the map-building (id→ScheduledOperationwithdurationHoursetc.) into a plain builder (either simplifydate-calculator.tsto just that builder, or inline it in the engine and delete the file).startDate/dueDatestay null pre-placement except formanuallyScheduledops, which keep their stored dates. DeleteBackwardSchedulingStrategy,ForwardSchedulingStrategy,getSchedulingStrategy,subtractBusinessDays/addBusinessDaysre-exports if nothing else imports them (verified: nothing does). Delete the pass-1hasConflictcounting fromcalculateDates. - Single mode. Remove
SchedulingMode/SchedulingDirectionfromtypes.ts, themode/directionconstructor args and fields fromSchedulingEngine, andctx.stickyWorkCenters. Candidate rule becomes unconditional (current sticky behavior): an op with aworkCenterIdpresent incapacityByWorkCenterkeeps it; otherwise full process candidates (this is how new/unassigned ops get selection — there is no "initial" mode anymore). - Priority = placement order. In
priority-calculator.ts: deletecompareByDispatchRule, therule/resolveRuleparameters, and theDispatchRuleimport.sortOperationsByPrioritysorts by placed start date (then job priority, then deadline type — keep the legacy tie-break chain). Inscheduling-engine.tsdeleteresolveDispatchRulesanddispatchRuleByWorkCenter;calculatePrioritiesnumbers ops per work center by placedstartDateascending. Inmaster-data-provider.tsdeletegetSchedulingPolicies,loadSchedulingPolicies, andSchedulingPolicyRow. Intypes.tsdeleteDispatchRule. - Reconciliation.
apply-work-center-selections.ts: placements now always carry dates; remove any branch that preserved pass-1 backward dates or pass-1 conflicts for non-pinned, non-outside ops. Updateapply-work-center-selections.test.tsaccordingly (placed dates win; pinned op keepsdueDate; outside ops keep their computed span). - Sweep:
cd packages/database/supabase/functions && grep -rn "DispatchRule\|schedulingPolic\|stickyWorkCenters\|SchedulingMode\|SchedulingDirection" lib/ schedule/ | grep -v testmust return nothing. Then fix the tests the sweep breaks (work-center-selector.test.tsstill covers sticky/apply behavior — update names/args, keep coverage).
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/
# Expected: all tests pass; no test file references DispatchRule or backward strategies
Out of scope: the edge-function payload (Task 7); conflict-messages.ts (wait attribution unchanged); job.priority (job-level fractional index — untouched).
Task 6: Engine — remaining-work netting
Depends on: Task 5 Files:
- Modify:
packages/database/supabase/functions/lib/scheduling/master-data-provider.ts - Modify:
packages/database/supabase/functions/lib/scheduling/duration-calculator.ts - Modify:
packages/database/supabase/functions/lib/scheduling/work-center-selector.ts - Modify:
packages/database/supabase/functions/lib/scheduling/duration-calculator.test.ts
Steps:
- Provider:
getOperationsalready selectsquantityCompleteor can — ensure the operation rows carryquantityCompleteandoperationQuantity. Add one batched readgetOperationsWithEvents(operationIds: string[]): Promise<Set<string>>—SELECT DISTINCT "jobOperationId" FROM "productionEvent" WHERE "jobOperationId" IN (...)(chunk the IN list at 200, one query per chunk, never per-row). duration-calculator.ts: addexport function remainingFractions(op: { operationQuantity: number | null; quantityComplete: number | null }, hasProductionEvent: boolean): { setup: number; work: number }work = clamp(1 - (quantityComplete ?? 0) / max(operationQuantity ?? 1, 1), 0, 1);setup = hasProductionEvent ? 0 : 1. Apply in the selector wheredurationHours/attendedHours/teamComponentsare computed (~L424–442): scale labor and machine bywork, setup bysetup. Ops withwork === 0andsetup === 0get no reservation (same handling as existing zero-duration filtering inpersistChanges).- Tests: fraction math (0%, 50%, 100% complete; event vs no event; null quantities), and a selector-level case showing a half-complete op books half the hours.
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/duration-calculator.test.ts lib/scheduling/work-center-selector.test.ts
# Expected: all tests pass
Out of scope: deriving remaining time from productionEvent durations (quantity-proportional only, per spec); MES quantity recording.
Task 7: Edge function — whole-location regeneration + expedite + projectedCompletionAt
Depends on: Tasks 5, 6 Files:
- Modify:
packages/database/supabase/functions/schedule/index.ts - Modify:
packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts— dry-run + projectedCompletionAt - Modify:
packages/database/supabase/functions/lib/scheduling/master-data-provider.ts—getLiveReservationsexclusion list
Steps:
- New payload validator:
Removeconst payloadValidator = z.object({ locationId: z.string(), companyId: z.string(), userId: z.string(), expediteJobId: z.string().optional(), });jobId/jobIds/mode/direction. Handler: load the job set —jobwherelocationId,companyId,status IN ('Ready','In Progress','Paused'), ordered deadline class first (deadlineType: ASAP=0, Hard Deadline=1, Soft Deadline=2, No Deadline/null=3 — theDEADLINE_PRIORITYranking inpriority-calculator.ts; sort in TS after the select), thendueDate ASC NULLS LAST, priority ASC, createdAt ASC. This ordering is why a no-due-date ASAP job leads the queue instead of trailing on NULLS LAST. IfexpediteJobIdis set and present in the set, move it to index 0. - Determinism seam: capture
const now = new Date()ONCE in the handler and pass it into every engine run (add anowconstructor arg toSchedulingEngine; replace every internalnew Date()used for scheduling decisions with it — grep the engine files fornew Date()and audit each; timestamps for audit columns may keepnew Date().toISOString()at persist time). - Reservation snapshot: change
getLiveReservations(fromDate, excludeJobId)togetLiveReservations(fromDate, excludeJobIds: string[])and pass the FULL batch's job ids from the edge function through to every engine run (thread via constructor). This removes the need for any pre-clear: each engine sees only non-batch reservations plus the in-run placements of already-run batch jobs. Update the one call site inbuildFiniteContext. - Dry-run: add
persist: boolean(default true) to the engine options. When false,run()skipspersistChangesentirely and returns{ jobId, projectedCompletionAt, conflictsDetected, cause }whereprojectedCompletionAt= max placed end across the job's operations andcause= the job's first conflict/schedule note if any. Expedite flow: run job 0 (the expedited one) withpersist: false, return its result immediately as the response{ expedite: { jobId, projectedCompletionAt, cause } }— do NOT run the rest of the batch, do NOT write anything. - Normal flow (no
expediteJobId): run every job sequentially withpersist: true. InpersistChanges, additionally writejob.projectedCompletionAt(max placed end; null if no operations) and clearscheduleOutdatedReason/scheduleOutdatedAton that job, inside the same transaction.persistChangesmust also compute a newly-late flag before writing: read the job's priorprojectedCompletionAt(already loaded onthis.job), and setnewlyLate = truewhen (prior was null OR prior business day ≤dueDate) AND new business day >dueDate(business days via the existingbusinessDay(iso, timezone)helper; jobs with nodueDateare never late). Response:{ locationId, jobsScheduled: n, conflictsDetected: total, newlyLate: [{ jobId, readableJobId, assignee, projectedCompletionAt }] }—readableJobId=job.jobId,assignee=job.assignee(may be null). Task 18 consumes this. - Sweep ALL other invokers of the
schedulefunction to the new payload:grep -rn 'invoke("schedule"' packages/ apps/— known sites:packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts(Task 8 rewrites it),packages/jobs/src/inngest/functions/tasks/reschedule-job.ts(deleted in Task 8), and anyrecalculate/job-release task that passesmode: "initial"— for those, resolve the job'slocationId(one select) and invoke with{ locationId, companyId, userId }. If a caller cannot supply a locationId, STOP and report — do not invent a fallback.
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/
# Expected: all pass
grep -rn "mode:\s*\"initial\"\|direction:" packages/jobs/src apps/erp/app | grep -v node_modules | wc -l
# Expected: 0
Out of scope: Inngest wiring (Task 8); UI for expedite (Task 11).
Task 8: Jobs layer — location regen wave, 30s debounce, delete reschedule-job path
Depends on: Task 7 Files:
- Modify:
packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts - Modify:
packages/jobs/src/inngest/functions/scheduled/nightly-replan.ts— comment/behavior check only - Delete:
packages/jobs/src/inngest/functions/tasks/reschedule-job.ts - Modify:
packages/jobs/src/inngest/functions/index.tsandpackages/jobs/src/inngest/index.ts— remove the deleted function's registration/exports - Modify:
packages/lib/src/events.ts— removecarbon/reschedule-job;packages/lib/src/trigger.ts— remove"schedule-job"key - Modify:
apps/erp/app/modules/production/production.service.ts—triggerJobScheduleremoval - Delete the duplicate:
apps/erp/app/modules/production/production.server.tstriggerJobSchedule+ deprecatedtriggerJobReschedule(remove the functions; keep the file if it has other exports) - Modify:
apps/erp/app/routes/x+/schedule+/dates.update.tsx
Steps:
scheduleReplanWaveFunctionrewrite: keep idschedule-replan-wave, retries 1,onFailurerecovery event, and the env-scoped concurrency{ limit: 1, scope: "env", key: '"schedule:" + event.data.companyId' }. Change debounce to{ key: "event.data.companyId", period: "30s", timeout: "10m" }. New body: step"get-stale-locations"— select distinctlocationIdfromjobwherecompanyIdandscheduleOutdatedAt IS NOT NULLand status in Ready/In Progress/Paused; then one step per location`regen-${locationId}`invokingserviceRole.functions.invoke("schedule", { body: { locationId, companyId, userId: "system" } })sequentially. DeleteWAVE_BATCH_SIZE,IN_FILTER_CHUNK_SIZE,INVOKE_CHUNK_SIZE, the"clear-stale-reservations"step (the engine's exclusion list replaced it), the chunking loop, the"chain-next-wave"continuation, and the wave-side flag-clearing (the engine clears stamps per job in Task 7 step 5).markScheduleStaleFunction: unchanged except delete thecontinuationearly-return only if the wave no longer emits continuations (it doesn't) — keep the field tolerated in the zod schema for the nightly emitter.- Delete
reschedule-job.ts; remove its export/registration; remove the event fromevents.tsand the trigger key fromtrigger.ts. Typecheck will surface any missed reference. production.service.ts: deletetriggerJobSchedule(and its barrel export inapps/erp/app/modules/production/index.tsif listed). Every remaining caller must usenotifyScheduleInputsChanged. Grep fortriggerJobSchedulerepo-wide afterward — zero code hits (docs updated in Task 14).dates.update.tsx: remove thetriggerJobScheduleimport/call; keep the singlenotifyScheduleInputsChanged(companyId, "reorder", "Schedule reordered"). Also replacenew Date().toISOString()inupdateDatawithdatetime.timestamp()from@carbon/utilsif the date-handling check flags it (it is an instant column — acceptable either way; preferdatetime.timestamp()).nightly-replan.ts: no structural change (it emits onereorderevent per company; the wave now fans to locations). Update its comment to say "wave regenerates each location".
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/lib --filter=erp
# Expected: exit 0
grep -rn "reschedule-job\|triggerJobSchedule" packages/jobs/src packages/lib/src apps/erp/app --include="*.ts" --include="*.tsx" | grep -v ".test."
# Expected: no output
Out of scope: notifyScheduleInputsChanged call sites in ability/shift/people routes (unchanged); the mark function's scoping queries.
Task 9: Resources — workCenterShift service, validator, form, and schedule events
Depends on: Task 2 (parallel with Tasks 3–8) Files:
- Modify:
apps/erp/app/modules/resources/resources.models.ts—workCenterValidator - Modify:
apps/erp/app/modules/resources/resources.service.ts—upsertWorkCenter,getWorkCenter(s)reads - Modify:
apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx - Create:
apps/erp/app/components/Form/Shifts.tsx(multiselect) - Modify:
apps/erp/app/components/Form/index.ts— export it - Modify:
apps/erp/app/routes/x+/resources+/work-centers.new.tsxandwork-centers.$id.tsx - Copy from (precedent):
apps/erp/app/components/Form/Processes.tsx(multiselect),resources.service.ts:1879upsertWorkCenterprocesses join pattern
Steps:
- Validator: add
alwaysOn: zfd.checkbox()andshifts: z.array(z.string().min(1)).optional()toworkCenterValidator. Shifts.tsx: copyProcesses.tsxverbatim and adapt to shifts — options fromgetShiftsList-backed data (follow whatever data sourceProcessesuses; if it uses a store/hook, mirror it with the shifts equivalent; accept an optionallocationIdprop to filter options by location). Export from the Form barrel.upsertWorkCenter: mirror theprocessesjoin maintenance exactly forshifts→workCenterShiftrows (insert branch: map + insert; update branch: delete-all-by-workCenterId then reinsert; same audit fields, same error-return style).- Work-center reads: wherever the form's edit loader fetches the work center (the
$idroute loader /getWorkCenter), also fetch itsworkCenterShiftrows (select shiftId) and passshifts: string[]intoinitialValues. If the list view (workCentersview) is used for the form seed instead, adjust there — follow howprocessesreachesinitialValuestoday and do the identical thing. WorkCenterForm.tsx: below theProcessesfield add
with a helper line under the shifts field:<Shifts name="shifts" label={t`Operating shifts`} locationId={selectedLocationId} /> <Boolean name="alwaysOn" label={t`Runs 24×7 (lights-out)`} description={t`Ignore shift calendars — this machine can run unattended around the clock.`} />t`Empty = all shifts at the location`(follow the form's existing helper-text pattern; useBooleanfrom~/components/Form).- Both work-center routes' actions: after a successful
upsertWorkCenter, emitawait notifyScheduleInputsChanged(companyId, "work-center", "Work center hours changed", workCenterId)(import from~/modules/production). This wires the deadwork-centerevent kind — the mark scoping for it already exists. - Deactivation/reactivation: find the route(s) whose actions call
deleteWorkCenter(soft delete,active: false) andactivateWorkCenterinresources.service.ts(grepdeleteWorkCenter\|activateWorkCenterunderapps/erp/app/routes/x+/resources+/). Add the samenotifyScheduleInputsChanged(companyId, "work-center", "Work center deactivated"|"Work center reactivated", workCenterId)emit to each after a successful write — a deactivated WC drops out ofcapacityByWorkCenterat the next regen, so its sticky ops re-select automatically. pnpm run lingui:extractis deferred to Task 15 — do not run it here.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
grep -rn "notifyScheduleInputsChanged" apps/erp/app/routes/x+/resources+/work-centers.new.tsx apps/erp/app/routes/x+/resources+/work-centers.\$id.tsx
# Expected: one hit in each file
Out of scope: shift CRUD (people module, unchanged); the engine ladder (Task 3); seeding workCenterShift rows (none — empty = rung 2 by design).
Task 10: Job forecast surfaces — promise date + slack badges
Depends on: Task 7 Files:
- Modify:
apps/erp/app/modules/production/production.service.ts—getJobPromiseDate - Modify:
apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx - Modify:
apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx - Copy from (precedent):
JobCard.tsxL258–277 (conflict/outdated Tooltip pattern),JobHeader.tsxL231–244 (JobStatus badge block)
Steps:
getJobPromiseDate(client, jobId, companyId): reimplement to readjob.projectedCompletionAt(single select). Keep the return shape{ promiseDate, basis: "schedule", confidence }—confidence: "low"when the job has any conflicted op or a non-nullscheduleOutdatedReason, else"scheduled". Fall back to the old max-op-dueDate computation ONLY whenprojectedCompletionAtis null (pre-first-regen). This is the §7{date, confidence?}contract — callers must accept confidence as optional.JobHeader.tsx: in the badge block, when the job is active andprojectedCompletionAtis set, render a slack badge: computeslackDays= calendar-day difference betweenformatDate(projectedCompletionAt.slice(0,10))-style business day andjob.dueDateusingparseDatefrom@internationalized/date(never JSDatearithmetic — see.claude/rules/date-handling.md; slice the timestamptz to its date part per the repo pattern). Render<JobStatus status="On Track" />-style badge text:{n}d early(green/muted) or{n}d late(destructive) with a Tooltip showingtProjected completion` + formatted date. Follow the exact JSX shape of the existing Due Today/Overdue badges.JobCard.tsx(dates board): next to the existing outdated/conflict triangles add the same compact slack indicator (text-only, e.g.+2dred /-3dmuted with tooltip "Projected {date}") when the card's job row carriesprojectedCompletionAt. The loader RPCget_jobs_by_date_rangemust return it: add"projectedCompletionAt" timestamp with time zoneto the RETURNS TABLE + SELECT of the function in20260720121629_capacity-planning.sql(in-place, same file already being edited — coordinate with Task 1 if run in parallel; if Task 1 is merged, edit the migration again and re-apply the function body via the Task 2 psql method:DROP FUNCTION IF EXISTS get_jobs_by_date_range(TEXT, DATE, DATE);+ recreate +NOTIFY pgrst), then re-runpnpm run generate:typesand thread the field through the dates board loader types.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
grep -n "projectedCompletionAt" apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
# Expected: >= 1 hit in each
Out of scope: Monte Carlo bands (confidence stays a string enum); MES surfaces.
Task 11: Expedite what-if — service, route, "Best case" UI
Depends on: Task 7 Files:
- Modify:
apps/erp/app/modules/production/production.service.ts— addgetJobExpediteForecast - Create:
apps/erp/app/routes/x+/job+/$jobId.expedite.tsx(action-only route) - Modify:
apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx— menu action + result modal - Modify:
apps/erp/app/utils/path.ts—path.to.jobExpedite(jobId) - Copy from (precedent): an existing action-only job route in
apps/erp/app/routes/x+/job+/(e.g. the job status/recalculate action route — pick the nearest action-only sibling and mirror itsrequirePermissions+ flash shape); JobHeader's existing dropdown menu items for the trigger.
Steps:
- Service:
— reads the job'sexport async function getJobExpediteForecast( client: SupabaseClient<Database>, jobId: string, companyId: string, userId: string )locationId, thenclient.functions.invoke("schedule", { body: { locationId, companyId, userId, expediteJobId: jobId } }); returns{ data: { projectedCompletionAt, cause }, error }from the response'sexpediteobject. - Route: POST-only;
requirePermissions(request, { view: "production" })(read-only what-if — no writes happen); call the service; return the result asdata(...)for a fetcher (no redirect). - UI: add a "Best case…" item to JobHeader's existing actions menu (visible for active jobs). On click,
useFetcher().submitto the route; while loading show the fetcher spinner pattern used elsewhere in the header; on data, open a smallModal(copy the nearest confirm-modal in the Jobs UI) showing: current projection, expedited projection, andcause("bottleneck" sentence) — plainformatDaterendering, both with day-part slices.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: persisting expedite results; auto-repriotizing the job (the modal only informs); quote-level CTP (v1.x per spec §7).
Task 12: Capacity view — Scheduled vs Available on one date basis
Depends on: Tasks 2, 9 Files:
- Modify:
apps/erp/app/modules/production/peopleCapacity.server.ts - Modify:
apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsx - Modify:
apps/erp/app/routes/x+/schedule+/people.tsx— loader inputs - Modify:
apps/erp/app/modules/production/production.service.ts—getPeopleCapacityOperationslookback
Steps:
- Server ladder resolver in
peopleCapacity.server.ts:getWorkCenterCalendarHoursByDay(workCenters, workCenterShifts, locationShifts, weekDates, timezone): Map<workCenterId, Map<date, number>>— pure TS mirror of the engine ladder at day granularity:alwaysOn→ 24; WC shifts → Σ shift hours whose weekday flag covers that date; else location shifts; else 8 on Mon–Fri / 0 weekend. The loader (people.tsx) fetchesworkCenterShiftrows for the location's work centers (one.in()query) and passes them in. Note in a comment that the engine (Deno) owns the authoritative ladder; this is display math. Scheduledseries: in the reservation fold, replaceworkMs = workHours != null ? workHours * HOUR_MS : spanMswithworkMs = workHours != null ? workHours * HOUR_MS : min(spanMs, calendarMsWithinSpan)wherecalendarMsWithinSpanuses the day-hours map — fixes the legacy null-workHours overcount.AvailableinPeopleCapacity.tsx: base = the calendar hours map (never people-derived). When the station has assignments that day, show people-hours as a secondary annotation (small text under the cell:{peopleHours}h staffed), NOT as a replacement — this removes the fallback cliff at L179–182.Loadverdict:delta = scheduledHours − availableHoursper day (was demand − available). Keep the+Xh / Xh freerendering. Move the due-date Demand series to a "Due" sub-tab (the component already has sub-tab structure for coverage — follow it), clearly labeledtDue (by due date)`.- Assumption badge: when every work center resolved via rung 2 render
tHours assumed from location shifts; rung 3 → `t`No shifts configured — assuming Mon–Fri, 8h days(single banner above the grid; use the existing banner/Alert pattern from@carbon/react— grepAlertusage inui/Schedule/). - Past-due truncation: in
people.tsxchangelookbackStartfromweekStart − 28dto the earliest open-op due date — simplest correct form: drop thestartDatefloor fromgetPeopleCapacityOperationswhen computing the past-due bucket (passstartDate: null→ service omits the.gte("dueDate", ...)filter; released-only status filters already bound the set).
Verify:
pnpm exec turbo run typecheck --filter=erp
pnpm --filter erp test -- resourceTimeline
# Expected: typecheck exit 0; existing resourceTimeline tests still pass
Out of scope: PeopleMatrix needed-count ladder unification and the browser-tz "today" highlight (pre-existing, noted in the critique — separate cleanup); the People board/week views.
Task 13: Engine determinism + performance-envelope tests
Depends on: Tasks 3–7 Files:
- Create:
packages/database/supabase/functions/lib/scheduling/determinism.test.ts - Create:
packages/database/supabase/functions/lib/scheduling/envelope.test.ts
Steps:
- Build a fixture
MasterDataProvider(in-memory, no DB) — the interface is constructor-injected everywhere, so implement it over plain objects: ~6 work centers on the ladder's three rungs, 2 gated processes, 4 employees with shifts, a manning-board day, 20 jobs / ~120 ops with dependencies. IfSchedulingEnginestill requires a livedb/clientfor non-read work in the run path (it should not after Task 7's dry-run flag — dry-run must touch neither), STOP and report rather than mocking Kysely. determinism.test.ts: run the whole batch twice in dry-run with the same injectednow; assert the two runs' planned reservations are deeply equal (same multiset of{resourceKind, resourceId, operationId, startAt, endAt}) and every job's projected completion matches. Also assert zero placements fall outside the machine windows of their work center (spot-check a rung-3 WC: no reservation minutes on Saturday/Sunday).envelope.test.ts: generate 2,000 ops across 200 jobs / 20 work centers programmatically; assert the full dry-run batch completes in under 10_000 ms (performance.now()bracketing). Mark it so it can be skipped in constrained CI if needed (Deno.test({ name, ignore: Deno.env.get("SKIP_ENVELOPE") === "1", fn })).
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/determinism.test.ts lib/scheduling/envelope.test.ts
# Expected: both pass; envelope reports elapsed < 10000ms
Out of scope: load-testing the deployed edge function; Monte Carlo sampling.
Task 17: Machine downtime derived from maintenance dispatches
Depends on: Tasks 2, 3 (ladder); form/emitter parts parallel with Tasks 4–8 Files:
- Modify:
packages/database/supabase/functions/lib/scheduling/calendar-utils.ts— addsubtractIntervals - Modify:
packages/database/supabase/functions/lib/scheduling/master-data-provider.ts— downtime read + ladder subtraction - Modify:
packages/database/supabase/functions/lib/scheduling/machine-availability.test.ts— downtime cases - Modify:
apps/erp/app/modules/resources/resources.models.ts— dispatch validator - Modify: the ERP maintenance-dispatch form + its create/edit routes (grep
insertMaintenanceDispatch\|updateMaintenanceDispatchunderapps/erp/app/routes/x+/resources+/and the form underapps/erp/app/modules/resources/ui/) - Modify: the MES dispatch write routes (
apps/mes/app/routes/x+/dispatch*.tsx— the maintenance-dispatch routes) andapps/mes/app/services/for the notify helper - Copy from (precedent):
subtractAbsencesinpeople-utils.ts(window subtraction),Booleanfield usage inWorkCenterForm.tsx(Task 9)
Steps:
calendar-utils.ts: addexport function subtractIntervals(windows: CalendarWindow[], outages: CalendarWindow[]): CalendarWindow[]— pure interval subtraction over disjoint sorted lists (split windows around outage overlaps; drop empty remainders). Unit-test alongsideintersectWindows.- Provider: in
getWorkCenterAvailability, after resolving the ladder windows per work center, load open offline dispatches in ONE query:maintenanceDispatchwherecompanyId,takesWorkCenterOffline = true,status NOT IN ('Completed','Cancelled'), and (workCenterId IN (ids)OR id IN (selectmaintenanceDispatchIdfrommaintenanceDispatchWorkCenterwhereworkCenterId IN (ids))) — two selects unioned in TS is fine; never per-WC queries. Each dispatch contributes an outage[actualStartTime ?? plannedStartTime ?? createdAt, actualEndTime ?? plannedEndTime ?? rangeEnd)to itsworkCenterIdAND every joined work center. ApplysubtractIntervals(windows, outages)per affected WC.alwaysOnmachines are subtracted too (a broken lights-out machine is still broken). - Tests in
machine-availability.test.ts: (a) an outage with aplannedEndTimesplits the week's windows and an op flows around it; (b) an open-ended outage (no end estimate) empties the WC's windows to the horizon → ungated allocation returns the "No working time available" conflict; (c) a Completed dispatch contributes nothing. - Dispatch validator + form: add
takesWorkCenterOffline: zfd.checkbox()to the maintenance-dispatch validator inresources.models.ts; add aBooleanfield to the ERP dispatch form — labeltTakes work center offline, description `t`While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed).Place it next to the planned start/end time fields. - Emitters (the schedule must react to downtime edits): in the ERP dispatch create/edit/status routes, after a successful write where
takesWorkCenterOfflineis set OR was just cleared OR the status moved to/from Completed/Cancelled OR planned/actual times changed on a flagged dispatch, emitnotifyScheduleInputsChanged(companyId, "work-center", "Machine downtime changed", workCenterId)once per affected work center id (primary + join rows). For MES: the maintenance-dispatch write routes need the same emit — copy the 6-linenotifyScheduleInputsChangedhelper fromproduction.service.ts:5403intoapps/mes/app/services/operations.service.ts(same dynamic@carbon/jobsimport pattern) and call it from the MES dispatch actions. If MES routes turn out not to write dispatch status/timing (display-only), skip the MES emit and note it in the task checklist — verify by grepping the MES dispatch routes for.update(/insertMaintenanceDispatch. - Do not create any downtime table or scheduled sync — the windows are derived at snapshot-build time, which is what makes dispatch completion self-healing.
Verify:
cd packages/database/supabase/functions && deno test lib/scheduling/machine-availability.test.ts lib/scheduling/calendar-utils.test.ts
# Expected: all pass, including the three downtime cases
pnpm exec turbo run typecheck --filter=erp --filter=mes
# Expected: exit 0
Out of scope: maintenance scheduling/PM plans (maintenanceSchedule — future: planned PM windows could pre-book downtime, note only); OEE math; any change to dispatch statuses.
Task 18: Newly-late digest notification
Depends on: Tasks 7, 8 Files:
- Modify:
packages/notifications/src/index.ts— newNotificationEventmember + topic/heading/CTA registrations - Modify:
packages/jobs/src/inngest/functions/notifications/content.ts— content case - Modify:
packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts— notify step - Copy from (precedent): an existing digest-capable event in the same files — grep
documentIdsinpackages/jobs/src/inngest/functions/notifications/and follow whichever event already builds a multi-document digest (e.g. the gauge-calibration or quote-expired flow);carbon/notifypayload shape is defined inpackages/lib/src/events.ts:16
Steps:
packages/notifications: addJobsProjectedLate = "jobs-projected-late"toNotificationEvent; register it in every exhaustive map the package keeps (getNotificationTopic,getNotificationEmailHeading,getNotificationEmailCtaLabel, and anyisRecurringNotificationEvent/destination map the compiler forces) — heading"Jobs projected late", CTA"View job". Do NOT add it todefaultDestinationsinnotify.ts(in-app only by default; email/Slack stay opt-in).content.ts: add theJobsProjectedLatecase following the digest precedent — title`${n} job(s) newly projected late`(singular/plural), body listing readable job ids (comma-joined, cap at 10 + "+n more") and the triggering reason when provided; link target = the first job (documentId ?? documentIds[0]convention per the payload comment).- Wave: in
scheduleReplanWaveFunction, collect each location invoke'snewlyLatearray (Task 7 response). After all regens, add step"notify-newly-late": group entries byassignee, drop null assignees, and for each assigneestep.sendEvent("notify-newly-late-" + userId, { name: "carbon/notify", data: { event: NotificationEvent.JobsProjectedLate, companyId, documentIds: jobIds, recipient: { type: "user", userId }, body: reason } })— one digest per assignee per wave. Pass the wave event'sreasonthrough. Send nothing when the array is empty. - Idempotency note: "newly late" is edge-triggered by construction (prior vs new projection inside
persistChanges), so a second identical regen produces no entries — no dedup table needed. Do not add one.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/notifications --filter=@carbon/jobs
# Expected: exit 0 (exhaustive NotificationEvent maps force every registration point)
grep -n "JobsProjectedLate" packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts packages/jobs/src/inngest/functions/notifications/content.ts packages/notifications/src/index.ts
# Expected: >= 1 hit in each file
Out of scope: email/Slack default delivery (opt-in only); a configurable planner recipient group (follow-up, per spec); notifying on jobs that recovered to on-time.
Task 14: Docs sync
Depends on: Tasks 1–12, 17, 18 Files:
- Modify:
.claude/rules/scheduling-data-structures.md - Modify:
apps/erp/app/modules/production/AGENTS.md - Modify:
apps/erp/app/modules/resources/AGENTS.md - Modify:
.ai/specs/2026-08-12-forecast-first-finite-scheduling.md— changelog entry
Steps:
- Rewrite the affected sections of
scheduling-data-structures.md: engine pipeline (no backward pass, no modes, whole-location payload, ladder windows incl. maintenance-dispatch downtime subtraction, remaining-work netting, projectedCompletionAt, expedite), trigger chain (nocarbon/reschedule-job; wave = location regen, 30s debounce, newly-late digest notification), job ordering (deadline class → due date), and delete the dispatch-rule paragraph. Only document what the code now does — verify each claim against the files as written. production/AGENTS.md: replacetriggerJobScheduleguidance withnotifyScheduleInputsChanged; update the Scheduling concept paragraph (ladder, forward-ASAP, projectedCompletionAt, priority = placement order); removeschedulingPolicyfrom the data-model table; addworkCenterShiftmention.resources/AGENTS.md: update the Work Center concept ("always open 24×7 — no capacity knobs" is now wrong): operating shifts viaworkCenterShift,alwaysOn, ladder defaults.- Spec changelog: add "2026-08-12: implementation landed via .ai/plans/2026-08-12-forecast-first-finite-scheduling.md" once Tasks 1–13 are checked (leave unchecked items accurate if the run stops early).
Verify:
grep -rn "triggerJobSchedule\|schedulingPolicy\|dispatch rule" .claude/rules/scheduling-data-structures.md apps/erp/app/modules/production/AGENTS.md apps/erp/app/modules/resources/AGENTS.md
# Expected: no output (except historical changelog lines, which should not exist in these files)
Out of scope: the customer docs site (docs/) — the feature ships behind ERP screens already documented at concept level; flag for a follow-up instead of authoring here.
Task 15: i18n extraction for new UI strings
Depends on: Tasks 9–12 Files:
- Modify:
packages/locale/locales/*/erp.po(generated by extract)
Steps:
pnpm run lingui:extract- Invoke the
/translateskill to fill the new emptymsgstrentries (it fans out to Haiku subagents and merges deterministically). pnpm run lingui:cleanif/translatedid not already run it.
Verify:
grep -c 'msgstr ""' packages/locale/locales/es/erp.po
# Expected: 0 (no untranslated strings remain)
Out of scope: adding locales; MES catalog (no MES strings changed).
Task 16: Browser verification via /test
Depends on: all prior tasks; requires the local stack running (crbn up) and the schema delta applied (Task 2). If the stack is not running, STOP and ask the user to boot it — never boot or reset it yourself.
Steps:
- Invoke the
/testskill scoped to this branch's diff with this scenario list: a. Resources → Work Centers → edit one: set "Operating shifts" to one shift, save, reopen — selection persists. Toggle "Runs 24×7", save, reopen — persists. b. Schedule → Dates board: drag a job to a new due-date column — the card shows the amber "outdated" triangle, and within ~1 minute (30s debounce + regen) the stamp clears on reload and the card shows a slack indicator. c. Open a job header: slack badge renders with a tooltip showing the projected completion date; "Best case…" runs and the modal shows current vs expedited projections. d. Schedule → People → Capacity: Load compares Scheduled vs Available; a station with no assignments shows calendar hours (not 0/24); the assumption banner appears if the dev company lacks shifts; the "Due" sub-tab still shows due-date demand. e. Confirm no reservation bars on the resource timeline fall on a weekend for a non-alwaysOnwork center (dev-seed shifts permitting). f. Maintenance downtime: create a dispatch against a busy work center with "Takes work center offline" and a planned end 2 days out — after the regen, that WC's reservations vacate the outage window (resource timeline) and Capacity shows reduced Available; complete the dispatch — hours return at the next regen. g. Newly-late notification: with a job assigned to the test user, create the downtime from (f) sized to push that job past its due date — the in-app notification bell shows one "jobs newly projected late" digest naming the job; re-running the same regen adds no duplicate. - Capture screenshots per the playbook convention; cache the successful playbook.
Verify: /test run report with all scenarios passing (or precise failure notes fed back into the relevant task).
Out of scope: load/perf testing in the browser; MES flows.
Extension: Dual Dates (2026-08-15 → 2026-08-18, complete)
Absorbed from the standalone 2026-08-15-dual-dates-due-vs-projected plan at
consolidation; full task text in git history of that file. All 12 tasks landed,
one commit per task:
- D1 Migration
20260818031629_dual-dates.sql(projectedCompletionAt + RPC outputs) - D2 Apply + regenerate types
- D3
need-by-calculator.ts(pure backward walk + calendarAdapters, 13 tests) - D4 Engine wiring: need-by pre-pass, unified diff-writing persist, pins un-frozen
- D5 Placement-isolation + target-stability determinism guards (mutation-tested)
- D6 Services: promise-date fallback removed, projection threaded to boards/MES
- D7 BOP dual dates + behind-target amber
- D8 Ops-board ItemCard + MES operation detail projected line
- D9
composeBehindTargetfirst-behind-target attribution on the job cause - D10 Docs sync (rule + AGENTS.md + adoption test plan)
- D11 i18n (96 strings across 12 locales)
- D12 Browser verification — 5/5 PASS; found+fixed: weekly-pattern working-day
test (year-runaway) and pin's missing
schedule.inputs.changedemit
Engine suite after extension: 155 passed / 0 failed.