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.
Job Operation Batching — implementation plan
Spec: .ai/specs/2026-08-21-job-operation-batching.md (all questions resolved; status in-progress)
Research: .ai/research/job-operation-batching.md
Branch: feat/job-operation-batching-v2 (cut from main 2026-08-21)
Replanned: 2026-08-21 (v2 of this plan — deterministic salvage mechanics)
Executor ground rules
- Refs.
SRC=feat/job-operation-batching(tip8f7fc8a67) is the salvage source: it already contains the two-phase completion,batch-time-split, the guarded RPC, and the status-aware i18n'd MES page.PR1137=origin/loop/1010-20260714010219is used for exactly one test file. Nevergit mergeorgit cherry-pickfrom either. - Porting a NEW file (does not exist on this branch):
git show $SRC:<path> > <path>, then apply the edits the task lists. - Porting changes to an EXISTING file (main has drifted since July):
Clean apply → done. Conflict markers → resolve using the task's "intent" line (each task states what the change accomplishes, so you resolve toward that outcome, keeping main's surrounding code).git diff $(git merge-base main $SRC) $SRC -- <path> | git apply --3waygit applyrefuses entirely → make the change by hand from the intent line, usinggit diff $(git merge-base main $SRC) $SRC -- <path>as reference. - Never rebuild the database.
pnpm db:migrateapplies pending migrations; if the local DB is unreachable, STOP and tell the user. - Typecheck is always scoped (
--filter=erp,--filter=mes,--filter=@carbon/utils). Never whole-repo (OOMs). - Commit per task via
/check-and-commit. Never push without explicit approval. - After any migration:
pnpm run generate:typesBEFORE typechecking. Thengit diff --stat packages/database/src/types.ts— if the diff is dominated by deletions of tables unrelated to this feature, STOP and ask the user (stale local DB) instead of committing mass deletions. - Banned term:
git grep -inE 'st[i]tch' -- ':!*.po' ':!.ai/'over your changed files must return nothing. - Spec wins over plan; code wins over both — surface conflicts, don't improvise.
Conflict watch — capacity planning (PR #1151, origin/naveen/capacity-planning)
Open 39k-line PR, likely to merge first. Verified collisions (tip f17db29ab):
processesview: both migrations recreate it; theirs uses an explicit column list (nop.*). If it lands first, Task 2's view SQL must be rebuilt from THEIR list plus"batchable". If we land first, tell their PR to add"batchable"to the list.get_active_job_operations_by_location: theirs changes the signature (addswork_center_ids TEXT[]) and addshasConflict/conflictReason. Task 2's pre-flight fails loudly if theirs landed — that's the rebase signal, not a plan bug. Second-lander merges both column sets.- Same-hunk UI conflicts: they add
requiresAbilityat the same spots we addbatchable(ProcessForm.tsxaftercompleteAllOnScan;components/Form/Process.tsxinitialValues). Resolution: keep both fields. - Compatible column adds (no action):
process.requiresAbilityvsbatchable;jobOperation.readyAtvsjobOperationBatchId. - Shared-file churn (schedule Kanban, both
path.ts, MES operations files, production/resources models): mergeable. Generated types: regenerate, never hand-merge. - Semantic follow-up (NOT this plan's scope): their
capacityReservationis per-operation with zero batch awareness → batch members would N×-over-book a work center, and nightly replan could re-assign one member's work center, splitting the batch. Raise on #1151 review; post-merge fix is coalescing reservations perjobOperationBatchIdand pinning batched ops.
Progress
- Task 1: Port the batch-time-split util (+ tests + Deno mirror)
- Task 2: Consolidated migration + sequence seed + config.toml
- Task 3: Regenerate DB types
- Task 4: Resources — process
batchableflag end-to-end - Task 5: ERP production models + services
- Task 6:
batch-operationsedge function + resume quantity contract - Task 7: ERP batch planning board + schedule integration
- Task 8: MES — kanban collapse, batch page, complete route
- Task 9: Port and adapt the tests
- Task 10: i18n extraction + translation fill
- Task 11: AGENTS.md + spec changelog sync
- Task 12: Full verification gate
- Task 13: Browser verification via /test
Dependencies
Task 1 independent. Task 2 → 3 → {4, 5, 6}. Task 6 also needs 1. Task 7 needs 5. Task 8 needs 5 + 6. Task 9 needs 2. Task 10 needs 7 + 8. Tasks 11 → 12 → 13 close out. Tasks 4 and 5 may run in parallel.
Task 1: Port the batch-time-split util (+ tests + Deno mirror)
Depends on: none Files:
- Create:
packages/utils/src/batch-time-split.ts - Create:
packages/utils/src/batch-time-split.test.ts - Create:
packages/database/supabase/functions/shared/batch-time-split.ts - Modify:
packages/utils/src/index.ts— addexport * from "./batch-time-split"; - Copy from (precedent): the same three paths on
$SRC
Steps:
- Copy all three files per ground rule 2.
- Add the export line to
packages/utils/src/index.tsalongside the existingexport * fromlines. - Confirm both TS files export
buildBatchCompletionPlan,planBatchCompletion,assertBatchCompletionMembership,sliceEventByWeight(the edge fn imports all four). Missing export → STOP and report.
Verify:
pnpm --filter @carbon/utils test
# Expected: batch-time-split.test.ts runs, all tests pass, 0 failures
Out of scope: changing the util's math or API.
Task 2: Consolidated migration + sequence seed + config.toml
Depends on: none Files:
- Create:
packages/database/supabase/migrations/{timestamp}_job-operation-batching.sql(viapnpm db:migrate:new) - Modify:
packages/database/supabase/functions/lib/seed.data.ts— intent: add the new-company sequence row{ table: "jobOperationBatch", name: "Operation Batch", prefix: "BAT", next: 0, size: 6, step: 1 }to the sequences array - Modify:
packages/database/supabase/config.toml— intent: add[functions.batch-operations]withenabled = true,verify_jwt = true - Copy from (precedent):
$SRC:packages/database/supabase/migrations/20260707135312_job-operation-batching.sql(base) and$SRC:packages/database/supabase/migrations/20260716120250_batchable-operations-rpc-started-guard.sql(RPC body)
Steps:
- Pre-flight — confirm the definitions the salvage SQL was built on are still
newest (they were on 2026-08-21; this catches capacity-planning landing):
Either expectation fails → STOP: rebase the ported view/RPC bodies onto the newer definitions first (see Conflict watch).git fetch origin main git grep -l "get_active_job_operations_by_location" origin/main -- packages/database/supabase/migrations/ | tail -1 # Expected: 20260531084723_rework-serial-flow.sql git grep -l 'VIEW "processes"' origin/main -- packages/database/supabase/migrations/ | tail -1 # Expected: 20260721004140_operation-type-consolidation.sql (def is textually identical to the salvage SQL's) pnpm db:migrate:new job-operation-batching(never hand-pick a timestamp).- Fill the file with the salvage base migration, then make exactly three edits:
a. Replace the enum creation with:
(3 values — noDO $$ BEGIN CREATE TYPE "jobOperationBatchStatus" AS ENUM ('Active', 'Completing', 'Completed'); EXCEPTION WHEN duplicate_object THEN NULL; END $$;Cancelled,Completingfrom day one.) b. Replace the base file'sget_batchable_operationsfunction with the version from the guard migration (it adds the started-opNOT EXISTS (SELECT 1 FROM "productionEvent" …)predicate and thebatchStatusreturn column). KeepSECURITY INVOKER— it is the tenant-scoping mechanism and Task 9's test pins it. c. In that function's lane branch, changeOR b."status" = 'Active'to:
Everything else from the base file stays verbatim:OR b."status" IN ('Active', 'Completing')process.batchablecolumn +processesview recreation,jobOperationBatchtable (composite PK, RLS, audit columns),jobOperation.jobOperationBatchIdFK + partial index,productionEvent.jobOperationBatchIdFK + partial index, the existing-companysequenceINSERT, and the additiveget_active_job_operations_by_locationre-declaration. Do NOT port the old..._completing-status.sqlmigration (obsolete — the enum already has the value). - Apply the seed.data.ts and config.toml intents (ground rule 3; both hunks are small and should apply cleanly).
pnpm db:migrate
Verify:
grep -c "Cancelled" packages/database/supabase/migrations/*_job-operation-batching.sql
# Expected: 0
grep -n "IN ('Active', 'Completing')" packages/database/supabase/migrations/*_job-operation-batching.sql
# Expected: exactly 1 match
grep -c "NOT EXISTS" packages/database/supabase/migrations/*_job-operation-batching.sql
# Expected: >= 1 (started-op guard present)
pnpm db:migrate
# Expected: applies with no error
Out of scope: other tables; the issue / post-production-event functions;
existing triggers.
Task 3: Regenerate DB types
Depends on: Task 2 Files:
- Modify (generated):
packages/database/src/types.ts,packages/database/supabase/functions/lib/types.ts
Steps:
- Both files carry uncommitted local edits from unrelated licensing work.
Save
git diff packages/database/src/types.tsto the scratchpad first and tell the user if regeneration clobbers those hunks. pnpm run generate:types- Ground rule 7 check on the diff.
Verify:
grep -n '"Completing"' packages/database/src/types.ts | head -2
# Expected: jobOperationBatchStatus = "Active" | "Completing" | "Completed" (no "Cancelled" in this enum)
grep -c "jobOperationBatch" packages/database/src/types.ts
# Expected: > 0
Out of scope: hand-editing generated files.
Task 4: Resources — process batchable flag end-to-end
Depends on: Task 3 Files (all Modify, ground rule 3; intent per file):
apps/erp/app/modules/resources/resources.models.ts—processValidatorgainsbatchable: zfd.checkbox()apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx— aBooleanfieldname="batchable", label "Batchable", description "Multiple jobs can run on this process at the same time (laser table, furnace, plating bath)", inserted after thecompleteAllOnScanBoolean (same idiom)apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx— a Batchable boolean badge column (same idiom as the Complete All On Scan column)apps/erp/app/routes/x+/resources+/processes.$processId.tsxandprocesses.new.tsx— passbatchablethrough insert/update payloadsapps/erp/app/components/Form/Process.tsx—batchable: falsein the create-modal initialValuesapps/erp/app/components/Form/Processes.tsx— carry the flag in the select's row type
Steps:
- Port each file per ground rule 3.
upsertProcessinresources.service.tsneeds no change (the validator spread carries the field — the salvage diff has no service hunk). If typecheck disagrees, STOP and report rather than casting.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
grep -n "batchable" apps/erp/app/modules/resources/resources.models.ts
# Expected: 1 line in processValidator
Out of scope: work centers; abilities; any other resources entity.
Task 5: ERP production models + services
Depends on: Task 3 Files (Modify, ground rule 3; intent per file):
apps/erp/app/modules/production/production.models.ts— addjobOperationBatchStatus = ["Active", "Completing", "Completed"] as const(the salvage version also has"Cancelled"— drop it; do NOT touch the JOB status consts that legitimately contain"Cancelled"), pluscreateJobOperationBatchValidator,updateJobOperationBatchValidator(add/remove/dissolve intents),completeJobOperationBatchValidator(member rows, int quantities ≥ 0,zfd.repeatablefor array fields, no max-size rule)apps/erp/app/modules/production/production.service.ts— addgetJobOperationBatch,getBatchableOperations(rpc wrapper),getActiveBatchesByProcess, and the four invoke wrapperscreateJobOperationBatch/addToJobOperationBatch/removeFromJobOperationBatch/dissolveJobOperationBatch, all(client, ...) → {data, error}shape
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
grep -A3 "jobOperationBatchStatus" apps/erp/app/modules/production/production.models.ts | head -4
# Expected: exactly Active, Completing, Completed
Out of scope: scheduling/deadline services; non-batch validators.
Task 6: batch-operations edge function + resume quantity contract
Depends on: Tasks 1, 3 Files:
- Create:
packages/database/supabase/functions/batch-operations/index.ts - Copy from (precedent):
$SRC:packages/database/supabase/functions/batch-operations/index.ts(604 lines, already two-phase)
Steps:
- Copy wholesale (ground rule 2).
- Confirm by grep (do not rewrite):
FOR UPDATEbatch lock,planBatchCompletionslice/resume branch, guardedActive → CompletingandCompleting → Completedflips,postedToGLskip, Phase 2 throwing on first error (that IS the spec's fail-fast). - Add the resume payload contract. In Phase 1's
phase === "resume"branch, BEFORE the existing event reload/return, insert (adapt local names — the validated payload array is the task'smembers):
Assumption: batch members were unstarted at batch time and batch completion is the only// Resume contract: the payload must match what Phase 1 already recorded — // an edited quantity on retry is rejected, never silently ignored. const recorded = await trx .selectFrom("productionQuantity") .select(["jobOperationId", "type", "quantity"]) .where("jobOperationId", "in", members.map((m) => m.jobOperationId)) .where("companyId", "=", companyId) .execute(); const sums = new Map<string, { produced: number; scrap: number }>(); for (const r of recorded) { const s = sums.get(r.jobOperationId) ?? { produced: 0, scrap: 0 }; if (r.type === "Production") s.produced += Number(r.quantity); if (r.type === "Scrap") s.scrap += Number(r.quantity); sums.set(r.jobOperationId, s); } const mismatches = members.filter((m) => { const s = sums.get(m.jobOperationId) ?? { produced: 0, scrap: 0 }; return s.produced !== m.quantity || s.scrap !== (m.scrapQuantity ?? 0); }); if (mismatches.length > 0) { const detail = mismatches .map((m) => { const s = sums.get(m.jobOperationId) ?? { produced: 0, scrap: 0 }; return `${m.jobOperationId}: ${s.produced} produced / ${s.scrap} scrap`; }) .join(", "); throw new Error( `Quantities were already recorded for this batch (${detail}). ` + `Retry with the recorded values; corrections happen after completion.` ); }productionQuantitywriter betweenActiveandCompleting, so per-op sums equal Phase-1 inserts. If the ported file shows another writer in that window, STOP and report. - Confirm the import of
../shared/batch-time-split.tsresolves (Task 1).
Verify:
cd packages/database/supabase/functions && deno check batch-operations/index.ts; cd -
# Expected: no type errors. If deno is not installed, note the skip in the run
# log and rely on Task 12's gates.
grep -n "already recorded" packages/database/supabase/functions/batch-operations/index.ts
# Expected: 1 match
Out of scope: issue, post-production-event, other functions; error
aggregation (fail-fast is locked).
Task 7: ERP batch planning board + schedule integration
Depends on: Task 5 Files:
- Create (ground rule 2):
apps/erp/app/modules/production/ui/Schedule/Batching/BatchingBoard.tsx,Batching/types.ts,Batching/index.ts,apps/erp/app/routes/x+/schedule+/batching.tsx,batching.update.tsx - Modify (ground rule 3; intent per file):
apps/erp/app/utils/path.ts—scheduleBatching+scheduleBatchingUpdateroute paths, and in theexternalblock next tomesJobOperation(line ~896):mesBatch: (id: string) => \${MES_URL}/x/batch/${id}``apps/erp/app/routes/x+/schedule+/operations.tsx— loader passes the RPC's new batch columns through to the kanban items.../Schedule/Kanban/ScheuleNavigation.tsx(filename sic) — "Batching" nav entry.../Schedule/Kanban/components/ItemCard.tsx—BAT…badge for batched ops; card menu gains "Batch planning" (nav, process pre-filtered) for batchable unbatched ops and a guarded "Remove from batch" for batched ones.../Schedule/Kanban/types.ts—processBatchable/jobOperationBatchId/batchReadableIdon the item type
- Copy from (precedent): same paths on
$SRC; badge idiom for step 2c from$SRC:apps/mes/app/routes/x+/batch.$batchId.tsx(~lines 201–211)
Steps:
- Port all files. Keep three v1 bug fixes that are already in the salvage:
route imports concrete files (
./BatchingBoard,./types), never a new directory barrel (Vite SSR cache bug); shared UI types live inBatching/types.ts, not the route (tsgo inference bug); array form fields usezfd.repeatable. - Add
Completingread-only lanes (new work — salvage board is Active-only): a.Batching/types.ts:status: "Active" | "Completing"onBatchLaneData. b.batching.tsxloader, lane-partition block: thread the RPC'sbatchStatusinto each lane (status: r.batchStatus ?? "Active"). c.BatchingBoard.tsx: whenlane.status === "Completing"— don't register the lane as a droppable, hide dissolve + work-center controls, render a yellowCompletingBadge, render an external link "Completion in progress — retry in Shop Floor" topath.to.external.mesBatch(lane.id), and render member cards without drag handles.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
grep -n "mesBatch" apps/erp/app/utils/path.ts
# Expected: 1 helper
grep -c "Completing" apps/erp/app/modules/production/ui/Schedule/Batching/BatchingBoard.tsx
# Expected: >= 2 (lane gating + badge)
Out of scope: board redesign; MRP/auto-suggestions; the operations board's drag logic beyond the listed intents.
Task 8: MES — kanban collapse, batch page, complete route
Depends on: Tasks 5, 6 Files:
- Create (ground rule 2):
apps/mes/app/routes/x+/batch.$batchId.tsx(already status-aware: badge,canRunTimer = status === "Active", "Retry Completion" relabel, live timer,<Trans>i18n),apps/mes/app/routes/x+/batch.$batchId.complete.tsx(singleinvoke("batch-operations", { type: "complete" }), no issue/GL loop) - Modify (ground rule 3; intent per file):
apps/mes/app/services/models.ts— batch status const (3 values — drop"Cancelled"if the salvage hunk has it) +completeJobOperationBatchValidatorapps/mes/app/services/operations.service.ts—getJobOperationBatch,startBatchProductionEvent, batch-aware event helpersapps/mes/app/utils/path.ts—batch+batchCompletepath helpersapps/mes/app/routes/x+/operations.tsx— loader collapses rows sharingjobOperationBatchIdinto one kanban card (member count, summed quantity, batch readableId)apps/mes/app/components/Kanban/components/ItemCard.tsx— batch card renders the BAT badge and links to the batch viewapps/mes/app/components/Kanban/types.ts— batch fields on the item type
- Copy from (precedent): same paths on
$SRC
Steps:
- Port everything.
operations.tsxhas the largest drifted hunk (108 lines vs capacity-adjacent churn on main) — expect a 3-way conflict; resolve toward the collapse intent while keeping main's newer loader code. - Keep two v1 bug fixes already in the salvage page: completion pre-fill reads
operationQuantity(NOTtargetQuantity ?? operationQuantity— target is 0, not null, so??pre-filled 0), and per-member fields useNumberControlled. grep -n "Cancelled" apps/mes/app/routes/x+/batch.\$batchId.tsx— expected 0; remove any dead branch found.
Verify:
pnpm exec turbo run typecheck --filter=mes
# Expected: exit 0
grep -n "operationQuantity" "apps/mes/app/routes/x+/batch.\$batchId.tsx" | head -3
# Expected: pre-fill reads operationQuantity
grep -c "Trans" "apps/mes/app/routes/x+/batch.\$batchId.tsx"
# Expected: > 5
Out of scope: per-operation MES flows (x+/complete.tsx, start/end
routes); picking/issue UI.
Task 9: Port and adapt the tests
Depends on: Task 2 Files:
- Create:
apps/erp/test/batching-migration-guards.test.ts— from$SRC - Create:
apps/erp/test/batching-tenant-scope-and-fk-locks.test.ts— from$PR1137 - Create:
apps/mes/app/services/models.batch.test.ts— from$SRC
Steps:
- Copy all three (ground rule 2).
- Both migration-reading tests reference old migration filenames
(
20260707135312_...,20260716...). Point everyread(...)at the single Task-2 file (find it:ls packages/database/supabase/migrations/*_job-operation-batching.sql). - In the guards test, add two assertions: the enum line contains no
Cancelled; the lane branch matchesIN \('Active', 'Completing'\). - In the tenant-scope test, keep every property it pins (
SECURITY INVOKER, FK/lock behavior); where an assertion targets #1137's 4-migration split, rewrite it against our consolidated file — never delete the property. models.batch.test.ts: align validator import names with ourapps/mes/app/services/models.tsexports if they differ.
Verify:
pnpm run test
# Expected: all three new test files run and pass; no previously-green test breaks
Out of scope: DB-connected integration tests.
Task 10: i18n extraction + translation fill
Depends on: Tasks 7, 8 Files:
- Modify (generated):
packages/locale/locales/*/erp.po,packages/locale/locales/*/mes.po
Steps:
pnpm lingui:extract- Invoke
/translateto fill new emptymsgstrentries. pnpm lingui:cleanif the script exists.
Verify:
git status --short packages/locale | head
# Expected: erp.po AND mes.po updated across locales; no compiled .mjs staged
Out of scope: adding/renaming strings; locale list changes.
Task 11: AGENTS.md + spec changelog sync
Depends on: Tasks 7, 8 Files:
- Modify:
apps/erp/app/modules/production/AGENTS.md— port the salvage "Operation Batch" domain-concept paragraph, then delete its "(plusCancelled)" parenthetical and add one sentence: aCompletingretry must resubmit the recorded quantities (mismatches are rejected). - Modify:
apps/erp/app/modules/resources/AGENTS.md— port the salvagebatchableflag mention. - Modify:
.ai/specs/2026-08-21-job-operation-batching.md— changelog entry: "Implemented onfeat/job-operation-batching-v2(Tasks 1–11), migration{timestamp}_job-operation-batching.sql."
Verify:
grep -n "Cancelled" apps/erp/app/modules/production/AGENTS.md
# Expected: matches only in Job-status lines; zero in the Operation Batch paragraph
Out of scope: .claude/rules/ (no durable convention changed); glossary.
Task 12: Full verification gate
Depends on: Tasks 1–11
Steps (in order; stop at first failure, fix, restart the failed step):
pnpm run generate:types
pnpm run lint
pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/utils
pnpm run test
pnpm run build
git grep -inE 'st[i]tch' -- ':!*.po' ':!.ai/' | grep -i batch
# Expected: every command exit 0; final grep prints nothing
Verify: paste the tail of each command's output into the run log.
Out of scope: deploying; pushing (ask first).
Task 13: Browser verification via /test
Depends on: Task 12. Needs the user's running dev stack (crbn up) — if
unreachable, STOP and ask; never boot or rebuild it yourself.
Steps: invoke /test (which uses /auth first) with these scenarios:
- Processes: toggle Batchable on a process → table badge shows; DB row
batchable = t. - Batching board: candidates with material chips; a substance facet filter
drops non-matching ops; drag 2 ops into "New batch" →
BAT…created; drag one out; assign work center → members'workCenterIdupdated; dissolve works pre-start. - Eligibility: start a timer on an op in MES → it disappears from board candidates (RPC guard).
- MES: kanban batch card; batch page Start → batch-tagged event; Stop; Complete with pre-filled quantities → members Done, next ops Ready, batch Completed, sliced per-member events sum to the recorded span ∝ quantity.
- Resume: put a batch into
Completing(cheapest simulated Phase-2 failure, or direct edge-fn invocation) and verify: yellow badge + "Retry Completion" in MES; read-only lane on the ERP board; retry with CHANGED quantities is rejected naming the recorded values; retry with the same values landsCompletedwith no duplicated issues/quantities/events/GL. Clean up seeded data.
Verify: /test report green on scenarios 1–4; scenario-5 evidence
(screenshots or response bodies) in the run log. Any failure → fix and re-run
before checking the box.
Out of scope: GL posting against real accounting config (needs accounts + work-center rates; note as follow-up if the dev environment lacks them).