Skip to content

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

docs(production): job operation batching research, spec, and plan (#1095)

Brad Barbin5bb67a649b0e
diff --git a/.ai/plans/2026-07-03-job-operation-batching.md b/.ai/plans/2026-07-03-job-operation-batching.md
new file mode 100644
index 0000000000..165098fb0d
--- /dev/null
+++ b/.ai/plans/2026-07-03-job-operation-batching.md
@@ -0,0 +1,1339 @@
+# Job Operation Batching — implementation plan
+
+**Spec:** `.ai/specs/2026-07-03-job-operation-batching.md` (all open questions resolved 2026-07-03)
+**Research:** `.ai/research/job-operation-batching.md`
+**Branch:** `feature/job-operation-batching`
+**Supersedes:** the never-merged prior plan (commit `d6c7ad3de`)
+
+Every grounded fact below marked **[VERIFIED]** was re-checked against the working
+tree on 2026-07-03. Line numbers are anchors, not gospel — re-locate by the quoted
+code if they drifted. The superseded feature's terminology (case-insensitive grep
+pattern `st[i]tch`) must not appear in any code, SQL, or docs this plan produces.
+
+## Executor ground rules
+
+1. **Never rebuild the database.** `pnpm db:migrate` applies pending migrations; if the local DB is unreachable, STOP and tell the user.
+2. **Commits:** conventional format, matching the style of recent commits on `main`. Commit per task via the `/check-and-commit` gate; never auto-push.
+3. **Typecheck filters:** `pnpm exec turbo run typecheck --filter=erp` and `--filter=mes` (package names are `erp` / `mes` — **[VERIFIED]** in the prior plan; if turbo reports "no package found", retry with `@carbon/erp` / `@carbon/mes` and report which name worked). Never run a whole-repo typecheck (OOMs).
+4. **Generated DB types reality:** `pnpm db:migrate` regenerates `packages/database/src/types.ts` + swagger from the LOCAL database, but the committed types are generated from the cloud DB and include cloud-only per-company tables. After migrating, run `git diff --stat packages/database/src/types.ts`. If the diff is dominated by deletions of tables unrelated to this feature, run `git restore packages/database/src/types.ts` (and the swagger file if also mass-changed) and write app code using the cast idiom instead: `client.from("jobOperationBatch" as any)`, `client.rpc("get_batchable_operations" as any, {...})`, and `(row as any).batchable` for new columns — with a `// TODO: remove casts after types regenerate post-deploy` comment at each site. If the diff is clean/additive, commit it and use full types. **If unsure which case you're in, STOP and ask Brad.**
+5. Verification commands close each task. Run them; never assert green without output.
+6. Spec wins over plan; code wins over both — surface conflicts, don't improvise silently.
+7. Do not directly write `jobOperation.startDate`/`dueDate`, and never delete operations with production events (module AGENTS.md). This plan never requires either.
+
+## Verified facts the design rests on (do not re-litigate)
+
+- **[VERIFIED]** `trg_event_sync_"jobOperation"` is a `BEFORE INSERT OR UPDATE OR DELETE ... FOR EACH ROW` trigger (created by `attach_event_trigger`, `20260410030406_event-system-after-interceptors.sql:119-123`). A multi-row Kysely `UPDATE ... SET status='Done'` fires it once per row. The `sync_finish_job_operation` interceptor (`20260410031809_production-interceptors.sql:109-150`) closes that row's open `productionEvent`s and flips `Waiting` dependents to `Ready` via `jobOperationDependency`. **Each member job's downstream op releases independently; no cross-job edges needed.** No newer migration redefines either.
+- **[VERIFIED]** `process` has a **bare PK `("id")`** with `companyId` column; current columns include `completeAllOnScan BOOLEAN NOT NULL DEFAULT FALSE` (`20251001001426_kanban-jobs.sql:29`) — the precedent flag. Created in `20240819115702_work-centers.sql:1-17`.
+- **[VERIFIED]** `jobOperation.processId` is `TEXT NOT NULL`; `workCenterId` nullable; PK bare `("id")`; `companyId NOT NULL` (`20240915192542_job-methods.sql:125-151`). Status enum: `'Canceled','Done','In Progress','Paused','Ready','Todo','Waiting'` (`20240927033740`). No grouping/batch column exists yet.
+- **[VERIFIED]** `productionQuantity` (`20241002012019:7-28`): `id` DEFAULT `xid()`, `quantity` INTEGER NOT NULL, type enum `'Rework'|'Scrap'|'Production'` DEFAULT 'Production', `setupProductionEventId` TEXT nullable.
+- **[VERIFIED]** `getNextSequence(trx, tableName, companyId)` — `packages/database/supabase/functions/shared/get-next-sequence.ts:5-9`.
+- **[VERIFIED]** Sequence seeding pattern for existing companies: `20260601143527_picking-lists.sql:134-145` (`INSERT INTO "sequence" ... SELECT ... FROM "company" ON CONFLICT DO NOTHING`). New companies: the sequences array imported by `packages/database/supabase/functions/seed-company/index.ts` (rows like `{ table: 'pickingList', name: 'Picking List', prefix: 'PL', next: 0, size: 6, step: 1 }`).
+- **[VERIFIED]** Newest `get_active_job_operations_by_location` definition: `20260531084723_rework-serial-flow.sql`. It feeds BOTH the ERP schedule board (`apps/erp/app/modules/production/production.service.ts` → `getActiveJobOperationsByLocation`) and the MES kanban (`apps/mes/app/services/operations.service.ts`). Returns `processId`, `workCenterId`, `operationQuantity`, `targetQuantity`, etc. — no batch/material columns yet.
+- **[VERIFIED]** Material property chain: `jobMaterial.jobOperationId` (nullable TEXT, added `20260120132502` with backfill) → `jobMaterial.itemId` → `item.id`; `material.id = item.readableId AND material.companyId = item.companyId`; property FKs on `material`: `materialFormId`, `materialSubstanceId`, `gradeId`, `dimensionId`, `finishId`, `materialTypeId`; lookups `materialForm`/`materialSubstance`/`materialGrade`/`materialDimension`/`materialFinish` display column `name`.
+- **[VERIFIED]** `issue` edge function (`packages/database/supabase/functions/issue/index.ts`) has a `type: "jobOperation"` case `{ id, quantity, companyId, userId }` that issues all eligible untracked materials for ONE operation per that job's own BOM (`jobMaterial` where `jobOperationId = id`, itemType Material/Part/Consumable, methodType ≠ Make to Order, no batch/serial tracking). The MES completion route `apps/mes/app/routes/x+/complete.tsx` invokes it. (Its `jobOperationBatchComplete` case is **lot**-tracking completion — unrelated; do not touch it.)
+- **[VERIFIED]** MES `finishJobOperation` (`apps/mes/app/services/operations.service.ts:148-189`): sets status `Done`, then for each ended `productionEvent` with `postedToGL = false` invokes `post-production-event`. Batch completion must replicate this GL step.
+- **[VERIFIED]** ERP schedule board: route `apps/erp/app/routes/x+/schedule+/operations.tsx` (loader ~69-311, URL-param filters `?filter=key:operator:value` parsed in the loader, `SearchFilter` + `Filter`/`ActiveFilters` from `~/components/Table/components/Filter` with `useFilters()`); drag-and-drop via `@dnd-kit` in `apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx` (onDragEnd ~291-447 submits `{id, columnId, priority}` to `path.to.scheduleOperationUpdate` with `useSubmit`, `navigate:false`, per-item `fetcherKey`); item type = `operationItemValidator` in `.../Kanban/types.ts:97`; card = `.../Kanban/components/ItemCard.tsx` (menu ~181-220, badges ~299-311). Path entries at `apps/erp/app/utils/path.ts:1718-1719`.
+- **[VERIFIED]** Material lookup pickers exist: `apps/erp/app/components/Form/{Shape,Substance,MaterialGrade,MaterialDimension,MaterialFinish,MaterialType}.tsx`; list services `getMaterialFormList`/`getMaterialSubstanceList`/etc. in `items.service.ts`.
+- **[VERIFIED]** MES kanban: `apps/mes/app/routes/x+/operations.tsx` (loader maps RPC rows ~52-236), card `apps/mes/app/components/Kanban/components/ItemCard.tsx` (~76+, Card/CardHeader/CardContent/CardFooter). MES modal-drawer precedent: `ModalDrawer*` primitives (see `apps/erp/app/modules/production/ui/Procedures/ProcedureForm.tsx` imports).
+- **[VERIFIED]** Edge functions: config entries are `[functions.<name>]` + `enabled` + `verify_jwt` in `packages/database/supabase/config.toml`; deno std `0.175.0` in the newest functions; no function named `batch*` exists.
+
+## Dependency graph
+
+```
+Task 0 (branch)
+ → Task 1 (migration) → Task 2 (types/casts decision)
+ → Task 3 (seed sequences) ∥ Task 4 (resources UI) ∥ Task 5 (validators)
+ → Task 6 (edge function) → Task 7 (ERP services + paths + action route)
+ → Task 8 (batch planning board UI) ∥ Task 9 (schedule board integration)
+ → Task 10 (MES board collapse) → Task 11 (MES batch view + complete)
+ → Task 12 (docs sync) → Task 13 (verification gate) → Task 14 (PR)
+Tasks 3, 4, 5 are independent of each other. Tasks 8 and 9 are independent.
+```
+
+## Progress
+
+- [ ] Task 0: Create the branch
+- [ ] Task 1: Database migration (flag, batch table, FKs, sequence, RPCs)
+- [ ] Task 2: Types regeneration decision
+- [ ] Task 3: Seed new-company sequence
+- [ ] Task 4: Process form + table (resources module)
+- [ ] Task 5: Production validators
+- [ ] Task 6: `batch-operations` edge function
+- [ ] Task 7: ERP services, paths, batching action route
+- [ ] Task 8: Batch planning board UI
+- [ ] Task 9: Schedule board badge + menu
+- [ ] Task 10: MES kanban batch collapse
+- [ ] Task 11: MES batch view + complete flow
+- [ ] Task 12: Docs/AGENTS sync
+- [ ] Task 13: Full verification gate (typecheck, lint, test, browser e2e)
+- [ ] Task 14: PR
+
+---
+
+## Task 0: Create the branch
+
+**Depends on:** none
+**Files:** none
+
+**Steps:**
+1. ```bash
+ git checkout main && git pull
+ git checkout -b feature/job-operation-batching
+ ```
+
+**Verify:**
+```bash
+git branch --show-current
+# Expected: feature/job-operation-batching
+```
+
+**Out of scope:** nothing else.
+
+---
+
+## Task 1: Database migration (flag, batch table, FKs, sequence, RPCs)
+
+**Depends on:** Task 0
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_job-operation-batching.sql`
+- Copy from (precedent): `packages/database/supabase/migrations/20260601143527_picking-lists.sql` (sequence seeding), `20260531084723_rework-serial-flow.sql` (RPC to fork)
+
+**Steps:**
+
+1. ```bash
+ pnpm db:migrate:new job-operation-batching
+ ```
+ If the generated HHMMSS is `000000`, rename the file with random digits (e.g. `142817`). The timestamp must be NEWER than every migration on `main`.
+
+2. Before writing SQL, capture the two definitions you must fork:
+ ```bash
+ grep -rln 'VIEW "processes"' packages/database/supabase/migrations/ | sort | tail -2
+ grep -rln 'get_active_job_operations_by_location' packages/database/supabase/migrations/ | sort | tail -2
+ ```
+ Open the NEWEST file from each result and copy the full `CREATE VIEW "processes"` and `CREATE OR REPLACE FUNCTION get_active_job_operations_by_location` definitions verbatim into a scratch buffer. **If a newer definition than `20260531084723` exists for the RPC, fork that one.** Also eyeball the RLS idiom in the single newest `CREATE POLICY` migration; if it differs from `= ANY (SELECT unnest(...::text[]))` below, copy the current idiom.
+
+3. Write the migration. Every statement idempotent (the deploy runner retries failed files over committed partial state). Full contents, in this order:
+
+ ```sql
+ -- Job Operation Batching (spec: .ai/specs/2026-07-03-job-operation-batching.md)
+ -- Batchability is a property of the process. Batches group real jobOperations;
+ -- jobs are never merged and the BOM is never modified.
+ -- NOTE: an operation batch is unrelated to lot/batch tracking (batchNumber/trackedEntity).
+
+ -- 1. Process capability flag
+ ALTER TABLE "process" ADD COLUMN IF NOT EXISTS "batchable" BOOLEAN NOT NULL DEFAULT false;
+
+ -- 2. Recreate the "processes" view from its NEWEST definition (Postgres expands
+ -- SELECT * at creation time, so the view must be re-declared to pick up the column).
+ DROP VIEW IF EXISTS "processes";
+ -- >>> paste the NEWEST "processes" view definition here, adding p."batchable"
+ -- >>> to the select list (keep WITH(SECURITY_INVOKER=true) if present in the original)
+
+ -- 3. Batch status enum
+ DO $$ BEGIN
+ CREATE TYPE "jobOperationBatchStatus" AS ENUM ('Active', 'Completed', 'Cancelled');
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+
+ -- 4. The operation batch
+ CREATE TABLE IF NOT EXISTS "jobOperationBatch" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "readableId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "processId" TEXT NOT NULL,
+ "workCenterId" TEXT,
+ "locationId" TEXT NOT NULL,
+ "status" "jobOperationBatchStatus" NOT NULL DEFAULT 'Active',
+ "notes" TEXT,
+ "customFields" JSONB,
+ "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,
+ CONSTRAINT "jobOperationBatch_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "jobOperationBatch_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobOperationBatch_processId_fkey" FOREIGN KEY ("processId")
+ REFERENCES "process"("id"),
+ CONSTRAINT "jobOperationBatch_workCenterId_fkey" FOREIGN KEY ("workCenterId")
+ REFERENCES "workCenter"("id") ON DELETE SET NULL,
+ CONSTRAINT "jobOperationBatch_locationId_fkey" FOREIGN KEY ("locationId")
+ REFERENCES "location"("id"),
+ CONSTRAINT "jobOperationBatch_readableId_unique" UNIQUE ("readableId", "companyId")
+ );
+
+ CREATE INDEX IF NOT EXISTS "jobOperationBatch_companyId_idx" ON "jobOperationBatch" ("companyId");
+ CREATE INDEX IF NOT EXISTS "jobOperationBatch_processId_idx" ON "jobOperationBatch" ("processId");
+ CREATE INDEX IF NOT EXISTS "jobOperationBatch_workCenterId_idx" ON "jobOperationBatch" ("workCenterId");
+ CREATE INDEX IF NOT EXISTS "jobOperationBatch_locationId_idx" ON "jobOperationBatch" ("locationId");
+ CREATE INDEX IF NOT EXISTS "jobOperationBatch_createdBy_idx" ON "jobOperationBatch" ("createdBy");
+
+ ALTER TABLE "jobOperationBatch" ENABLE ROW LEVEL SECURITY;
+
+ DROP POLICY IF EXISTS "SELECT" ON "public"."jobOperationBatch";
+ CREATE POLICY "SELECT" ON "public"."jobOperationBatch"
+ FOR SELECT USING (
+ "companyId" = ANY (SELECT unnest(get_companies_with_employee_role()::text[]))
+ );
+ DROP POLICY IF EXISTS "INSERT" ON "public"."jobOperationBatch";
+ CREATE POLICY "INSERT" ON "public"."jobOperationBatch"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (SELECT unnest(get_companies_with_employee_permission('production_create')::text[]))
+ );
+ DROP POLICY IF EXISTS "UPDATE" ON "public"."jobOperationBatch";
+ CREATE POLICY "UPDATE" ON "public"."jobOperationBatch"
+ FOR UPDATE USING (
+ "companyId" = ANY (SELECT unnest(get_companies_with_employee_permission('production_update')::text[]))
+ );
+ DROP POLICY IF EXISTS "DELETE" ON "public"."jobOperationBatch";
+ CREATE POLICY "DELETE" ON "public"."jobOperationBatch"
+ FOR DELETE USING (
+ "companyId" = ANY (SELECT unnest(get_companies_with_employee_permission('production_delete')::text[]))
+ );
+
+ -- 5. Membership FK on jobOperation
+ ALTER TABLE "jobOperation" ADD COLUMN IF NOT EXISTS "jobOperationBatchId" TEXT;
+ DO $$ BEGIN
+ ALTER TABLE "jobOperation" ADD CONSTRAINT "jobOperation_jobOperationBatchId_fkey"
+ FOREIGN KEY ("jobOperationBatchId", "companyId")
+ REFERENCES "jobOperationBatch"("id", "companyId") ON DELETE SET NULL;
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ CREATE INDEX IF NOT EXISTS "jobOperation_jobOperationBatchId_idx"
+ ON "jobOperation" ("jobOperationBatchId") WHERE "jobOperationBatchId" IS NOT NULL;
+
+ -- 6. Batch tag on productionEvent (timers while running; slices keep it)
+ ALTER TABLE "productionEvent" ADD COLUMN IF NOT EXISTS "jobOperationBatchId" TEXT;
+ DO $$ BEGIN
+ ALTER TABLE "productionEvent" ADD CONSTRAINT "productionEvent_jobOperationBatchId_fkey"
+ FOREIGN KEY ("jobOperationBatchId", "companyId")
+ REFERENCES "jobOperationBatch"("id", "companyId") ON DELETE SET NULL;
+ EXCEPTION WHEN duplicate_object THEN NULL; END $$;
+ CREATE INDEX IF NOT EXISTS "productionEvent_jobOperationBatchId_idx"
+ ON "productionEvent" ("jobOperationBatchId") WHERE "jobOperationBatchId" IS NOT NULL;
+
+ -- 7. Sequence for readable ids (existing companies)
+ INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
+ SELECT 'jobOperationBatch', 'Operation Batch', 'BAT', NULL, 0, 6, 1, "id"
+ FROM "company"
+ ON CONFLICT DO NOTHING;
+
+ -- 8. Re-declare get_active_job_operations_by_location from the NEWEST definition
+ -- (feeds ERP schedule board AND MES kanban). DROP first, preserving the exact
+ -- signature of the newest version.
+ -- >>> paste DROP FUNCTION IF EXISTS get_active_job_operations_by_location(<newest arg types>);
+ -- >>> paste the NEWEST definition verbatim, then make exactly these additions:
+ -- * to RETURNS TABLE: "processBatchable" BOOLEAN, "jobOperationBatchId" TEXT, "batchReadableId" TEXT
+ -- * to the SELECT list: p."batchable" AS "processBatchable", jo."jobOperationBatchId", b."readableId" AS "batchReadableId"
+ -- * add joins (if p is not already joined, add it):
+ -- LEFT JOIN "process" p ON p."id" = jo."processId"
+ -- LEFT JOIN "jobOperationBatch" b ON b."id" = jo."jobOperationBatchId" AND b."companyId" = jo."companyId"
+
+ -- 9. Batch planning candidates RPC
+ DROP FUNCTION IF EXISTS get_batchable_operations(TEXT, TEXT);
+ CREATE OR REPLACE FUNCTION get_batchable_operations(location_id TEXT, process_id TEXT)
+ RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "jobReadableId" TEXT,
+ "jobDueDate" DATE,
+ "jobStatus" "jobStatus",
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "description" TEXT,
+ "operationQuantity" NUMERIC,
+ "status" "jobOperationStatus",
+ "workCenterId" TEXT,
+ "jobOperationBatchId" TEXT,
+ "batchReadableId" TEXT,
+ "batchStatus" "jobOperationBatchStatus",
+ "batchWorkCenterId" TEXT,
+ "companyId" TEXT,
+ "materials" JSONB
+ ) LANGUAGE sql STABLE AS $$
+ SELECT
+ jo."id",
+ j."id" AS "jobId",
+ j."jobId" AS "jobReadableId",
+ j."dueDate" AS "jobDueDate",
+ j."status" AS "jobStatus",
+ i."readableId" AS "itemReadableId",
+ i."name" AS "itemDescription",
+ jo."description",
+ jo."operationQuantity",
+ jo."status",
+ jo."workCenterId",
+ jo."jobOperationBatchId",
+ b."readableId" AS "batchReadableId",
+ b."status" AS "batchStatus",
+ b."workCenterId" AS "batchWorkCenterId",
+ jo."companyId",
+ COALESCE(mats."materials", '[]'::jsonb) AS "materials"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j."id" = jo."jobId"
+ JOIN "item" i ON i."id" = j."itemId"
+ LEFT JOIN "jobOperationBatch" b
+ ON b."id" = jo."jobOperationBatchId" AND b."companyId" = jo."companyId"
+ LEFT JOIN LATERAL (
+ SELECT jsonb_agg(jsonb_build_object(
+ 'itemReadableId', mi."readableId",
+ 'description', jm."description",
+ 'quantity', jm."quantity",
+ 'formId', m."materialFormId", 'formName', mf."name",
+ 'substanceId', m."materialSubstanceId", 'substanceName', ms."name",
+ 'gradeId', m."gradeId", 'gradeName', mg."name",
+ 'dimensionId', m."dimensionId", 'dimensionName', md."name",
+ 'finishId', m."finishId", 'finishName', mfin."name"
+ )) AS "materials"
+ FROM "jobMaterial" jm
+ JOIN "item" mi ON mi."id" = jm."itemId"
+ LEFT JOIN "material" m ON m."id" = mi."readableId" AND m."companyId" = mi."companyId"
+ LEFT JOIN "materialForm" mf ON mf."id" = m."materialFormId"
+ LEFT JOIN "materialSubstance" ms ON ms."id" = m."materialSubstanceId"
+ LEFT JOIN "materialGrade" mg ON mg."id" = m."gradeId"
+ LEFT JOIN "materialDimension" md ON md."id" = m."dimensionId"
+ LEFT JOIN "materialFinish" mfin ON mfin."id" = m."finishId"
+ WHERE jm."jobOperationId" = jo."id"
+ ) mats ON TRUE
+ WHERE j."locationId" = location_id
+ AND jo."processId" = process_id
+ AND (
+ (jo."jobOperationBatchId" IS NULL
+ AND jo."status" IN ('Todo', 'Ready', 'Waiting'))
+ OR b."status" = 'Active'
+ );
+ $$;
+ ```
+ Adjustments while writing:
+ - Mirror the **job-status filter** and the exact item/job column expressions from the newest `get_active_job_operations_by_location` (e.g. if it uses `i."name"` vs another display expression for item description, and if it restricts `j."status"` to active jobs — copy that restriction into the candidates branch of the WHERE clause). If `job` has no `"jobStatus"` enum type name, use the type the newest RPC uses.
+ - Mirror the newest RPC's `SECURITY` posture and any `GRANT EXECUTE` statements for `get_batchable_operations`.
+ - If `jobOperation."operationQuantity"` does not exist as a column (check the newest RPC's select list for where `operationQuantity` comes from), source it exactly as that RPC does. **If it is computed rather than a column, STOP and report before improvising.**
+
+4. Apply:
+ ```bash
+ pnpm db:migrate
+ ```
+
+**Verify:**
+```bash
+pnpm db:migrate
+# Expected: applies cleanly, no ERROR lines
+
+psql "$SUPABASE_DB_URL" -c 'SELECT "table","prefix","size" FROM "sequence" WHERE "table"=$$jobOperationBatch$$ LIMIT 3;'
+# Expected: one row per company, prefix BAT, size 6
+
+psql "$SUPABASE_DB_URL" -c '\d "jobOperationBatch"' | head -20
+# Expected: columns id, readableId, companyId, processId, workCenterId, locationId, status...
+
+psql "$SUPABASE_DB_URL" -c 'SELECT proname FROM pg_proc WHERE proname IN ($$get_batchable_operations$$,$$get_active_job_operations_by_location$$);'
+# Expected: both names present
+```
+
+**Out of scope:** any change to `jobMaterial`, `jobMakeMethod`, `methodOperation`, `quoteOperation`, `itemReplenishment`, or the `issue` function's SQL. No `batchable` column anywhere except `process`.
+
+---
+
+## Task 2: Types regeneration decision
+
+**Depends on:** Task 1
+**Files:**
+- Modify (maybe): `packages/database/src/types.ts` (+ swagger artifact) — commit or restore per ground rule 4
+
+**Steps:**
+1. ```bash
+ git diff --stat packages/database/src/types.ts
+ ```
+2. Apply ground rule 4: additive/clean diff → keep and commit with the migration; mass deletions of unrelated cloud tables → `git restore` the generated artifacts and adopt the cast idiom in all app code for: table `jobOperationBatch`, RPC `get_batchable_operations`, and new columns `process.batchable`, `jobOperation.jobOperationBatchId`, `productionEvent.jobOperationBatchId`, plus the three new RPC output columns.
+3. Record which path was taken in the commit message body.
+
+**Verify:**
+```bash
+git status --short packages/database/src/
+# Expected: either staged intentional changes, or clean (restored)
+```
+
+**Out of scope:** hand-editing generated types (never allowed).
+
+---
+
+## Task 3: Seed new-company sequence
+
+**Depends on:** Task 1
+**Files:**
+- Modify: the sequences seed module imported by `packages/database/supabase/functions/seed-company/index.ts` (follow the `import` at the top of that file — **[VERIFIED]** the sequences array lives in a `seed`-named module; open `seed-company/index.ts:1-30` and jump to the definition)
+
+**Steps:**
+1. Confirm the `BAT` prefix is unused:
+ ```bash
+ grep -rn "'BAT'\|\"BAT\"" packages/database/supabase/functions/ packages/database/supabase/migrations/ | grep -iv batch
+ ```
+ If any OTHER sequence already uses prefix `BAT`, STOP and report — propose `BTH` and update the Task 1 migration + spec before continuing.
+2. Add to the sequences array, matching the neighbors' exact literal shape:
+ ```typescript
+ { table: "jobOperationBatch", name: "Operation Batch", prefix: "BAT", next: 0, size: 6, step: 1 }
+ ```
+ (Include `suffix: null` only if neighbor entries carry it.)
+
+**Verify:**
+```bash
+grep -n "jobOperationBatch" packages/database/supabase/functions/**/*.ts | head
+# Expected: one hit in the sequences seed module
+deno check packages/database/supabase/functions/seed-company/index.ts 2>&1 | tail -3
+# Expected: no errors (or only pre-existing lib warnings shared by sibling functions)
+```
+
+**Out of scope:** other seed data.
+
+---
+
+## Task 4: Process form + table (resources module)
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/resources/resources.models.ts` — `processValidator` (~line 288-316)
+- Modify: `apps/erp/app/modules/resources/ui/Processes/ProcessForm.tsx` — add Boolean field
+- Modify: the processes list table component under `apps/erp/app/modules/resources/ui/Processes/` — add a Batchable column
+- Copy from (precedent): the `completeAllOnScan` handling in the SAME three files (**[VERIFIED]** validator has `completeAllOnScan: zfd.checkbox()`; form renders it as a `Boolean` at ProcessForm.tsx:155-159)
+
+**Steps:**
+1. `processValidator`: add `batchable: zfd.checkbox()` directly after `completeAllOnScan`.
+2. `upsertProcess` (`resources.service.ts:1633-1681`): its parameter type derives from the validator and the body passes the object through — read it; if it enumerates columns, add `batchable`; if it spreads, no change. State the finding in the commit message.
+3. `ProcessForm.tsx`: clone the `completeAllOnScan` `<Boolean>` block; new field:
+ - `name="batchable"`
+ - label: `Batchable`
+ - description: `Multiple jobs can run on this process at the same time — e.g. a laser table, furnace, or plating bath`
+ - Match the file's existing Lingui convention (wrap with `t`/`<Trans>` only if the sibling fields are wrapped).
+ - Also add `batchable` to the form's `initialValues`/`defaultValues` object exactly where `completeAllOnScan` appears (use the cast idiom for the row read if Task 2 chose casts).
+4. Processes table: find the column definitions (grep `completeAllOnScan\|columnHelper\|accessorKey` in `ui/Processes/`); add a `Batchable` boolean column rendering the same way an existing boolean column in that table renders (checkbox icon / badge). If the table has NO boolean column precedent, copy the boolean-cell rendering from any table that shows `active` flags (grep `Enumerable\|LuCheck` in a sibling table) and note the file used.
+5. Check the create/edit routes `apps/erp/app/routes/x+/resources+/processes.new.tsx` and `processes.$processId.tsx`: if the action enumerates fields from the validated payload, add `batchable`; if it spreads, no change.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0 (or the same pre-existing errors as on main — diff against a main run if unsure)
+```
+
+**Out of scope:** `defaultStandardFactor`, `processType`, work-center assignment logic.
+
+---
+
+## Task 5: Production validators
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.models.ts`
+- Modify: `apps/mes/app/services/models.ts`
+- Copy from (precedent): existing status consts + validators in the same files (e.g. `productionEventValidator` in MES models.ts ~137-155)
+
+**Steps:**
+1. In `production.models.ts`, near the other status consts, add exactly:
+ ```typescript
+ export const jobOperationBatchStatus = [
+ "Active",
+ "Completed",
+ "Cancelled"
+ ] as const;
+
+ export const createJobOperationBatchValidator = z.object({
+ locationId: z.string().min(1, { message: "Location is required" }),
+ workCenterId: zfd.text(z.string().optional()),
+ jobOperationIds: z
+ .array(z.string().min(1))
+ .min(1, { message: "Select at least one operation" })
+ });
+
+ export const updateJobOperationBatchValidator = z.object({
+ batchId: z.string().min(1, { message: "Batch is required" }),
+ intent: z.enum(["add", "remove", "dissolve", "update"]),
+ jobOperationIds: z.array(z.string().min(1)).optional(),
+ workCenterId: zfd.text(z.string().optional())
+ });
+ ```
+ **No maximum size anywhere** (user directive).
+2. In `apps/mes/app/services/models.ts`, add:
+ ```typescript
+ export const completeJobOperationBatchValidator = z.object({
+ batchId: z.string().min(1, { message: "Batch is required" }),
+ members: z
+ .array(
+ z.object({
+ jobOperationId: z.string().min(1),
+ quantity: zfd.numeric(z.number().int().min(0)),
+ scrapQuantity: zfd.numeric(z.number().int().min(0).optional())
+ })
+ )
+ .min(1)
+ });
+ ```
+ (`quantity` is `.int()` — `productionQuantity.quantity` is INTEGER **[VERIFIED]**.) If MES models.ts lacks a `zfd` import, add it matching the file's import style.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp && pnpm exec turbo run typecheck --filter=mes
+# Expected: exit 0 for both
+```
+
+**Out of scope:** touching `methodOperationValidator`, `quoteOperationValidator`, or `itemManufacturingValidator` — the old design's flags are GONE, nothing propagates.
+
+---
+
+## Task 6: `batch-operations` edge function
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/database/supabase/functions/batch-operations/index.ts` (via `pnpm db:function:new batch-operations`)
+- Modify: `packages/database/supabase/config.toml` — register the function
+- Copy from (precedent): `packages/database/supabase/functions/trigger-rework/index.ts` (imports/skeleton), `.ai/rules/workflow-edge-function.md`
+
+**Steps:**
+1. ```bash
+ pnpm db:function:new batch-operations
+ ```
+2. `config.toml` — add, matching neighbor formatting:
+ ```toml
+ [functions.batch-operations]
+ enabled = true
+ verify_jwt = true
+ ```
+3. Write `index.ts` — complete contents (adjust only the std version if neighbors use a different one):
+
+ ```typescript
+ import { serve } from "https://deno.land/[email protected]/http/server.ts";
+ import z from "npm:zod@^3.24.1";
+ import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+ import { corsHeaders } from "../lib/headers.ts";
+ import { requirePermissions } from "../lib/supabase.ts";
+ import type { DB } from "../lib/types.ts";
+ import { getNextSequence } from "../shared/get-next-sequence.ts";
+
+ const pool = getConnectionPool(1);
+ const db = getDatabaseClient<DB>(pool);
+
+ const NOT_STARTED = ["Todo", "Ready", "Waiting"];
+
+ const payloadValidator = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("create"),
+ jobOperationIds: z.array(z.string()).min(1),
+ locationId: z.string(),
+ workCenterId: z.string().optional().nullable(),
+ companyId: z.string(),
+ userId: z.string()
+ }),
+ z.object({
+ type: z.literal("add"),
+ batchId: z.string(),
+ jobOperationIds: z.array(z.string()).min(1),
+ companyId: z.string(),
+ userId: z.string()
+ }),
+ z.object({
+ type: z.literal("remove"),
+ batchId: z.string(),
+ jobOperationIds: z.array(z.string()).min(1),
+ companyId: z.string(),
+ userId: z.string()
+ }),
+ z.object({
+ type: z.literal("update"),
+ batchId: z.string(),
+ workCenterId: z.string().nullable(),
+ companyId: z.string(),
+ userId: z.string()
+ }),
+ z.object({
+ type: z.literal("dissolve"),
+ batchId: z.string(),
+ companyId: z.string(),
+ userId: z.string()
+ }),
+ z.object({
+ type: z.literal("complete"),
+ batchId: z.string(),
+ members: z
+ .array(
+ z.object({
+ jobOperationId: z.string(),
+ quantity: z.number().int().min(0),
+ scrapQuantity: z.number().int().min(0).optional()
+ })
+ )
+ .min(1),
+ companyId: z.string(),
+ userId: z.string()
+ })
+ ]);
+
+ /** Integer shares proportional to weights, summing exactly to total (largest remainder). */
+ function proportionalShares(total: number, weights: number[]): number[] {
+ const sum = weights.reduce((a, b) => a + b, 0);
+ const effective = sum > 0 ? weights : weights.map(() => 1);
+ const effectiveSum = sum > 0 ? sum : weights.length;
+ const raw = effective.map((w) => (total * w) / effectiveSum);
+ const floors = raw.map(Math.floor);
+ let remainder = total - floors.reduce((a, b) => a + b, 0);
+ const order = raw
+ .map((r, i) => ({ frac: r - Math.floor(r), i }))
+ .sort((a, b) => b.frac - a.frac);
+ const result = [...floors];
+ for (const { i } of order) {
+ if (remainder <= 0) break;
+ result[i] += 1;
+ remainder -= 1;
+ }
+ return result;
+ }
+
+ // deno-lint-ignore no-explicit-any
+ async function assertEligible(trx: any, companyId: string, jobOperationIds: string[], expectedProcessId?: string) {
+ const operations = await trx
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("id", "in", jobOperationIds)
+ .where("companyId", "=", companyId)
+ .execute();
+ if (operations.length !== jobOperationIds.length) {
+ throw new Error("One or more operations not found");
+ }
+ const processId = expectedProcessId ?? operations[0].processId;
+ const process = await trx
+ .selectFrom("process")
+ .select(["id", "batchable"])
+ .where("id", "=", processId)
+ .executeTakeFirst();
+ if (!process?.batchable) {
+ throw new Error("The process is not batchable");
+ }
+ for (const op of operations) {
+ if (op.processId !== processId) {
+ throw new Error(`Operation ${op.id} is not on the batch's process`);
+ }
+ if (op.jobOperationBatchId) {
+ throw new Error(`Operation ${op.id} is already in a batch`);
+ }
+ if (!NOT_STARTED.includes(op.status)) {
+ throw new Error(`Operation ${op.id} has already started`);
+ }
+ }
+ const events = await trx
+ .selectFrom("productionEvent")
+ .select("id")
+ .where("jobOperationId", "in", jobOperationIds)
+ .limit(1)
+ .execute();
+ if (events.length > 0) {
+ throw new Error("Operations with recorded production events cannot be batched");
+ }
+ return { operations, processId };
+ }
+
+ serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ const payload = payloadValidator.parse(await req.json());
+ const { companyId, userId } = payload;
+
+ await requirePermissions(req, companyId, userId, {
+ update: "production"
+ });
+
+ let result: Record<string, unknown> = {};
+
+ switch (payload.type) {
+ case "create": {
+ result = await db.transaction().execute(async (trx) => {
+ const { processId } = await assertEligible(trx, companyId, payload.jobOperationIds);
+ const readableId = await getNextSequence(trx, "jobOperationBatch", companyId);
+ const batch = await trx
+ .insertInto("jobOperationBatch")
+ .values({
+ readableId,
+ companyId,
+ processId,
+ workCenterId: payload.workCenterId ?? null,
+ locationId: payload.locationId,
+ status: "Active",
+ createdBy: userId
+ })
+ .returning(["id", "readableId"])
+ .executeTakeFirstOrThrow();
+
+ const memberUpdate: Record<string, unknown> = {
+ jobOperationBatchId: batch.id,
+ updatedBy: userId
+ };
+ if (payload.workCenterId) memberUpdate.workCenterId = payload.workCenterId;
+ await trx
+ .updateTable("jobOperation")
+ .set(memberUpdate)
+ .where("id", "in", payload.jobOperationIds)
+ .execute();
+ return batch;
+ });
+ break;
+ }
+
+ case "add": {
+ result = await db.transaction().execute(async (trx) => {
+ const batch = await trx
+ .selectFrom("jobOperationBatch")
+ .selectAll()
+ .where("id", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!batch) throw new Error("Batch not found");
+ if (batch.status !== "Active") throw new Error("Batch is not active");
+
+ const batchEvents = await trx
+ .selectFrom("productionEvent")
+ .select("id")
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .limit(1)
+ .execute();
+ if (batchEvents.length > 0) {
+ throw new Error("The batch has already started — complete it instead");
+ }
+
+ await assertEligible(trx, companyId, payload.jobOperationIds, batch.processId);
+
+ const memberUpdate: Record<string, unknown> = {
+ jobOperationBatchId: batch.id,
+ updatedBy: userId
+ };
+ if (batch.workCenterId) memberUpdate.workCenterId = batch.workCenterId;
+ await trx
+ .updateTable("jobOperation")
+ .set(memberUpdate)
+ .where("id", "in", payload.jobOperationIds)
+ .execute();
+ return { added: payload.jobOperationIds.length };
+ });
+ break;
+ }
+
+ case "remove": {
+ result = await db.transaction().execute(async (trx) => {
+ const batchEvents = await trx
+ .selectFrom("productionEvent")
+ .select("id")
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .limit(1)
+ .execute();
+ if (batchEvents.length > 0) {
+ throw new Error(
+ "Cannot remove operations: production has been recorded. Complete the batch instead."
+ );
+ }
+ await trx
+ .updateTable("jobOperation")
+ .set({ jobOperationBatchId: null, updatedBy: userId })
+ .where("id", "in", payload.jobOperationIds)
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .execute();
+
+ const remaining = await trx
+ .selectFrom("jobOperation")
+ .select("id")
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .limit(1)
+ .execute();
+ if (remaining.length === 0) {
+ await trx
+ .deleteFrom("jobOperationBatch")
+ .where("id", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+ return { removed: payload.jobOperationIds.length, dissolved: true };
+ }
+ return { removed: payload.jobOperationIds.length, dissolved: false };
+ });
+ break;
+ }
+
+ case "update": {
+ result = await db.transaction().execute(async (trx) => {
+ await trx
+ .updateTable("jobOperationBatch")
+ .set({
+ workCenterId: payload.workCenterId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+ if (payload.workCenterId) {
+ await trx
+ .updateTable("jobOperation")
+ .set({ workCenterId: payload.workCenterId, updatedBy: userId })
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .execute();
+ }
+ return { updated: true };
+ });
+ break;
+ }
+
+ case "dissolve": {
+ result = await db.transaction().execute(async (trx) => {
+ const batchEvents = await trx
+ .selectFrom("productionEvent")
+ .select("id")
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .limit(1)
+ .execute();
+ if (batchEvents.length > 0) {
+ throw new Error(
+ "Cannot dissolve: production has been recorded. Complete the batch instead — member jobs then proceed independently."
+ );
+ }
+ const members = await trx
+ .updateTable("jobOperation")
+ .set({ jobOperationBatchId: null, updatedBy: userId })
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .returning("id")
+ .execute();
+ await trx
+ .deleteFrom("jobOperationBatch")
+ .where("id", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+ return { dissolved: members.length };
+ });
+ break;
+ }
+
+ case "complete": {
+ result = await db.transaction().execute(async (trx) => {
+ const members = await trx
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+ if (members.length === 0) throw new Error("Batch not found or empty");
+ if (members.some((m) => m.status === "Done")) {
+ throw new Error("Batch already completed");
+ }
+ const inputById = new Map(
+ payload.members.map((m) => [m.jobOperationId, m])
+ );
+ for (const m of members) {
+ if (!inputById.has(m.id)) {
+ throw new Error(`Missing completion quantity for operation ${m.id}`);
+ }
+ }
+
+ // 1. Close open batch timers
+ await trx
+ .updateTable("productionEvent")
+ .set({ endTime: new Date().toISOString() })
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .where("endTime", "is", null)
+ .execute();
+
+ // 2. Slice each batch event into per-member events, durations ∝ operationQuantity
+ const weights = members.map((m) => Number(m.operationQuantity ?? 0));
+ const events = await trx
+ .selectFrom("productionEvent")
+ .selectAll()
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .execute();
+ const eventIds: string[] = events.map((e) => e.id);
+
+ for (const event of events) {
+ const start = new Date(event.startTime).getTime();
+ const end = new Date(event.endTime!).getTime();
+ const totalSeconds = Math.max(0, Math.round((end - start) / 1000));
+ if (totalSeconds === 0 || members.length === 1) continue;
+
+ const shares = proportionalShares(totalSeconds, weights);
+ let cursor = start;
+ for (let i = 0; i < members.length; i++) {
+ const sliceStart = new Date(cursor).toISOString();
+ cursor += shares[i] * 1000;
+ const sliceEnd = new Date(cursor).toISOString();
+ if (i === 0) {
+ await trx
+ .updateTable("productionEvent")
+ .set({
+ jobOperationId: members[0].id,
+ startTime: sliceStart,
+ endTime: sliceEnd
+ })
+ .where("id", "=", event.id)
+ .execute();
+ } else {
+ const inserted = await trx
+ .insertInto("productionEvent")
+ .values({
+ ...structuredClone({
+ type: event.type,
+ employeeId: event.employeeId,
+ workCenterId: event.workCenterId,
+ companyId: event.companyId,
+ createdBy: event.createdBy ?? userId,
+ jobOperationBatchId: event.jobOperationBatchId
+ }),
+ jobOperationId: members[i].id,
+ startTime: sliceStart,
+ endTime: sliceEnd
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ eventIds.push(inserted.id);
+ }
+ }
+ }
+
+ // 3. Per-member produced + scrap quantities
+ const quantityRows = members.flatMap((m) => {
+ const input = inputById.get(m.id)!;
+ const rows: Record<string, unknown>[] = [];
+ if (input.quantity > 0) {
+ rows.push({
+ jobOperationId: m.id,
+ type: "Production",
+ quantity: input.quantity,
+ companyId,
+ createdBy: userId
+ });
+ }
+ if ((input.scrapQuantity ?? 0) > 0) {
+ rows.push({
+ jobOperationId: m.id,
+ type: "Scrap",
+ quantity: input.scrapQuantity,
+ companyId,
+ createdBy: userId
+ });
+ }
+ return rows;
+ });
+ if (quantityRows.length > 0) {
+ await trx.insertInto("productionQuantity").values(quantityRows).execute();
+ }
+
+ // 4. Multi-row Done. [VERIFIED] trg_event_sync_jobOperation is a
+ // BEFORE/FOR EACH ROW trigger: each member's own downstream operation
+ // is released independently. No cross-job edges exist or are needed.
+ await trx
+ .updateTable("jobOperation")
+ .set({ status: "Done", updatedBy: userId })
+ .where("jobOperationBatchId", "=", payload.batchId)
+ .execute();
+
+ await trx
+ .updateTable("jobOperationBatch")
+ .set({
+ status: "Completed",
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", payload.batchId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ return {
+ completed: members.length,
+ memberIds: members.map((m) => m.id),
+ eventIds
+ };
+ });
+ break;
+ }
+ }
+
+ return new Response(JSON.stringify({ success: true, ...result }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200
+ });
+ } catch (err) {
+ console.error("Error in batch-operations:", err);
+ return new Response(JSON.stringify({ error: (err as Error).message }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500
+ });
+ }
+ });
+ ```
+4. Before `deno check`, open the created file and reconcile with reality:
+ - If `productionEvent` has more NOT NULL columns than `{jobOperationId, type, startTime, companyId, createdBy}` (check `psql "$SUPABASE_DB_URL" -c '\d "productionEvent"'`), copy those columns from the source event in the slice insert. **If a NOT NULL column cannot be sensibly copied, STOP and report.**
+ - Confirm `jobOperation.operationQuantity` exists (Task 1 step 3 already checked); if the column is named differently, use that name in the weights line.
+
+> **GL posting note:** `complete` intentionally does NOT invoke `post-production-event`
+> or `issue`. The MES caller (Task 11) replicates `finishJobOperation`'s pattern
+> per member/event after this call succeeds — exactly as
+> `apps/mes/app/services/operations.service.ts:148-189` does today.
+
+**Verify:**
+```bash
+deno check packages/database/supabase/functions/batch-operations/index.ts 2>&1 | tail -5
+# Expected: clean (or only lib warnings shared by sibling functions)
+grep -n "batch-operations" packages/database/supabase/config.toml
+# Expected: [functions.batch-operations] with enabled = true, verify_jwt = true
+grep -rn "max\|MAX_" packages/database/supabase/functions/batch-operations/index.ts | grep -iv "Math.max"
+# Expected: no group-size cap constants
+```
+
+**Out of scope:** modifying the `issue` or `post-production-event` functions; any Inngest event.
+
+---
+
+## Task 7: ERP services, paths, batching action route
+
+**Depends on:** Tasks 5, 6
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — new functions near `triggerJobSchedule`
+- Modify: `apps/erp/app/utils/path.ts` — new entries next to `scheduleOperation*` (~1718)
+- Create: `apps/erp/app/routes/x+/schedule+/batching.update.tsx` — action-only route
+- Copy from (precedent): `apps/erp/app/routes/x+/schedule+/operations.update.tsx` (action shape), existing `client.functions.invoke` wrappers in `production.service.ts`
+
+**Steps:**
+1. `path.ts`, after `scheduleOperationUpdate`:
+ ```typescript
+ scheduleBatching: `${x}/schedule/batching`,
+ scheduleBatchingUpdate: `${x}/schedule/batching/update`,
+ ```
+2. `production.service.ts` additions (use the Task 2 cast idiom if types were restored):
+ ```typescript
+ export async function getJobOperationBatch(
+ client: SupabaseClient<Database>,
+ batchId: string,
+ companyId: string
+ ) {
+ const batch = await client
+ .from("jobOperationBatch")
+ .select("*")
+ .eq("id", batchId)
+ .eq("companyId", companyId)
+ .single();
+ if (batch.error) return batch;
+ const operations = await client
+ .from("jobOperation")
+ .select("*, job(id, jobId, itemId, quantity, dueDate, status)")
+ .eq("jobOperationBatchId", batchId);
+ return {
+ data: { ...batch.data, operations: operations.data ?? [] },
+ error: operations.error
+ };
+ }
+
+ export async function getBatchableOperations(
+ client: SupabaseClient<Database>,
+ args: { locationId: string; processId: string }
+ ) {
+ return client.rpc("get_batchable_operations", {
+ location_id: args.locationId,
+ process_id: args.processId
+ });
+ }
+
+ export async function getBatchableProcesses(
+ client: SupabaseClient<Database>,
+ companyId: string
+ ) {
+ return client
+ .from("process")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .eq("batchable", true)
+ .order("name");
+ }
+
+ export async function createJobOperationBatch(
+ client: SupabaseClient<Database>,
+ args: {
+ jobOperationIds: string[];
+ locationId: string;
+ workCenterId?: string | null;
+ companyId: string;
+ userId: string;
+ }
+ ) {
+ return client.functions.invoke("batch-operations", {
+ body: { type: "create", ...args }
+ });
+ }
+
+ export async function updateJobOperationBatch(
+ client: SupabaseClient<Database>,
+ args: {
+ type: "add" | "remove" | "update" | "dissolve";
+ batchId: string;
+ jobOperationIds?: string[];
+ workCenterId?: string | null;
+ companyId: string;
+ userId: string;
+ }
+ ) {
+ const { type, ...rest } = args;
+ return client.functions.invoke("batch-operations", {
+ body: { type, ...rest }
+ });
+ }
+ ```
+3. `batching.update.tsx` — action-only route, standard pattern (`assertIsPost` → `requirePermissions(request, { update: "production" })` → branch on `formData.get("intent")`):
+ - `intent === "create"`: validate `createJobOperationBatchValidator` (repeated `jobOperationIds` fields) → `createJobOperationBatch` → on error `return data({}, await flash(request, error(result.error, "Failed to create batch")))`; on success `return data(result.data, await flash(request, success("Batch created")))`.
+ - `intent === "add" | "remove" | "update" | "dissolve"`: validate `updateJobOperationBatchValidator` → `updateJobOperationBatch` → same flash pattern with per-intent messages ("Added to batch" / "Removed from batch" / "Batch updated" / "Batch dissolved").
+ - Return plain objects via `data(...)` — never `Response.json`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+grep -n "scheduleBatching" apps/erp/app/utils/path.ts
+# Expected: two entries
+```
+
+**Out of scope:** the board UI itself (Task 8); MES paths (Task 10).
+
+---
+
+## Task 8: Batch planning board UI
+
+**Depends on:** Task 7
+**Files:**
+- Create: `apps/erp/app/routes/x+/schedule+/batching.tsx` — loader + page
+- Create: `apps/erp/app/modules/production/ui/Schedule/Batching/BatchingBoard.tsx` (+ small `CandidateCard.tsx`, `BatchLane.tsx` in the same folder if the board file grows past ~400 lines)
+- Copy from (precedent): `apps/erp/app/routes/x+/schedule+/operations.tsx` (loader: location handling, `?filter=key:operator:value` parsing, `SearchFilter`/`Filter`/`ActiveFilters` usage), `apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx` (@dnd-kit DndContext/DragOverlay/sensors + fetcher submit with `navigate:false`), `.../Kanban/components/ItemCard.tsx` (card layout)
+
+**Steps:**
+1. **Loader** (`batching.tsx`):
+ - `requirePermissions(request, { view: "production" })`.
+ - Resolve `locationId` exactly as `operations.tsx` does (same search param + user-preference fallback).
+ - `processId` from `?process=` search param; load the picker list via `getBatchableProcesses`. If no `processId` selected, render the page with only the process picker and an empty state ("Pick a batchable process to plan batches").
+ - With a process selected: `getBatchableOperations(client, { locationId, processId })`. Partition rows: `candidates` (`jobOperationBatchId === null`) and `batches` (group the rest by `jobOperationBatchId`, carrying `batchReadableId`/`batchWorkCenterId`).
+ - Parse material facet filters from URL params using the SAME `?filter=` grammar as `operations.tsx` (keys: `formId`, `substanceId`, `gradeId`, `dimensionId`, `finishId`, plus `search`). A candidate matches if ANY element of its `materials` array satisfies ALL active facets; `search` matches job/item readable ids and descriptions case-insensitively. Filter in the loader, after the RPC.
+ - Facet options: derive each facet's options from the DISTINCT values present in the unfiltered candidates' `materials` arrays (id + name), so the planner only sees applicable choices.
+ - Also load work centers for the process (mirror how `operations.tsx` loads work centers for its columns) for the lane work-center picker.
+2. **Board** (`BatchingBoard.tsx`):
+ - Two-pane layout: left = filter bar (`SearchFilter` + `Filter` + `ActiveFilters`, same components as `operations.tsx`) above a scrollable list of candidate cards; right = vertical stack of Active batch lanes + a dashed "New batch" drop zone.
+ - Candidate card: job readableId, item readableId + description, operation quantity, due date, and material chips (`substanceName gradeName dimensionName formName` per material, deduped; show `No material properties` chip when the array is empty). Clone the visual structure of `Kanban/components/ItemCard.tsx` — do not design a new card from scratch.
+ - Batch lane: header row with `readableId`, member count and summed quantity (plain numbers — never parenthesized counts), a work-center `Combobox` (options from the loader; on change POST `intent=update` with `workCenterId`), and a dissolve menu item; body lists member cards (same card component, draggable out).
+ - DnD: one `DndContext` wrapping both panes, sensors/overlay cloned from `Kanban.tsx`. On drop: candidate → "New batch" posts `intent=create` (with `locationId`, the dragged op id); candidate → existing lane posts `intent=add`; member → candidate pane posts `intent=remove`. Submit with `useSubmit`/fetchers with `navigate: false` targeting `path.to.scheduleBatchingUpdate`, mirroring `Kanban.tsx`'s optimistic-update pattern (per-item `fetcherKey`); rely on default revalidation to refresh the loader.
+ - Wire the route page: render pickers (Location + Process, matching `operations.tsx`'s selector components) above the board.
+ - Match the file's surroundings for Lingui: `operations.tsx`-family components use unwrapped literals in places — match whichever convention the cloned files use; do not introduce a mixed style.
+3. Add a navigation entry so the board is reachable: grep for where `path.to.scheduleOperation`/"Schedule" is registered in the production nav/menu config (`grep -rn "scheduleOperation" apps/erp/app/modules/production/ apps/erp/app/components/Layout/ --include="*.ts*" -l`) and add a sibling "Batching" entry pointing to `path.to.scheduleBatching`, cloning the existing entry's shape. **If no obvious nav registry exists, STOP and note it in the PR description instead of inventing one.**
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+Browser check happens in Task 13.
+
+**Out of scope:** capacity indicators, auto-suggested batches, nesting imports, editing operation quantities/dates from this board.
+
+---
+
+## Task 9: Schedule board badge + menu
+
+**Depends on:** Task 7 (independent of Task 8)
+**Files:**
+- Modify: `apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts` — extend `operationItemValidator` (~line 97)
+- Modify: `apps/erp/app/routes/x+/schedule+/operations.tsx` — thread new RPC fields in the loader mapping
+- Modify: `apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx` — badge + menu items
+- Copy from (precedent): the existing badge/menu rendering in the SAME ItemCard (menu ~181-220, badges ~299-311)
+
+**Steps:**
+1. `types.ts`: add to `operationItemValidator`: `processBatchable: z.boolean().optional()`, `jobOperationBatchId: z.string().nullable().optional()`, `batchReadableId: z.string().nullable().optional()`.
+2. `operations.tsx` loader: where RPC rows map into items (`makeDurations(op)` region ~241), thread the three new RPC columns onto each item.
+3. `ItemCard.tsx`:
+ - Badge, next to the existing status/priority badges: when `item.jobOperationBatchId` is set, render `<Badge variant="secondary">{item.batchReadableId ?? "Batched"}</Badge>` (import `Badge` from `@carbon/react` if not present; match neighbors).
+ - Menu, after the existing items: for `item.processBatchable && !item.jobOperationBatchId`, a "Batch planning" item that navigates to `` `${path.to.scheduleBatching}?process=${item.processId}` `` (use the file's existing navigation idiom); for `item.jobOperationBatchId`, a destructive "Remove from batch" item that posts `intent=remove` + `batchId` + `jobOperationIds[]=[item.id]` to `path.to.scheduleBatchingUpdate` via a fetcher (clone the prop-threading used by the existing menu callbacks ~198-212).
+ - Icons: pick existing `react-icons/lu` icons — verify `LuLayers` and `LuUngroup` exist in the installed version (`grep -rn "LuLayers\|LuUngroup" apps/erp/app --include="*.tsx" | head`); fall back to icons already imported in this file.
+4. MES reads the same RPC but its card changes are Task 10 — do not touch MES here.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exit 0
+```
+
+**Out of scope:** collapsing ERP board cards into one (ERP keeps one card per operation; only MES collapses — the ERP badge communicates membership).
+
+---
+
+## Task 10: MES kanban batch collapse
+
+**Depends on:** Task 7
+**Files:**
+- Modify: `apps/mes/app/utils/path.ts` — batch paths
+- Modify: `apps/mes/app/routes/x+/operations.tsx` — loader collapse (~52-236 mapping region)
+- Modify: `apps/mes/app/components/Kanban/components/ItemCard.tsx` — batch card rendering
+- Copy from (precedent): the SAME files' existing item mapping and card structure
+
+**Steps:**
+1. `apps/mes/app/utils/path.ts` (pattern near the operation paths):
+ ```typescript
+ batch: (id: string) => generatePath(`${x}/batch/${id}`),
+ batchComplete: (id: string) => generatePath(`${x}/batch/${id}/complete`),
+ ```
+ (Match the file's actual `x`/generatePath idiom.)
+2. `operations.tsx` loader: after mapping RPC rows, collapse rows sharing a non-null `jobOperationBatchId`: keep the first row per batch as the card item; attach `batchId`, `batchReadableId`, `batchSize` (member count), `batchTargetQuantity` (sum of member `targetQuantity`), and `batchMembers: [{ jobReadableId, itemReadableId, targetQuantity }]`. Non-batched rows pass through unchanged.
+3. `ItemCard.tsx`: when `item.batchSize > 1`:
+ - render the batch readableId and a `×{batchSize}` indicator next to the quantity heading (MES components are `size="lg"`),
+ - show summed quantity,
+ - link the card to `path.to.batch(item.batchId)` instead of the per-operation route (find where the card link/`Link` target is built and branch there).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: exit 0
+```
+
+**Out of scope:** the batch view itself (Task 11); ERP board.
+
+---
+
+## Task 11: MES batch view + complete flow
+
+**Depends on:** Tasks 6, 10
+**Files:**
+- Create: `apps/mes/app/routes/x+/batch.$batchId.tsx` — batch view (loader + page)
+- Create: `apps/mes/app/routes/x+/batch.$batchId.complete.tsx` — action route
+- Modify: `apps/mes/app/services/operations.service.ts` — `getJobOperationBatch` + optional batch tag on event creation
+- Copy from (precedent): `apps/mes/app/routes/x+/start.$operationId.tsx` + `end.$operationId.tsx` (timer actions + `requirePermissions(request, {})` idiom), `apps/mes/app/routes/x+/complete.tsx` (per-op completion: `issue` invoke), `finishJobOperation` (`operations.service.ts:148-189`, GL loop)
+
+**Steps:**
+1. `operations.service.ts`: add `getJobOperationBatch(client, batchId, companyId)` — same two-query shape as the ERP version (Task 7 step 2), MES idiom (`getOpenJobs` at :24-37 is the style reference).
+2. **Timer tagging:** read how `start.$operationId.tsx` creates a `productionEvent` (which service function inserts it). Extend that service function with an OPTIONAL `jobOperationBatchId` param (additive; default undefined → column null) and pass it only from the new batch routes. **If event creation happens inside an edge function rather than the MES service, STOP and report with the file/line you found — do not fork the flow.**
+3. **Batch view route** `batch.$batchId.tsx`:
+ - Loader: same `requirePermissions` idiom as `start.$operationId.tsx:20`; `getJobOperationBatch`; plus open/ended batch events (`productionEvent` where `jobOperationBatchId = batchId`) for timer display.
+ - Page (MES sizing `size="lg"`): batch header (readableId, process name, work center, member count, summed quantity); member table: job readableId, item, operation quantity, due date, link to `path.to.operation(memberOpId)` for per-op flows (materials, scrap before completion); Start/Stop buttons posting to new nested actions that call the SAME start/end service functions as the per-op routes but with the first member's operation id + `jobOperationBatchId` (clone the action bodies of `start.$operationId.tsx` / `end.$operationId.tsx` into `batch.$batchId.tsx`'s action with intents, or as tiny sibling action routes — pick whichever mirrors the existing file layout most closely);
+ - **Complete Batch** section: `ValidatedForm` with `completeJobOperationBatchValidator`; one row per member with a `Number` input pre-filled with the member's remaining quantity (operation quantity minus prior `quantityComplete` if the loader has it, else operation quantity) and an optional scrap `Number`; copy text: "Time and cost split across jobs proportionally to quantity."
+4. **Complete action** `batch.$batchId.complete.tsx`:
+ - `assertIsPost` → `requirePermissions` → validate → `serviceRole.functions.invoke("batch-operations", { body: { type: "complete", batchId, members, companyId, userId } })`; on error, flash + return.
+ - Then replicate `complete.tsx`'s material issue per member: for each member with `quantity > 0`, `serviceRole.functions.invoke("issue", { body: { type: "jobOperation", id: member.jobOperationId, quantity: member.quantity, companyId, userId } })` — read `complete.tsx` first and mirror its EXACT body shape for the `jobOperation` case (field names may include extras); collect per-member errors and flash a combined warning if any fail (operations are already Done — same failure surface as today's per-op flow).
+ - Then replicate the GL loop from `finishJobOperation:148-189`: select `productionEvent` rows where `id IN (returned eventIds)` (or `jobOperationBatchId = batchId`) with `endTime NOT NULL AND postedToGL = false`, and invoke `post-production-event` per event with the same body shape that file uses.
+ - `throw redirect(path.to.operations)` with success flash (mirror `end.$operationId.tsx`'s redirect+flash shape).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: exit 0
+deno check packages/database/supabase/functions/batch-operations/index.ts 2>&1 | tail -3
+# Expected: still clean
+```
+
+**Out of scope:** aggregate one-tap material issue beyond the per-member `issue` calls above; NCR/quality workflow changes; rework flows on batches (per-member ops remain real rows — existing flows apply).
+
+---
+
+## Task 12: Docs/AGENTS sync
+
+**Depends on:** Tasks 1-11
+**Files:**
+- Modify: `apps/erp/app/modules/production/AGENTS.md` — data model row + service functions + concept line
+- Modify: `apps/erp/app/modules/resources/AGENTS.md` (if it exists; check) — `process.batchable` mention
+- Modify: `.ai/specs/2026-07-03-job-operation-batching.md` — changelog entry on implementation
+- Copy from (precedent): existing table rows / concept lines in the same AGENTS.md files
+
+**Steps:**
+1. Production AGENTS.md: add `jobOperationBatch` to the data-model table ("Operation batch: N job operations on one batchable process run together; proportional time/cost split at completion; jobs never merged; BOM untouched"); add the new service functions to Key Service Functions; add a Key Domain Concepts bullet: "**Operation Batch** — jobs sharing one run on a batchable process (laser, furnace). Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`)."
+2. Resources AGENTS.md (if present): note `process.batchable` next to wherever `completeAllOnScan` is documented; skip silently if the file doesn't document process columns.
+3. Spec changelog: add implementation entry; **ask Brad** before moving the spec to `implemented/`.
+4. Comment on issue #1010 linking the PR and suggesting the title change to "Job Operation Batching" (do this in Task 14 alongside the PR).
+
+**Verify:**
+```bash
+grep -n "jobOperationBatch" apps/erp/app/modules/production/AGENTS.md
+# Expected: at least 2 hits (table + concept)
+grep -rni "st[i]tch" apps/erp/app apps/mes/app packages/database/supabase --include="*.ts" --include="*.tsx" --include="*.sql" | grep -v node_modules
+# Expected: no output (the superseded feature's terminology does not exist in shipped code)
+```
+
+**Out of scope:** reader-facing docs site pages (`docs/`) — flag in the PR body that a `carbon-docs` follow-up should document batching + add the glossary entry once the feature ships; do not block this PR on it.
+
+---
+
+## Task 13: Full verification gate
+
+**Depends on:** Tasks 1-12
+**Files:** none (verification only)
+
+**Steps:**
+1. ```bash
+ pnpm exec turbo run typecheck --filter=erp && pnpm exec turbo run typecheck --filter=mes
+ pnpm run lint
+ pnpm run test
+ ```
+2. Browser e2e (mandatory for UI work). Boot with plain `crbn up` (portless `*.dev`), never `--no-portless`. If accounting-enabled behavior is checked (GL posting), first enable accounting at `/x/settings/accounting` (fresh resets seed it off). Then use the `/test` skill to drive:
+ 1. Resources → Processes → edit "Laser Cutting" (or any process) → check **Batchable** → save → reload → persisted; processes table shows the column.
+ 2. Create/verify 3 jobs whose routing uses that process (release them so operations exist and are Todo/Ready).
+ 3. Schedule → Batching → pick location + process → all 3 operations listed with material chips; apply a substance/grade/dimension filter and confirm narrowing (jobs with A36-steel BOM lines stay; others drop).
+ 4. Drag one op to "New batch" → `BAT000001` lane appears; drag the other two in; assign a work center → member ops' work centers update on the schedule board (badge `BAT000001` on each card).
+ 5. Drag one member out → it returns to candidates; drag it back in. Dissolve+recreate once to prove dissolve works.
+ 6. MES → one collapsed card ×3 → open batch view → Start → wait ~1 min → Stop → Complete with per-member quantities (e.g. 5/20/10, scrap 0/1/0) → success.
+ 7. Verify in DB or UI: per-member `productionEvent` slices whose durations are ~1/7, 4/7, 2/7 of the recorded minute (weights 5/20/10); `productionQuantity` rows 5/20/10 + one Scrap 1; all member ops Done; each job's next operation Ready; batch Completed; `itemLedger` rows from `issue` per member; GL entries per event if accounting enabled.
+ 8. Ungrouped operations elsewhere behave exactly as before (spot-check one normal op start/complete).
+ 9. Attempt to dissolve the completed batch's twin scenario: create a fresh 2-op batch, start it, then try dissolve → blocked with the "complete the batch instead" error.
+ Screenshot the batching board (filters visible + a populated lane) and the MES batch view for the PR.
+
+**Verify:** the commands above; all green, screenshots saved.
+
+**Out of scope:** performance/load testing.
+
+---
+
+## Task 14: PR
+
+**Depends on:** Task 13
+**Files:** none
+
+**Steps:**
+1. **Ask Brad before pushing.** Then:
+ ```bash
+ git push -u origin feature/job-operation-batching
+ gh pr create --title "feat(production): job operation batching — batchable processes, batch planning board, proportional completion" --body "$(cat <<'EOF'
+ Tracking spec: .ai/specs/2026-07-03-job-operation-batching.md
+ Research: .ai/research/job-operation-batching.md
+ Closes #1010 (suggest retitling the issue to "Job Operation Batching")
+
+ ## What
+ - `process.batchable` flag — batchability is a property of the process (laser table: yes; brake press: no); job operations derive it via processId. No item/routing-step flags, no propagation.
+ - `jobOperationBatch` (+ `jobOperation.jobOperationBatchId`, `productionEvent.jobOperationBatchId`, `BAT` sequence); RPC additions for both boards; new `get_batchable_operations` RPC with per-operation material properties from the BOM chain.
+ - Batch planning board (`/x/schedule/batching`): filter unstarted operations by material form/substance/grade/dimension/finish, drag into batches, assign work centers. No batch size limit.
+ - `batch-operations` edge function: create/add/remove/update/dissolve/complete with server-side eligibility (batchable process, same process, unstarted, unbatched).
+ - Completion: per-member quantities + optional scrap; shared timers sliced into per-member productionEvents proportional to operation quantity (largest remainder), so job costing, estimates-vs-actuals, and GL post per job with zero special-casing; material issued per member job's own BOM via the existing issue function.
+ - MES: collapsed batch card, batch view with timers, complete-batch flow with GL posting.
+ - Operation batches are distinct from lot/batch tracking — documented in AGENTS.md.
+
+ ## Verification
+ - typecheck (erp, mes), lint, tests green
+ - Browser e2e: flag → plan (filters + drag) → run → complete (5/20/10 split) → downstream release → guards
+ - Screenshots: batching board, MES batch view
+
+ ## Follow-ups (not in this PR)
+ - carbon-docs page + glossary entry once shipped
+ - v2: area/cut-time weights via nesting import; solver-suggested batches; capacity modeling
+ EOF
+ )"
+ ```
+2. Comment on issue #1010 linking the PR and the retitle suggestion.
+
+**Out of scope:** merging; moving the spec to `implemented/` (ask first).
+
+---
+
+## Out of scope for the whole plan (do not build)
+
+- Batch capacity semantics (table area, furnace volume) — separate future spec.
+- Nesting-software import (per-part cut time/area weights) — v2.
+- Auto-suggested batches in planning/MRP — v2.
+- Batch-level NCR (per-operation NCR flow is unchanged and sufficient).
+- ANY flag on items, method operations, or quote operations. Nothing propagates through `get-method`.
+- Group size limits of any kind.
+
+## Residual risks
+
+| Watch for | Mitigation |
+|-----------|------------|
+| Generated-types divergence (cloud vs local) | Ground rule 4: inspect diff, restore + cast if wrong; note in commits |
+| `get_active_job_operations_by_location` fork drift | Task 1 step 2 forces re-locating the NEWEST definition before forking; both boards smoke-tested in Task 13 |
+| `productionEvent` NOT NULL columns beyond those cloned in slices | Task 6 step 5 checks `\d "productionEvent"` before deno check; STOP hatch |
+| Event-creation flow living somewhere unexpected (edge fn vs MES service) | Task 11 step 2 STOP hatch |
+| `issue`/`post-production-event` body shapes | Task 11 mirrors `complete.tsx` / `finishJobOperation` verbatim rather than trusting this plan's sketch |
+| Filter grammar mismatch with `useFilters` | Task 8 parses with the same helpers `operations.tsx` uses — clone, don't reimplement |
diff --git a/.ai/plans/work-order-stitching-plan.md b/.ai/plans/work-order-stitching-plan.md
deleted file mode 100644
index 54116c76be..0000000000
--- a/.ai/plans/work-order-stitching-plan.md
+++ /dev/null
@@ -1,921 +0,0 @@
-# Work Order Stitching — Implementation Plan (v2, fully grounded)
-
-> **Executor:** Claude Opus 4.8
-> **Design spec:** `.ai/specs/2026-07-02-work-order-stitching.md` (in-progress; all open questions resolved)
-> **Research:** `.ai/scratch/research/work-order-stitching.md`
-> **Tracking issue:** https://github.com/crbnos/carbon/issues/1010
-> **Branch:** `feature/work-order-stitching`
->
-> v2 note: every file below was read during planning (2026-07-02). Line numbers are
-> anchors, not gospel — re-locate by the quoted code if they drifted. All former
-> "ground-then-edit" unknowns are resolved; findings are inlined as **[VERIFIED]** notes.
-
-## Executor ground rules
-
-1. **Never rebuild the database.** `pnpm db:migrate` applies; if the local DB is unreachable, stop and tell the user.
-2. **Commits:** conventional format, **no AI attribution** (no Co-Authored-By, no "Generated with").
-3. **`pnpm --filter erp`** — the package name is `erp`, NOT `@carbon/erp` (wrong filter silently no-ops). MES is `mes`.
-4. Verification commands close each phase. Run them; don't assert green without output.
-5. Spec wins over plan; code wins over both — surface conflicts, don't improvise silently.
-
-## Verified facts the design rests on (do not re-litigate)
-
-- **[VERIFIED]** `sync_finish_job_operation` is a **BEFORE, FOR EACH ROW** Postgres trigger (`trg_event_sync_jobOperation` → `dispatch_event_interceptors('sync_finish_job_operation')`, created by `attach_event_trigger` in `20260410030406_event-system-after-interceptors.sql:113-124`). A multi-row Kysely `UPDATE ... SET status='Done'` fires it once per row, and Kysely does NOT bypass it (it's a real DB trigger). Each member job's own downstream op is released independently by the interceptor's dependency query (`20260410031809_production-interceptors.sql:109-148`). **No cross-job dependency edges needed.**
-- **[VERIFIED]** `getNextSequence(trx, tableName, companyId)` — exact signature in `packages/database/supabase/functions/shared/get-next-sequence.ts:5-9`; reads/updates the `"sequence"` table by `(table, companyId)`.
-- **[VERIFIED]** `process` has a **bare PK `("id")`** (`20240819115702_work-centers.sql:12`) — FK from `jobOperationGroup.processId` references `"process"("id")` only, no composite.
-- **[VERIFIED]** `productionQuantity` (`20241002012019:7-27`): bare PK `id` DEFAULT `xid()`, `quantity` is **INTEGER**, `createdAt` defaults NOW(). Minimal insert: `{ jobOperationId, type, quantity, companyId, createdBy }`.
-- **[VERIFIED]** Newest `get_active_job_operations_by_location` definition lives in `20260531084723_rework-serial-flow.sql` — the RPC feeds **both** the ERP schedule board and the MES kanban.
-- **[VERIFIED]** New companies get their sequences from `packages/database/supabase/functions/seed-company/index.ts` (it writes `"sequence"` rows).
-- **[VERIFIED]** `get-method` copies: `itemToJob` builds `jobOperationsInserts.push({...})` with an **enumerated field list** at ~lines 635–663 (loop var `op`); `quoteLineToJob` maps `quoteOperation → jobOperation` with an enumerated list at ~4543–4579; `itemToQuoteLine` pushes `quoteOperationsInserts` at ~1939–1969; `itemToItem` (method→method) uses spread `{...operation}` at ~215–224 so new columns copy automatically.
-- **[VERIFIED]** MES `finishJobOperation` (`apps/mes/app/services/operations.service.ts:148-189`) sets status `Done` then invokes `post-production-event` for each ended, un-posted `productionEvent` (`postedToGL = false`). Group completion must replicate this GL-posting step.
-
-## Dependency graph
-
-```
-Phase 0 → Phase 1 (schema) → Phase 2 (models) → Phase 3 (edge fn) → Phase 4 (services/propagation)
- → Phase 5 (ERP UI) ∥ Phase 6 (MES UI)
- → Phase 7 (verify, docs, PR)
-```
-
----
-
-## Phase 0 — Branch
-
-```bash
-git checkout main && git pull
-git checkout -b feature/work-order-stitching
-```
-
----
-
-## Phase 1 — Database migration
-
-### Task 1.1 Create + write the migration
-
-```bash
-pnpm db:migrate:new work-order-stitching
-```
-
-If the generated HHMMSS is `000000`, rename with random digits (timestamp = cross-branch PK).
-
-Complete file contents:
-
-```sql
--- Work Order Stitching (spec: .ai/specs/2026-07-02-work-order-stitching.md)
--- Groups compatible jobOperations across jobs into one virtual operation.
--- Jobs are never merged; the BOM is never touched.
-
--- 1. Master-data flags
-ALTER TABLE "itemReplenishment"
- ADD COLUMN "workOrderStitching" BOOLEAN NOT NULL DEFAULT false;
-
-ALTER TABLE "methodOperation"
- ADD COLUMN "stitchable" BOOLEAN NOT NULL DEFAULT false;
-
--- quoteOperation carries the flag so quote-born jobs (quoteLineToJob) keep it
-ALTER TABLE "quoteOperation"
- ADD COLUMN "stitchable" BOOLEAN NOT NULL DEFAULT false;
-
-ALTER TABLE "jobOperation"
- ADD COLUMN "stitchable" BOOLEAN NOT NULL DEFAULT false;
-
--- 2. Operation group ("virtual operation")
-CREATE TYPE "jobOperationGroupStatus" AS ENUM ('Active', 'Completed', 'Cancelled');
-
-CREATE TABLE "jobOperationGroup" (
- "id" TEXT NOT NULL DEFAULT id('wos'),
- "readableId" TEXT NOT NULL,
- "companyId" TEXT NOT NULL,
- "processId" TEXT NOT NULL,
- "workCenterId" TEXT,
- "status" "jobOperationGroupStatus" NOT NULL DEFAULT 'Active',
- "customFields" JSONB,
- "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,
-
- CONSTRAINT "jobOperationGroup_pkey" PRIMARY KEY ("id", "companyId"),
- CONSTRAINT "jobOperationGroup_companyId_fkey" FOREIGN KEY ("companyId")
- REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "jobOperationGroup_processId_fkey" FOREIGN KEY ("processId")
- REFERENCES "process"("id"),
- CONSTRAINT "jobOperationGroup_workCenterId_fkey" FOREIGN KEY ("workCenterId")
- REFERENCES "workCenter"("id") ON DELETE SET NULL,
- CONSTRAINT "jobOperationGroup_readableId_unique" UNIQUE ("readableId", "companyId")
-);
-
-CREATE INDEX "jobOperationGroup_companyId_idx" ON "jobOperationGroup" ("companyId");
-CREATE INDEX "jobOperationGroup_processId_idx" ON "jobOperationGroup" ("processId");
-CREATE INDEX "jobOperationGroup_workCenterId_idx" ON "jobOperationGroup" ("workCenterId");
-CREATE INDEX "jobOperationGroup_createdBy_idx" ON "jobOperationGroup" ("createdBy");
-
-ALTER TABLE "jobOperationGroup" ENABLE ROW LEVEL SECURITY;
-
-CREATE POLICY "SELECT" ON "public"."jobOperationGroup"
- FOR SELECT USING (
- "companyId" = ANY (
- SELECT unnest(get_companies_with_employee_role()::text[])
- )
- );
-
-CREATE POLICY "INSERT" ON "public"."jobOperationGroup"
- FOR INSERT WITH CHECK (
- "companyId" = ANY (
- SELECT unnest(get_companies_with_employee_permission('production_create')::text[])
- )
- );
-
-CREATE POLICY "UPDATE" ON "public"."jobOperationGroup"
- FOR UPDATE USING (
- "companyId" = ANY (
- SELECT unnest(get_companies_with_employee_permission('production_update')::text[])
- )
- );
-
-CREATE POLICY "DELETE" ON "public"."jobOperationGroup"
- FOR DELETE USING (
- "companyId" = ANY (
- SELECT unnest(get_companies_with_employee_permission('production_delete')::text[])
- )
- );
-
--- 3. Membership — one nullable column on jobOperation
-ALTER TABLE "jobOperation" ADD COLUMN "operationGroupId" TEXT;
-
-CREATE INDEX "jobOperation_operationGroupId_idx"
- ON "jobOperation" ("operationGroupId")
- WHERE "operationGroupId" IS NOT NULL;
-
--- 4. Sequence for readable ids (WOS000001) — pattern from 20260601143527_picking-lists.sql:134-145
-INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
-SELECT
- 'jobOperationGroup',
- 'Operation Group',
- 'WOS',
- NULL,
- 0,
- 6,
- 1,
- "id"
-FROM "company"
-ON CONFLICT DO NOTHING;
-```
-
-> Before applying, eyeball the RLS idiom in the single newest migration in the
-> directory; if it differs from `= ANY (SELECT unnest(...::text[]))`, copy the
-> current idiom. Everything else above is verified against live schema.
-
-### Task 1.2 New-company sequence seeding
-
-File: `packages/database/supabase/functions/seed-company/index.ts` **[VERIFIED: this is where new companies get sequence rows]**. Find the array/insert of sequence rows and add an entry matching the existing shape:
-
-```typescript
-{ table: "jobOperationGroup", name: "Operation Group", prefix: "WOS", suffix: null, next: 0, size: 6, step: 1 }
-```
-
-(Adapt to the exact literal shape used by neighbors in that file.)
-
-### Task 1.3 RPC columns for both boards
-
-The ERP schedule board and MES kanban both read `get_active_job_operations_by_location`. Newest definition: `packages/database/supabase/migrations/20260531084723_rework-serial-flow.sql`. In the **same migration file from Task 1.1**, re-declare the function: copy the newest definition verbatim, and add to its SELECT list + return table:
-
-```sql
- jo."stitchable",
- jo."operationGroupId",
- g."readableId" AS "operationGroupReadableId"
-```
-
-with `LEFT JOIN "jobOperationGroup" g ON g."id" = jo."operationGroupId" AND g."companyId" = jo."companyId"`.
-
-### Task 1.4 Apply + verify + commit
-
-```bash
-pnpm db:migrate
-# Expected: applies cleanly; DB types + swagger regenerate.
-
-grep -n "workOrderStitching\|operationGroupId\|jobOperationGroup" packages/database/src/types.ts | head
-# Expected: hits for all three.
-
-psql "$SUPABASE_DB_URL" -c 'SELECT "table","prefix","size" FROM "sequence" WHERE "table"=$$jobOperationGroup$$ LIMIT 3;'
-# Expected: one row per company, prefix WOS, size 6.
-
-git add -A && git commit -m "feat(production): work order stitching schema (jobOperationGroup, stitchable flags, sequence, RPC columns)"
-```
-
----
-
-## Phase 2 — Validators / models
-
-### Task 2.1 Items validators
-
-File: `apps/erp/app/modules/items/items.models.ts`.
-
-Edit 1 — `itemManufacturingValidator` (~line 517), full replacement:
-
-```typescript
-export const itemManufacturingValidator = z.object({
- itemId: z.string().min(1, { message: "Item ID is required" }),
- // manufacturingBlocked: zfd.checkbox(),
- requiresConfiguration: zfd.checkbox().optional(),
- lotSize: zfd.numeric(z.number().min(0)),
- scrapPercentage: zfd.numeric(z.number().min(0)),
- leadTime: zfd.numeric(z.number().min(0)),
- workOrderStitching: zfd.checkbox().optional()
-});
-```
-
-Edit 2 — `methodOperationValidator` object body (~line 388; the object closes at ~line 430 before the `.refine` chain). Add after `operationLeadTime`:
-
-```typescript
- operationLeadTime: zfd.numeric(z.number().min(0).optional()),
- stitchable: zfd.checkbox().optional()
-```
-
-Edit 3 — find the **quote operation validator** (grep `quoteOperationValidator` in `apps/erp/app/modules/sales/sales.models.ts`) and add the same `stitchable: zfd.checkbox().optional()` field so quote-side operation forms round-trip the column.
-
-### Task 2.2 Production models
-
-File: `apps/erp/app/modules/production/production.models.ts` (imports `z` and `zfd` already — verify at top of file). Add near the other status consts:
-
-```typescript
-export const jobOperationGroupStatus = [
- "Active",
- "Completed",
- "Cancelled"
-] as const;
-
-export const groupJobOperationsValidator = z.object({
- jobOperationIds: z
- .array(z.string().min(1))
- .min(2, { message: "Select at least two operations to group" })
- .max(10, { message: "A group cannot exceed 10 operations" })
-});
-
-export const ungroupJobOperationsValidator = z.object({
- operationGroupId: z.string().min(1, { message: "Group is required" })
-});
-
-export const completeOperationGroupValidator = z.object({
- operationGroupId: z.string().min(1, { message: "Group is required" }),
- producedQuantity: zfd.numeric(z.number().int().min(0)),
- notes: zfd.text(z.string().optional())
-});
-```
-
-(`producedQuantity` is `.int()` — `productionQuantity.quantity` is INTEGER **[VERIFIED]**.)
-
-```bash
-pnpm --filter erp typecheck
-git add -A && git commit -m "feat(production): validators for operation grouping"
-```
-
----
-
-## Phase 3 — `stitch` edge function
-
-### Task 3.1 Scaffold + register
-
-```bash
-pnpm db:function:new stitch
-```
-
-`packages/database/supabase/config.toml` — add (formatting mirrors `[functions.mrp]` at ~line 161):
-
-```toml
-[functions.stitch]
-enabled = true
-verify_jwt = true
-```
-
-### Task 3.2 Function body
-
-File: `packages/database/supabase/functions/stitch/index.ts` — complete contents. Imports mirror `trigger-rework/index.ts` (std `0.168.0` **[VERIFIED]**):
-
-```typescript
-import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import z from "npm:zod@^3.24.1";
-import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-import { corsHeaders } from "../lib/headers.ts";
-import { requirePermissions } from "../lib/supabase.ts";
-import type { DB } from "../lib/types.ts";
-import { getNextSequence } from "../shared/get-next-sequence.ts";
-
-const pool = getConnectionPool(1);
-const db = getDatabaseClient<DB>(pool);
-
-const MAX_GROUP_SIZE = 10;
-
-const payloadValidator = z.discriminatedUnion("type", [
- z.object({
- type: z.literal("group"),
- jobOperationIds: z.array(z.string()).min(2).max(MAX_GROUP_SIZE),
- companyId: z.string(),
- userId: z.string()
- }),
- z.object({
- type: z.literal("ungroup"),
- operationGroupId: z.string(),
- companyId: z.string(),
- userId: z.string()
- }),
- z.object({
- type: z.literal("complete"),
- operationGroupId: z.string(),
- producedQuantity: z.number().int().min(0),
- companyId: z.string(),
- userId: z.string()
- })
-]);
-
-/** Even split with largest-remainder rounding: integer parts sum exactly to total. */
-function evenSplit(total: number, parts: number): number[] {
- const base = Math.floor(total / parts);
- const remainder = total - base * parts;
- return Array.from({ length: parts }, (_, i) => base + (i < remainder ? 1 : 0));
-}
-
-serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
-
- try {
- const payload = payloadValidator.parse(await req.json());
- const { companyId, userId } = payload;
-
- await requirePermissions(req, companyId, userId, {
- update: "production"
- });
-
- let result: Record<string, unknown> = {};
-
- switch (payload.type) {
- case "group": {
- result = await db.transaction().execute(async (trx) => {
- const operations = await trx
- .selectFrom("jobOperation")
- .selectAll()
- .where("id", "in", payload.jobOperationIds)
- .where("companyId", "=", companyId)
- .execute();
-
- if (operations.length !== payload.jobOperationIds.length) {
- throw new Error("One or more operations not found");
- }
-
- const first = operations[0];
- for (const op of operations) {
- if (!op.stitchable) {
- throw new Error(`Operation ${op.id} is not marked stitchable`);
- }
- if (op.operationGroupId) {
- throw new Error(`Operation ${op.id} is already in a group`);
- }
- if (op.processId !== first.processId) {
- throw new Error("All operations must share the same process");
- }
- if (op.workCenterId !== first.workCenterId) {
- throw new Error("All operations must share the same work center");
- }
- if (!["Todo", "Ready", "Waiting"].includes(op.status)) {
- throw new Error(`Operation ${op.id} has already started`);
- }
- }
-
- const events = await trx
- .selectFrom("productionEvent")
- .select("id")
- .where("jobOperationId", "in", payload.jobOperationIds)
- .limit(1)
- .execute();
- if (events.length > 0) {
- throw new Error(
- "Operations with recorded production events cannot be grouped"
- );
- }
-
- const jobs = await trx
- .selectFrom("job")
- .select(["id", "itemId"])
- .where("id", "in", operations.map((o) => o.jobId))
- .execute();
- const replenishments = await trx
- .selectFrom("itemReplenishment")
- .select(["itemId", "workOrderStitching"])
- .where("itemId", "in", jobs.map((j) => j.itemId))
- .where("companyId", "=", companyId)
- .execute();
- const optedIn = new Set(
- replenishments
- .filter((r) => r.workOrderStitching)
- .map((r) => r.itemId)
- );
- for (const job of jobs) {
- if (!optedIn.has(job.itemId)) {
- throw new Error(
- `Item on job ${job.id} does not have Work Order Stitching enabled`
- );
- }
- }
-
- const readableId = await getNextSequence(
- trx,
- "jobOperationGroup",
- companyId
- );
-
- const group = await trx
- .insertInto("jobOperationGroup")
- .values({
- readableId,
- companyId,
- processId: first.processId,
- workCenterId: first.workCenterId,
- status: "Active",
- createdBy: userId
- })
- .returning(["id", "readableId"])
- .executeTakeFirstOrThrow();
-
- await trx
- .updateTable("jobOperation")
- .set({ operationGroupId: group.id, updatedBy: userId })
- .where("id", "in", payload.jobOperationIds)
- .execute();
-
- return group;
- });
- break;
- }
-
- case "ungroup": {
- result = await db.transaction().execute(async (trx) => {
- const members = await trx
- .selectFrom("jobOperation")
- .select(["id"])
- .where("operationGroupId", "=", payload.operationGroupId)
- .execute();
- if (members.length === 0) {
- throw new Error("Group not found or empty");
- }
-
- const events = await trx
- .selectFrom("productionEvent")
- .select("id")
- .where("jobOperationId", "in", members.map((m) => m.id))
- .limit(1)
- .execute();
- if (events.length > 0) {
- throw new Error(
- "Cannot ungroup: production has been recorded. Complete the group instead — member jobs then proceed independently."
- );
- }
-
- await trx
- .updateTable("jobOperation")
- .set({ operationGroupId: null, updatedBy: userId })
- .where("operationGroupId", "=", payload.operationGroupId)
- .execute();
-
- await trx
- .deleteFrom("jobOperationGroup")
- .where("id", "=", payload.operationGroupId)
- .where("companyId", "=", companyId)
- .execute();
-
- return { ungrouped: members.length };
- });
- break;
- }
-
- case "complete": {
- result = await db.transaction().execute(async (trx) => {
- const members = await trx
- .selectFrom("jobOperation")
- .selectAll()
- .where("operationGroupId", "=", payload.operationGroupId)
- .where("companyId", "=", companyId)
- .execute();
- if (members.length === 0) {
- throw new Error("Group not found or empty");
- }
- if (members.some((m) => m.status === "Done")) {
- throw new Error("Group already completed");
- }
-
- // productionQuantity minimal insert [VERIFIED cols]: id defaults xid(),
- // createdAt defaults NOW(); quantity is INTEGER.
- const splits = evenSplit(payload.producedQuantity, members.length);
- if (payload.producedQuantity > 0) {
- await trx
- .insertInto("productionQuantity")
- .values(
- members.map((op, i) => ({
- jobOperationId: op.id,
- type: "Production" as const,
- quantity: splits[i],
- companyId,
- createdBy: userId
- }))
- )
- .execute();
- }
-
- // Multi-row Done. [VERIFIED] trg_event_sync_jobOperation is a
- // BEFORE/FOR EACH ROW trigger dispatching sync_finish_job_operation
- // per row: closes each op's open productionEvents and releases each
- // job's own dependent operation. No cross-job edges exist or are needed.
- await trx
- .updateTable("jobOperation")
- .set({ status: "Done", updatedBy: userId })
- .where("operationGroupId", "=", payload.operationGroupId)
- .execute();
-
- await trx
- .updateTable("jobOperationGroup")
- .set({
- status: "Completed",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .where("id", "=", payload.operationGroupId)
- .where("companyId", "=", companyId)
- .execute();
-
- return { completed: members.length, splits, memberIds: members.map((m) => m.id) };
- });
- break;
- }
- }
-
- return new Response(JSON.stringify({ success: true, ...result }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 200
- });
- } catch (err) {
- console.error("Error in stitch:", err);
- return new Response(JSON.stringify({ error: (err as Error).message }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500
- });
- }
-});
-```
-
-> **GL posting note:** `complete` intentionally does NOT invoke `post-production-event`.
-> The caller (MES action, Task 6.3) replicates `finishJobOperation`'s pattern:
-> after the edge call succeeds, query ended events with `postedToGL = false` for
-> the returned `memberIds` and invoke `post-production-event` per event —
-> exactly as `apps/mes/app/services/operations.service.ts:148-189` does today.
-
-### Task 3.3 Verify + commit
-
-```bash
-deno check packages/database/supabase/functions/stitch/index.ts 2>&1 | head
-# Expected: clean (or only lib warnings shared by sibling functions)
-
-git add -A && git commit -m "feat(functions): stitch edge function (group/ungroup/complete)"
-```
-
----
-
-## Phase 4 — ERP services + propagation
-
-### Task 4.1 `production.service.ts` additions
-
-File: `apps/erp/app/modules/production/production.service.ts`. Place near `triggerJobSchedule` (~line 2172), matching its signature idiom:
-
-```typescript
-export async function getJobOperationGroup(
- client: SupabaseClient<Database>,
- operationGroupId: string,
- companyId: string
-) {
- const group = await client
- .from("jobOperationGroup")
- .select("*")
- .eq("id", operationGroupId)
- .eq("companyId", companyId)
- .single();
- if (group.error) return group;
-
- const operations = await client
- .from("jobOperation")
- .select("*, job(id, jobId, itemId, quantity, dueDate, status)")
- .eq("operationGroupId", operationGroupId);
-
- return {
- data: { ...group.data, operations: operations.data ?? [] },
- error: operations.error
- };
-}
-
-export async function getStitchableOperations(
- client: SupabaseClient<Database>,
- args: { processId: string; workCenterId: string | null; companyId: string }
-) {
- let query = client
- .from("jobOperation")
- .select("*, job(id, jobId, itemId, quantity, dueDate)")
- .eq("companyId", args.companyId)
- .eq("processId", args.processId)
- .eq("stitchable", true)
- .is("operationGroupId", null)
- .in("status", ["Todo", "Ready", "Waiting"]);
-
- return args.workCenterId
- ? query.eq("workCenterId", args.workCenterId)
- : query.is("workCenterId", null);
-}
-
-export async function groupJobOperations(
- client: SupabaseClient<Database>,
- args: { jobOperationIds: string[]; companyId: string; userId: string }
-) {
- return client.functions.invoke("stitch", {
- body: { type: "group", ...args }
- });
-}
-
-export async function ungroupJobOperations(
- client: SupabaseClient<Database>,
- args: { operationGroupId: string; companyId: string; userId: string }
-) {
- return client.functions.invoke("stitch", {
- body: { type: "ungroup", ...args }
- });
-}
-```
-
-(No ERP-side `complete` wrapper — completion is an MES flow, Task 6.3.)
-
-### Task 4.2 `upsertItemManufacturing` passthrough
-
-File: `apps/erp/app/modules/items/items.service.ts` (~line 3290). Read the function body: if it spreads the validated payload into `.update(...)`, no change; if it enumerates columns, add `workOrderStitching`. Also confirm `getItemManufacturing` (~line 712) uses `select("*")` — it does per prior research; if enumerated, add the column. State the finding in the commit message.
-
-### Task 4.3 `get-method` propagation **[all sites VERIFIED]**
-
-File: `packages/database/supabase/functions/get-method/index.ts`. Source selects are `select("*", ...)` everywhere, so the new columns arrive on `op` automatically. Four edits:
-
-1. **`itemToJob`** (~635–663): add to the `jobOperationsInserts.push({...})` object:
- ```typescript
- stitchable: op.stitchable ?? false,
- ```
-2. **`quoteLineToJob`** (~4543–4579): add to the mapped jobOperation object:
- ```typescript
- stitchable: op.stitchable ?? false,
- ```
-3. **`itemToQuoteLine`** (~1939–1969): add to `quoteOperationsInserts.push({...})`:
- ```typescript
- stitchable: op.stitchable ?? false,
- ```
-4. **`itemToItem`** (~215–224): uses `{...operation}` spread — **no edit needed** (verify the spread is still there).
-
-```bash
-deno check packages/database/supabase/functions/get-method/index.ts 2>&1 | head
-git add -A && git commit -m "feat(production): operation group services + stitchable propagation through get-method"
-```
-
----
-
-## Phase 5 — ERP UI
-
-### Task 5.1 Manufacturing tab checkbox
-
-File: `apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx`. Insert after the `requiresConfiguration` `<Boolean>` block (ends line ~89), inside the same grid:
-
-```tsx
- <Boolean
- name="workOrderStitching"
- label={t`Work Order Stitching`}
- bordered
- description={t`Allow this item's stitchable operations to be grouped into a shared run across work orders`}
- className="col-span-3"
- />
-```
-
-No route change needed: the action at `apps/erp/app/routes/x+/part+/$itemId.details.tsx` (`intent === "manufacturing"`) validates with the updated validator.
-
-### Task 5.2 `BillOfProcess.tsx` stitchable checkbox **[structure VERIFIED]**
-
-File: `apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx`.
-
-1. Add `Boolean` to the import from `~/components/Form` (current imports at ~84–96: `Number, NumberControlled, Process, Select, SelectControlled, StandardFactor, Submit, SupplierProcess, Tags, Tool, UnitHint, UnitOfMeasure, WorkCenter` — no Boolean yet).
-2. The operation edit defaults object is at ~968–987. Add:
- ```typescript
- stitchable: item.data.stitchable ?? false,
- ```
-3. Place the field in the main (always-visible) field grid near `operationType`/`processId` (NOT inside the collapsible time-disclosure grids at ~1546+). The form is `ValidatedForm`-based with plain fields alongside controlled ones, so a plain field works with defaultValues:
- ```tsx
- <Boolean
- name="stitchable"
- label={t`Stitchable`}
- description={t`Can be grouped with matching operations from other work orders`}
- />
- ```
-4. The same component serves the job-method editor (routes `x+/items+/methods+/operation.$id.tsx` / `x+/job+/methods+/$jobId.operation.$id.tsx` both submit `methodOperationValidator`-shaped data — verify the job route's validator; if it has its own copy, add the field there too).
-
-### Task 5.3 Schedule-board card: badge + Group/Ungroup menu **[structure VERIFIED]**
-
-Card file: `apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx`.
-
-1. **Type:** the `OperationItem` type (declared in/near `apps/erp/app/routes/x+/schedule+/operations.tsx`, used by the Kanban) gains `stitchable?: boolean`, `operationGroupId?: string | null`, `operationGroupReadableId?: string | null` — sourced from the RPC columns added in Task 1.3. Find where loader rows map into `OperationItem` and thread the three fields.
-2. **Badge:** in the card JSX near the status chip (~299–311), render when grouped:
- ```tsx
- {item.operationGroupId && (
- <Badge variant="secondary">{item.operationGroupReadableId ?? "Stitched"}</Badge>
- )}
- ```
- (Import `Badge` from `@carbon/react`; match how neighboring badges in the file are rendered.)
-3. **Menu:** in the `DropdownMenu` (~181–220), after "Open in MES", add:
- ```tsx
- {item.stitchable && !item.operationGroupId && (
- <DropdownMenuItem onClick={() => setGroupSeed?.(item)}>
- <DropdownMenuIcon icon={<LuCombine />} />
- Group with matching operations
- </DropdownMenuItem>
- )}
- {item.operationGroupId && (
- <DropdownMenuItem onClick={() => onUngroup?.(item.operationGroupId!)} destructive>
- <DropdownMenuIcon icon={<LuUngroup />} />
- Ungroup {item.operationGroupReadableId}
- </DropdownMenuItem>
- )}
- ```
- Thread `setGroupSeed` / `onUngroup` props down from the board the same way `setSelectedGroup` already flows (~198–212 shows the prop pattern). Pick real `react-icons/lu` icons that exist (`LuCombine`, `LuUngroup` — verify; fall back to `LuLayers`/`LuSplit`).
-4. Wrap new user-visible strings in Lingui (`useLingui`/`t`) if the file already does (the existing menu items at 194/211/216 are unwrapped literals — match the file's current convention; do not introduce a mixed style).
-
-### Task 5.4 Group modal + action route
-
-1. **Paths** — `apps/erp/app/utils/path.ts`, next to `scheduleOperationUpdate` (~1719):
- ```typescript
- scheduleOperationsGroup: `${x}/schedule/operations/group`,
- scheduleOperationsStitchable: (operationId: string) =>
- generatePath(`${x}/schedule/operations/stitchable/${operationId}`),
- ```
-2. **Loader route** `apps/erp/app/routes/x+/schedule+/operations.stitchable.$operationId.tsx`:
- - `requirePermissions(request, { view: "production" })`
- - load the seed op (`client.from("jobOperation").select("processId, workCenterId").eq("id", operationId).single()`), then return `getStitchableOperations(client, { processId, workCenterId, companyId })`.
-3. **Action route** `apps/erp/app/routes/x+/schedule+/operations.group.tsx` — action-only, standard pattern (`assertIsPost` → `requirePermissions(request, { update: "production" })` → branch on `formData.get("intent")`):
- - `intent === "group"`: validate `groupJobOperationsValidator` (`jobOperationIds` posted via `zfd.repeatableOfType`-compatible repeated fields) → `groupJobOperations` → error: `return data({}, await flash(request, error(result.error, "Failed to group operations")))`; success: `return data(result.data, await flash(request, success("Operations grouped")))`.
- - `intent === "ungroup"`: validate `ungroupJobOperationsValidator` → `ungroupJobOperations` → same flash pattern.
-4. **Modal** `apps/erp/app/modules/production/ui/Schedule/OperationGroupModal.tsx`: props `{ seed: OperationItem; onClose: () => void }`. `useFetcher().load(path.to.scheduleOperationsStitchable(seed.id))` for candidates; render checkbox rows (job readableId, item description, quantity, due date), seed preselected + locked, cap 10 with counter; submit via a second fetcher POST to `path.to.scheduleOperationsGroup` with `intent=group` + repeated `jobOperationIds`. Use `Modal`/`ModalContent`/... from `@carbon/react` matching a neighboring modal in `ui/Schedule/`.
-5. Wire into `apps/erp/app/routes/x+/schedule+/operations.tsx`: board state `groupSeed`, render the modal when set; `onUngroup` posts `intent=ungroup` via fetcher; `revalidate` after either completes (fetcher completion already revalidates loaders by default — verify board data refreshes; if the board uses client cache, invalidate as neighbors do).
-
-### Task 5.5 Verify + commit
-
-```bash
-pnpm --filter erp typecheck
-pnpm lingui:extract # only if new strings were Lingui-wrapped
-git add -A && git commit -m "feat(erp): stitching UI — manufacturing flag, stitchable op flag, group modal, board badge"
-```
-
----
-
-## Phase 6 — MES UI
-
-### Task 6.1 Board: collapse grouped ops to one card **[structure VERIFIED]**
-
-Files: `apps/mes/app/routes/x+/operations.tsx` (loader ~52–236) + `apps/mes/app/components/Kanban/components/ItemCard.tsx`.
-
-1. RPC already returns the new columns (Task 1.3) via `getActiveJobOperationsByLocation` (`apps/mes/app/services/operations.service.ts:204-213`). Thread `operationGroupId` / `operationGroupReadableId` into the item type used by the board (where `targetQuantity` etc. are mapped, ~line 226+ region).
-2. In the loader's items mapping, **collapse**: group rows by `operationGroupId` (non-null); keep the first row per group as the card, attach `groupMembers: [{ jobReadableId, itemReadableId, targetQuantity }]` and `groupSize`; sum `targetQuantity` for display.
-3. `ItemCard.tsx` (~111–136): when `item.groupSize > 1`, render a `×{groupSize}` badge next to the quantity `Heading` and the group readableId under the item description; card link goes to `path.to.operationGroup(item.operationGroupId)` instead of `path.to.operation(item.id)`.
-
-### Task 6.2 MES paths + service reads
-
-1. `apps/mes/app/utils/path.ts` (pattern at ~105–151):
- ```typescript
- operationGroup: (id: string) => generatePath(`${x}/group/${id}`),
- completeOperationGroup: (id: string) => generatePath(`${x}/group/${id}/complete`),
- ```
-2. `apps/mes/app/services/operations.service.ts` — add (idiom matches `getOpenJobs` at :24-37):
- ```typescript
- export async function getJobOperationGroup(
- client: SupabaseClient<Database>,
- operationGroupId: string,
- companyId: string
- ) {
- const group = await client
- .from("jobOperationGroup")
- .select("*")
- .eq("id", operationGroupId)
- .eq("companyId", companyId)
- .single();
- if (group.error) return group;
-
- const operations = await client
- .from("jobOperation")
- .select("*, job(id, jobId, itemId, quantity, dueDate, status)")
- .eq("operationGroupId", operationGroupId);
-
- return {
- data: { ...group.data, operations: operations.data ?? [] },
- error: operations.error
- };
- }
- ```
-3. `apps/mes/app/services/models.ts` — add (idiom matches `productionEventValidator` at :137-155):
- ```typescript
- export const completeOperationGroupValidator = z.object({
- operationGroupId: z.string().min(1, { message: "Group is required" }),
- producedQuantity: zfd.numeric(z.number().int().min(0))
- });
- ```
-
-### Task 6.3 Group view + complete flow
-
-1. **Route** `apps/mes/app/routes/x+/group.$groupId.tsx`:
- - Loader: `requirePermissions(request, {})` (MES idiom **[VERIFIED]** at `start.$operationId.tsx:20`), `getJobOperationGroup(serviceRole, groupId, companyId)`; also `getProductionEventsForJobOperation` for the **first** member op (timers run against it).
- - Render: member-job table (jobId, item, quantity, due date), aggregate quantity header, Start/Stop buttons linking to the existing `path.to.startOperation(firstMemberOpId)` / `path.to.endOperation(firstMemberOpId)` routes (one `productionEvent` on one member op is the design — cost divides by N at reporting), and a **Complete group** form (`ValidatedForm`, `completeOperationGroupValidator`, one `Number` input, copy: "Will be split evenly across {N} work orders").
-2. **Action route** `apps/mes/app/routes/x+/group.$groupId.complete.tsx`:
- - `assertIsPost` → `requirePermissions` → validate → `serviceRole.functions.invoke("stitch", { body: { type: "complete", operationGroupId, producedQuantity, companyId, userId } })`.
- - On success, replicate `finishJobOperation`'s GL step **[VERIFIED pattern at operations.service.ts:148-189]**: for the returned `memberIds`, select `productionEvent` rows with `endTime not null` and `postedToGL = false`, and `serviceRole.functions.invoke("post-production-event", { body: { productionEventId, userId, companyId } })` for each.
- - Redirect `path.to.operations` with success flash (mirror `end.$operationId.tsx:286-310`).
-3. **Scrap/material on a group (v1 boundary):** per-member scrap and material issue continue through the existing per-operation screens (each member op is real). The group view links each member row to `path.to.operation(memberOpId)` for those flows. **Aggregate one-tap material issue is explicitly deferred** (spec: v2) — do not build it.
-
-### Task 6.4 Verify + commit
-
-```bash
-pnpm --filter mes typecheck
-git add -A && git commit -m "feat(mes): grouped operation card, group view, complete-group flow"
-```
-
----
-
-## Phase 7 — Costing display, verification, docs, PR
-
-### Task 7.1 Estimates-vs-actuals 1/N share **[structure VERIFIED]**
-
-File: `apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx`.
-
-- `getActualTime(operation)` at ~150–185 sums `productionEvent` durations per op. For an operation with `operationGroupId`, divide `setup`, `labor`, `machine` (and `total`) by the group's member count before returning.
-- Member count: the component's data comes from the `$jobId.details.tsx` loader (`getProductionDataByOperations`, ~line 135). Add a lightweight count: select `jobOperation.id,operationGroupId` for the job's ops, and for grouped ones query member counts (`client.from("jobOperation").select("id", { count: "exact", head: true }).eq("operationGroupId", gid)`) — or extend `getProductionDataByOperations` to return it; pick whichever touches less.
-- Label the row: a small badge `1/{n} · {groupReadableId}` next to the operation name, tooltip "Shared operation — time and cost split evenly across {n} work orders".
-
-### Task 7.2 Full verification gate
-
-```bash
-pnpm --filter erp typecheck && pnpm --filter mes typecheck
-pnpm run lint
-pnpm run test
-```
-
-Manual smoke against the user's **running** dev stack (never restart it):
-
-1. Item → Manufacturing tab → enable flag → save → reload → persisted.
-2. Make method operation → Stitchable on → create 2 jobs → both jobs' op copies have `stitchable = true` (check via the job method editor or DB).
-3. Schedule board → card menu → "Group with matching operations" → picker lists the sibling → confirm → both cards collapse/badge `WOS000001`.
-4. MES board shows one card ×2 → group view → Start → End → Complete with 10 → `productionQuantity` rows 5/5 on the two member ops; both jobs' next ops flipped to Ready; group `Completed`.
-5. Fresh group → Ungroup works; after any event → blocked with recovery message.
-6. ERP job details → estimates-vs-actuals shows the 1/N badge and halved actuals.
-
-### Task 7.3 Docs/knowledge sync (same PR)
-
-1. `apps/erp/app/modules/production/AGENTS.md` — data-model table row for `jobOperationGroup`; key-functions entries (`getJobOperationGroup`, `getStitchableOperations`, `groupJobOperations`, `ungroupJobOperations`); domain concept line: "Operation Group — N stitchable jobOperations (same process + work center) grouped into one virtual operation; even time/cost/output split at recording time; jobs never merged; BOM untouched."
-2. `apps/erp/app/modules/items/AGENTS.md` — note `workOrderStitching` (itemReplenishment) and `stitchable` (methodOperation).
-3. Spec changelog entry; **ask the user** before moving the spec to `implemented/`.
-4. Comment on issue #1010 linking the PR.
-
-### Task 7.4 PR
-
-```bash
-git push -u origin feature/work-order-stitching # ask the user before pushing
-gh pr create --title "feat(production): work order stitching — group compatible job operations into a shared run" \
- --body "Tracking spec: .ai/specs/2026-07-02-work-order-stitching.md
-Closes #1010
-
-## What
-- \`jobOperationGroup\` + \`operationGroupId\`/\`stitchable\` columns; \`WOS\` sequence; RPC columns for both boards (jobs never merged; BOM untouched)
-- \`stitch\` edge function: group / ungroup / complete — server-side eligibility gate, even split (largest remainder), multi-row Done (verified: sync_finish_job_operation is a per-row BEFORE trigger, so each job's downstream op releases independently)
-- \`stitchable\` propagates through get-method (itemToJob, quoteLineToJob, itemToQuoteLine; itemToItem via spread)
-- ERP: Manufacturing-tab flag, stitchable routing-step flag, board badge + Group/Ungroup menu, group picker modal
-- MES: collapsed group card, group view, complete-group flow with post-production-event GL posting
-- Estimates-vs-actuals shows 1/N share for grouped operations
-
-## Verification
-- typecheck (erp, mes), lint, tests green
-- Manual smoke: flag → stitchable → group → run → complete 10 → 5/5 split → downstream ops released → ungroup guards
-"
-```
-
----
-
-## Out of scope (do not build)
-
-- Aggregate one-tap material issue on a group (v2; per-member issue works today).
-- Planning-drawer stitch suggestions (v2).
-- Work-center batch capacity (separate future spec).
-- Group-level NCR (per-operation NCR flow unchanged and sufficient).
-
-## Residual risks (all downgraded after grounding)
-
-| Watch for | Status |
-|-----------|--------|
-| Interceptor not firing on multi-row UPDATE | **Retired** — verified FOR EACH ROW trigger |
-| RPC column list | **Retired** — Task 1.3 re-declares from the newest def (`20260531084723`) |
-| Sequence seeding | **Retired** — existing companies in migration; new companies via `seed-company` fn (Task 1.2) |
-| Quote-born jobs losing the flag | **Retired** — `quoteOperation.stitchable` + both quote copy paths (Tasks 1.1, 4.3) |
-| Line-number drift | Anchors + quoted code given everywhere; re-locate by content |
-| `getStitchableOperations` cross-company leak via missing companyId on join | Query filters `companyId` explicitly; RLS backstops |
diff --git a/.ai/research/job-operation-batching.md b/.ai/research/job-operation-batching.md
new file mode 100644
index 0000000000..46c372c425
--- /dev/null
+++ b/.ai/research/job-operation-batching.md
@@ -0,0 +1,137 @@
+# Job Operation Batching Research: Best Practices Survey
+
+> Researched: 2026-07-03 · For spec: `.ai/specs/2026-07-03-job-operation-batching.md`
+> Question: how do best-in-class systems model batch processing of operations across
+> work orders — where does "batchable" live, how are batches planned (material-property
+> filtering), and how do time/cost/output fan back out to member orders?
+
+## Summary
+
+Surveyed SAP (PP, PP/DS, PP-PI, Digital Manufacturing), APS tools (Siemens Opcenter
+APS/Preactor, PlanetTogether, Asprova, frePPLe), and sheet-metal/job-shop systems
+(Fulcrum, SigmaNEST, ProNest, Lantek, Epicor Kinetic/NestLink, JobBOSS², STRUMIS,
+Tekla PowerFab). Three findings are unanimous: (1) **batch capability is a property of
+the resource/machine** — a furnace, oven, tank, or laser table can run several orders'
+operations simultaneously; a brake press cannot — while compatibility criteria come
+from the operation/material; (2) grouping happens at the **operation** level, never by
+merging orders; (3) allocation back to member orders is **proportional** (by quantity
+or area), never even. In sheet metal, "filter by material grade + thickness + machine,
+then group across work orders" is the standard planner workflow in every product.
+The academic literature calls this a **batch processing machine** ("parallel batch
+scheduling", the "Oven Scheduling Problem").
+
+## Competitors Surveyed
+
+- **SAP S/4HANA (PP, PP/DS, PP-PI, Digital Manufacturing)** — enterprise reference: Order Combination, multi-activity resources, campaigns, process lots
+- **Siemens Opcenter APS (Preactor), PlanetTogether, Asprova, frePPLe** — APS tools with first-class batch-resource concepts
+- **Fulcrum, SigmaNEST, ProNest, Lantek, Epicor Kinetic + NestLink, JobBOSS², STRUMIS, Tekla PowerFab** — job-shop/sheet-metal systems where cross-order nesting is the daily workflow
+
+## Key Consensus Patterns
+
+### 1. Batch capability is modeled on the resource/machine, not the part
+
+- **SAP PP/DS**: resource master's category — *multi-activity resource* runs several orders' activities concurrently; *single-activity* is loaded-or-idle. ECC work-center capacity header has "number of individual capacities" + "can be used by several operations".
+- **PlanetTogether**: resource Capacity Type (Single-Tasking vs Multi-Tasking), plus resource-level Operation Batching (Batch Type by Percent/Volume, "Batch Volume" = max units per batch).
+- **Asprova**: resource class "Furnace resource" — "multiple operations start and finish at the same time".
+- **Critical Manufacturing MES**: batch limits sit on the equipment; compatibility on the recipe.
+- **Rationale**: the machine's physics determines simultaneity. Parts/orders only determine *which* operations are compatible within a batch — via attributes (PlanetTogether "Batch Code", Asprova spec values, SAP classification characteristics).
+
+### 2. Grouping is operation-level; orders are never merged
+
+- **SAP Order Combination** (Mill Products/DIMP; S/4HANA Cloud "Combined Production Orders"): combines the *identical operation sequence* of several orders into a combined order; orders diverge again downstream. SAP DM **process lots** group SFCs from different shop orders at the same operation/resource and complete them as one unit.
+- **Fulcrum**: "work is grouped together into a single operation in Job Tracking" — its Grouped Work & Nesting is explicitly operation-level.
+- **Odoo-style order merging** destroys order identity and is the anti-pattern (confirmed in the prior research pass, 2026-07-02).
+
+### 3. Planner workflow: filter by material + thickness + machine, then group
+
+- **Fulcrum**: nest suggestions grouped by material, machine type, schedule; planner filters by material, thickness, due date.
+- **SigmaNEST**: parts auto-sorted "into tasks by material and machine"; work orders sync with material + due date.
+- **Lantek**: sub-jobs keyed "Machine – Material – Thickness"; MES collates parts by material type, thickness, delivery date.
+- **JobBOSS²**: nesting candidates selected by "scheduled date, due date, work center, material thickness".
+- **STRUMIS**: Multi-Contract Nesting matches on section size, grade, thickness.
+- **Rationale**: nesting best practice — same material and thickness must share a sheet; the ERP's job is to make that filter cheap.
+
+### 4. Fan-out to member orders is proportional, never even
+
+- **SAP Order Combination**: confirmation posts on the combined order; "Quantity Distribution" fans yield back **pro-rata to order quantities** (manual override when yield differs); costs settle back quantity-proportionally.
+- **CADTALK (nesting↔ERP)**: scrap/material amortized by "weighted ratio — big parts take a bigger hit"; per-part machine time comes from the nesting software's computed per-part cut time.
+- **Fulcrum**: "proportionately allocates machine time and material costs to individual parts".
+- **SAP DM process lots**: each SFC reports yield/time to its own order pro-rata to SFC quantity.
+- (Exception proving the rule: SAP campaign *setup/clean-out* orders distribute evenly — but that is a sequential-campaign changeover cost, not a shared simultaneous run.)
+
+### 5. Material consumption follows each order's own BOM
+
+- **SigmaNEST/ProNest/NestLink**: after the nest, actual material usage per part is written back and issued to each job/shop order; the cutting operation on each routing is closed. The whole sheet is issued to the run; remnants return to inventory.
+- No product even-splits a raw consumption number across dissimilar jobs.
+
+### 6. Batch building UX: solver-driven in APS, manual pick/drag in MES
+
+- APS engines auto-group compatible operations (Opcenter "operation aggregation"/campaigning, PlanetTogether batch codes, Asprova spec matching); manual control is via the interactive Gantt.
+- The manual batch composer precedent is MES: Critical Manufacturing offers "batch group creation and dissolution", visibility into loaded vs waiting, and running at reduced capacity when too few compatible orders exist. Epicor shops without tooling suffer: "a single operator would have to sign in and out of every single one of the 200 jobs" on one nest.
+
+## Answers to Research Questions
+
+1. **Where does batchability attach?** The resource/process (SAP multi-activity resource, PlanetTogether Capacity Type, Asprova Furnace resource class). Compatibility attributes attach to the operation/material.
+2. **Grouping keys for nesting?** Material (grade) + thickness + machine are the hard keys everywhere; sheet size chosen afterward from inventory; due date is the soft key.
+3. **Industry terminology?** "Nest" (the sheet program), "grouped work" (Fulcrum), "Job Batching"/"nesting batches" (Epicor), "combined order" (SAP), "process lot" (SAP DM), "batch processing machine" (academic). "Batch" is well-supported — but every vendor also carries the batch-as-material-lot collision (SAP Batch Management = lot numbering) and lives with it.
+4. **Time/cost attribution?** Proportional to quantity (SAP quantity distribution, DM process lots) or to area/cut time (nesting integrations). Never even.
+5. **Completion mechanics?** One confirmation on the shared run fans out per member order (SAP combined order confirmation; DM process-lot completion applies to every member SFC; Fulcrum one-click confirm per parts).
+6. **Planner UX precedent for attribute-filtered batch building?** Filter-then-group is universal in sheet metal (§3); a drag/pick composer is an MES-side pattern (Critical Manufacturing), not an APS one — APS auto-groups.
+
+## Competitor-Specific Details
+
+### SAP
+- Order Combination uses a **reference order** for master data/scheduling; goods receipt still posts per original order — member identity is never lost.
+- Terminology collision handled by context: "Batch Management" (= material lots/charges) is unrelated to order batching; docs simply coexist.
+
+### PlanetTogether
+- "Only operations with the same batch code will schedule together in the same batch"; Batch Type by Percent (each op's share = Required Finish Qty / Qty Per Cycle) or by Volume.
+
+### Fulcrum
+- Does not nest natively: exports DXFs to nesting software, re-imports the nest PDF, extracts per-part material usage + machine time, creates and schedules a nesting work order automatically; operators one-click confirm parts and remnants.
+
+### frePPLe / just plan it
+- Documented gap: default resources with size > 1 allow overlap but no compatibility key and no synchronized start/finish — the "cheap" model to avoid copying.
+
+## Recommended Approach for Carbon
+
+1. **`process.batchable` boolean** on the process master (SAP resource-category / Asprova furnace-class pattern): job operations are batchable iff their process is batchable. No per-item, per-method-operation, or per-job flags.
+2. **Operation-level batch entity** over real job operations (SAP Order Combination / DM process-lot pattern): jobs keep their identity; only the shared operation is grouped; downstream operations untouched.
+3. **Filter-then-drag batch planning board** keyed by process + work center + material form/substance/grade/dimension (the SigmaNEST/Lantek/Fulcrum planner workflow), with manual drag-into-batch composition (Critical Manufacturing MES pattern) — Carbon is the planner's manual tool in v1; solver suggestions are a v2.
+4. **Proportional fan-out** of shared run time/cost by member operation quantity (SAP quantity-distribution pattern); material consumption issued per member job's own BOM (nesting write-back pattern); produced quantity entered per member, not split from one number.
+5. **No batch size cap** — no surveyed system caps member count; capacity is a physical property (v2: real capacity/volume modeling à la PlanetTogether Batch Volume).
+6. Keep lot-tracking "batch" and operation-batch terminology explicitly distinguished in docs/UI copy (the SAP coexistence pattern).
+
+## Sources
+
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/5e23dc8fe9be4fd496f8ab556667ea05/09ccd8530439414de10000000a174cb4.html
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/combined-production-orders-in-sap-s-4hana-cloud-public-edition/ba-p/14397369
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/combined-production-order-processing-dimp/ba-p/13266644
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/c7894a248ca14f74aca67f97528e5ad7/6b1bbf53d25ab64ce10000000a174cb4.html
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/34de0103497c4b80a7c7fbf6952ff971/1cda81ceef6c4e7f8f2b6f41af400ac0.html
+- https://help.sap.com/saphelp_SCM700_ehp02/helpdata/en/76/35c95360267614e10000000a174cb4/content.htm
+- https://help.sap.com/docs/SAP_ERP/698b19fa88b846359bc611f11184c810/6f80bf53f106b44ce10000000a174cb4.html
+- https://help.sap.com/saphelp_scm700_ehp02/helpdata/en/e6/47c95360267614e10000000a174cb4/content.htm
+- https://community.sap.com/t5/product-lifecycle-management-blog-posts-by-sap/configure-and-use-process-lots-in-sap-digital-manufacturing/ba-p/13553892
+- https://blogs.sw.siemens.com/opcenter/available-now-opcenter-aps-18-3/
+- https://www.siemens.com/en-us/products/opcenter/advanced-planning-scheduling-aps/advanced-scheduling-software/
+- https://lean-scheduling.com/watch-oven-furnace-scheduling-with-opcenter-aps-preactor/
+- https://www.planettogether.com/en/knowledge/batching
+- https://www.planettogether.com/en/knowledge/resource-options
+- https://asprova.net/furnace-resource/
+- https://frepple.com/docs/current/model-reference/resources.php
+- https://www.criticalmanufacturing.com/blog/how-mes-supports-advanced-scenarios-in-semiconductor-batching/
+- https://fulcrumpro.com/manufacturing-software/grouped-work-and-nesting
+- https://fulcrumpro.com/product-update/nesting-work-orders---looking-for-beta-users
+- https://sigmanest.com/nesting-software/work-order-basics
+- https://mie-solutions.com/sigmanest-mie-trak-software-integration/
+- https://www.hypertherm.com/products/software/pronest-optional-modules/
+- https://www.hypertherm.com/resources/more-resources/blogs/pronest-and-tekla-powerfab-integration/
+- https://cadtalk.com/the-value-of-nesting-integration-with-erp-system/
+- https://www.epicor.com/en-us/products/enterprise-resource-planning-erp/kinetic/nestlink/
+- https://www.epiusers.help/t/job-batching-nesting-sheet-parts-for-cnc/124778
+- https://customers.jobboss.com/nesting-integration
+- https://strumis.com/steel-fabrication-nesting-software-strumis
+- https://fabricatingandmetalworking.com/lantek-nesting-by-attribute-v45-upgrade/
+- https://link.springer.com/article/10.1007/s10601-023-09347-2
+- https://arxiv.org/pdf/2410.11981
diff --git a/.ai/specs/2026-07-02-work-order-stitching.md b/.ai/specs/2026-07-02-work-order-stitching.md
deleted file mode 100644
index 70cb8bd76d..0000000000
--- a/.ai/specs/2026-07-02-work-order-stitching.md
+++ /dev/null
@@ -1,308 +0,0 @@
-# Work Order Stitching
-
-> Status: in-progress
-> Author: Claude (with Sid)
-> Date: 2026-07-02
-> Research: `.ai/scratch/research/work-order-stitching.md`
-> Requirement: REQ-FUN-PRODUCTION-005 (Must, Daily)
-> Tracking issue: https://github.com/crbnos/carbon/issues/1010
-
-## TLDR
-
-Add "Work Order Stitching" to the production module: when several jobs need
-the same operation (same process, same work center — e.g. a furnace cycle or
-bath treatment), a planner can group those specific **job operations** into
-one virtual operation. The virtual operation completes all of its member
-operations together, and its time/cost splits evenly across them. Material
-consumption and produced quantity are logged once for the group and split
-evenly to each member job at posting time — the underlying bill of materials
-is never touched. **Jobs themselves are never merged or combined** — each
-member job keeps its own identity, status, cost, and downstream operations;
-only the one shared operation is shared. A per-item flag on the Manufacturing
-tab plus a per-operation "stitchable" marker on the routing step gate which
-operations are eligible to group.
-
-## Problem Statement
-
-Shops doing surface/heat treatment run the same preparation step (mix a bath,
-heat a furnace, prepare a coating) once per job even when several jobs need
-the identical step at the same time. Example from the requirement: two
-treatments on two layers, same raw materials, same semi-finished output —
-today Carbon forces 2 prep tasks, 2 material consumptions, 2 outputs, even
-though the furnace only ran once. Wanted: 1 shared prep task, 1 aggregated
-consumption, 1 aggregated output, while the 2 treatment/application steps
-that follow stay separate and traceable to their own jobs.
-
-Carbon has no concept of one operation belonging to more than one job today:
-`jobOperation.jobId` is a required, cascading foreign key, and every
-schedule/MES/costing query assumes an operation belongs to exactly one job.
-
-## Proposed Solution
-
-**A grouped operation is the unit being combined — not the job.** N jobs stay
-N separate jobs throughout. What changes is that one specific operation on
-each of those jobs (the shared prep step) gets pulled into a
-`jobOperationGroup`: a lightweight join over N real `jobOperation` rows, one
-per member job. There's no "lead job" and no deactivated duplicates — every
-member operation stays a first-class row on its own job.
-
-```
-jobOperationGroup (readable: WOS000001)
- process: Heat Treat · work center: Furnace 2
- │
- ├── Job A · jobOperation "Heat Treat" ──┐
- ├── Job B · jobOperation "Heat Treat" ──┤ members — same process + work
- └── Job C · jobOperation "Heat Treat" ──┘ center, grouped, not merged
-
-Job A's next op (Coat) ─┐ each job's OWN downstream operations and
-Job B's next op (Coat) ─┤ dependency chain are untouched — they still
-Job C's next op (Coat) ─┘ release on their own job's schedule, same as today
-```
-
-Key behaviors:
-
-1. **Group** (planner action): select N job operations that share a process +
- work center, none started, none already grouped → creates the
- `jobOperationGroup`, tags each member op with `operationGroupId`. Nothing
- else about the member jobs changes.
-2. **Run** (MES): the group shows as one card. The operator starts one
- Setup/Labor/Machine timer (one `productionEvent`) and, at completion, logs
- **one** produced-quantity number and **one** consumed-material number for
- the whole group. The system splits both **evenly** across the N member
- operations (largest-remainder rounding for whole units) and posts one
- `productionQuantity` row + one `issue` call per member operation. The
- underlying `jobMaterial`/`jobMakeMethod` (the BOM) is never read or
- rewritten — this is purely a runtime posting split, not a planning change.
-3. **Complete**: one action transitions all N member operations to `Done` in
- a single transaction. Each operation already has its own same-job
- `jobOperationDependency` chain to its own next step — Postgres fires the
- existing `finish_job_operation` row trigger once per updated row, so each
- job's downstream operation releases on its own, independently, exactly as
- it does for an ungrouped job today. **No cross-job dependency edge is
- needed anywhere in this design.**
-4. **Cost**: the shared `productionEvent`'s time × rate divides evenly by the
- member count at reporting time (query-time computation, not a stored
- split) — a 2-unit job and a 20-unit job through the same furnace absorb
- equal setup cost. This is a deliberate trade-off, not an oversight (see
- Design Decisions).
-5. **Ungroup** (before the shared operation starts): clear `operationGroupId`
- on all members, delete the group row. No state to restore beyond that —
- there was never anything deactivated or rewritten.
-
-### Eligibility gate (group validator)
-
-- Item opted in: `itemReplenishment.workOrderStitching = true` for every
- member job's item.
-- Operation marked shareable: `jobOperation.stitchable = true` (propagated
- from `methodOperation.stitchable` via `get-method`).
-- Same process, same work center across all candidate operations.
-- Not started: candidate op status `Todo`/`Ready`/`Waiting`, no
- `productionEvent` recorded yet.
-- Not already grouped: `jobOperation.operationGroupId IS NULL`.
-- Group size ≤ 10 members (constant in the `stitch` edge function).
-
-Member jobs do **not** need to share an item (decided — see Open Questions):
-because this design never touches the BOM, two different items whose routing
-hits the same furnace step can share a group. The double opt-in (item flag +
-operation flag) means every member's item owner deliberately enabled this.
-
-### Design Decisions
-
-| Decision | Choice | Rationale |
-|----------|--------|-----------|
-| What gets combined | **Operations, not jobs.** Jobs stay fully separate the whole time | Matches the actual ask: "application tasks stay separate, linked to the main order." Merging jobs (Odoo-style) was rejected earlier for destroying job identity — this avoids that question entirely, since jobs are never touched |
-| Group entity | `jobOperationGroup`, a plain join over real `jobOperation` rows via `operationGroupId` — no lead/follower asymmetry, no deactivated duplicates | Simpler than an execution-overlay-with-deactivation model; every member op stays a normal, queryable row. Removes an entire class of "is this op real or a shadow" bugs |
-| Completion mechanism | One transaction sets all member ops to `Done`; rely on Postgres firing `finish_job_operation` once per affected row | Row-level AFTER UPDATE triggers fire per row regardless of single- vs multi-row UPDATE — standard Postgres behavior, not new plumbing. Each job's own dependency chain releases independently, unmodified |
-| Cross-job dependency edges | **Not used.** Rejected entirely | The earlier design needed them to gate each member's next op on the shared op; multi-row completion makes them unnecessary. This was the single highest risk in the prior design — removing it removes the risk |
-| Material/output aggregation | Split evenly across members **at posting time only**; `jobMaterial`/`jobMakeMethod` never read or written | Confirmed with Sid: "without modifying the underlying BoM." `productionQuantity` has no `jobId` — it's attributed via `jobOperationId` → parent job — so posting one row per member operation gives correct per-job ledger/costing for free, no schema change to `issue` |
-| Cost split | **Even**, not proportional to job quantity | Confirmed with Sid: "splits the time/cost evenly." Simpler than proportional-by-quantity; the trade-off (small orders subsidize large orders' setup) is explicit, not hidden |
-| Setup event sharing | One `productionEvent`; member `productionQuantity` rows reference it via existing `setupProductionEventId` (nullable, no unique constraint — already legal) | Zero schema change for attribution |
-| Eligibility scope | Same process + work center + stitchable flag; **not** same item | Decided (Open Questions): BOM is never touched, so same-item is not structurally required; double opt-in prevents accidental cross-item groups; matches physical furnace reality |
-| Scrap on a grouped op | Even split, same posting path as production quantity; NCR workflow unchanged | Decided (Open Questions): scrap is just a `productionQuantity` type; load-level failure (the common case per MRB/Nadcap practice) splits evenly by construction; per-member NCR remains possible since member ops are real rows |
-| Flags | Item-level `itemReplenishment.workOrderStitching` (UX opt-in, matches requirement's "Manufacturing tab" framing) + operation-level `methodOperation.stitchable` (identifies which routing step is shareable, auto-propagates to `jobOperation` via `get-method`) | Two flags because they answer different questions: "does this item's routing ever get combined" vs. "which specific step" |
-| Multi-tenancy | `jobOperationGroup` composite PK `("id","companyId")` | Carbon convention |
-| RLS model | Permission-based: `production_view/create/update/delete` | Matches `job`/`jobOperation` policies |
-| Service shape | `(client, ...)` → `{ data, error }`; multi-row mutation via a `stitch` edge function (Kysely transaction) | `.ai/rules/conventions-services.md` |
-| Backward compatibility | All columns additive/nullable; inert until both flags are set | No FROZEN surface touched |
-
-## Data Model Changes
-
-```sql
--- 1. Master-data flags
-ALTER TABLE "itemReplenishment"
- ADD COLUMN "workOrderStitching" BOOLEAN NOT NULL DEFAULT false; -- Manufacturing tab gate
-
-ALTER TABLE "methodOperation" ADD COLUMN "stitchable" BOOLEAN NOT NULL DEFAULT false;
-ALTER TABLE "jobOperation" ADD COLUMN "stitchable" BOOLEAN NOT NULL DEFAULT false; -- copied via get-method
-
--- 2. Operation group ("virtual operation")
-CREATE TYPE "jobOperationGroupStatus" AS ENUM ('Active', 'Completed', 'Cancelled');
-
-CREATE TABLE "jobOperationGroup" (
- "id" TEXT NOT NULL DEFAULT id('wos'),
- "readableId" TEXT NOT NULL, -- e.g. WOS000001 (getNextSequence)
- "companyId" TEXT NOT NULL,
- "processId" TEXT NOT NULL, -- shared process; every member matches this
- "workCenterId" TEXT, -- shared work center; every member matches this
- "status" "jobOperationGroupStatus" NOT NULL DEFAULT 'Active',
- "customFields" JSONB,
- "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,
- CONSTRAINT "jobOperationGroup_pkey" PRIMARY KEY ("id", "companyId"),
- CONSTRAINT "jobOperationGroup_companyId_fkey" FOREIGN KEY ("companyId")
- REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "jobOperationGroup_processId_fkey" FOREIGN KEY ("processId", "companyId")
- REFERENCES "process"("id", "companyId"),
- CONSTRAINT "jobOperationGroup_readableId_unique" UNIQUE ("readableId", "companyId")
-);
-ALTER TABLE "jobOperationGroup" ENABLE ROW LEVEL SECURITY;
--- SELECT: employee role; INSERT/UPDATE/DELETE: production_create/update/delete
--- (same shape as job policies in 20240915192542)
-
--- 3. Membership — one column on jobOperation, no join table needed
-ALTER TABLE "jobOperation" ADD COLUMN "operationGroupId" TEXT; -- FK → jobOperationGroup(id), nullable
-CREATE INDEX "jobOperation_operationGroupId_idx" ON "jobOperation" ("operationGroupId")
- WHERE "operationGroupId" IS NOT NULL;
-```
-
-Note what's **absent** compared to the earlier design: no `job.stitchGroupId`
-(membership is derived by joining through `jobOperation`, not denormalized
-onto `job`), no `stitchRole` enum, no cross-job rows in
-`jobOperationDependency`. Smaller surface area.
-
-Also required (behavioral, not schema):
-
-- Views/RPCs that render the schedule board / MES operation lists must
- collapse operations sharing an `operationGroupId` into one card.
-- After migration: `pnpm run generate:types` before typecheck.
-
-## API / Service Changes
-
-### New edge function: `stitch` (`packages/database/supabase/functions/stitch/`)
-
-Follows `.ai/rules/workflow-edge-function.md`. Discriminated union payload:
-
-- `{ type: "group", jobOperationIds: string[], companyId, userId }` —
- validates the eligibility gate server-side (including the ≤10-member cap),
- creates the group, sets `operationGroupId` on each op, returns
- `{ id, readableId }`.
-- `{ type: "ungroup", operationGroupId, companyId, userId }` — guard: no
- `productionEvent` on any member op (all-or-nothing; error names the
- recovery route: complete the group); clears `operationGroupId` on all
- members, deletes the group row.
-- `{ type: "complete", operationGroupId, producedQuantity, consumedMaterial[], companyId, userId }`
- — splits `producedQuantity` and each material line evenly across member
- operations (largest-remainder rounding), inserts one `productionQuantity`
- row and issues one `issue` call per member operation (all referencing the
- one `productionEvent`), then sets every member operation's status to
- `Done` in the same transaction. Scrap logged against the group takes the
- same even split.
-
-### `production.service.ts` additions
-
-```typescript
-getJobOperationGroup(client, id, companyId) // group + member operations + jobs
-getStitchableOperations(client, processId, companyId)
- // open, ungrouped, flag-on operations matching a process (drives the picker)
-groupJobOperations(client, payload) // invoke("stitch", { body: { type: "group", ... } })
-ungroupJobOperations(client, payload) // invoke("stitch", { body: { type: "ungroup", ... } })
-completeOperationGroup(client, payload) // invoke("stitch", { body: { type: "complete", ... } })
-```
-
-`production.models.ts`: `groupJobOperationsValidator`, `ungroupValidator`,
-`completeOperationGroupValidator`, `jobOperationGroupStatus` const.
-
-### `items` module
-
-`itemManufacturingValidator` gains `workOrderStitching: zfd.checkbox()`
-(items.models.ts:514); `upsertItemManufacturing` passes it through.
-
-### `methodOperation` / `BillOfProcess.tsx`
-
-`methodOperationValidator` gains `stitchable: zfd.checkbox()`; one `Boolean`
-field added to the operation form. Selecting the column in `get-method`'s
-copy query is the only change needed for it to propagate to `jobOperation` —
-no explicit copy logic.
-
-## UI Changes
-
-| Surface | Change |
-|---------|--------|
-| Item → Manufacturing tab (`ItemManufacturingForm.tsx`) | "Work Order Stitching" checkbox, mirrors `requiresConfiguration` pattern |
-| Method operation form (`BillOfProcess.tsx`) | "Stitchable" checkbox on the routing step |
-| Jobs list / schedule board | Operations eligible to group (same process/work center, flags on, unstarted) surface a **Group** action; confirming opens a picker across matching open jobs (grouped by process + work center, cross-item allowed) |
-| Schedule board / MES operation list | Grouped operations render as **one card** with a member-job list, not N cards |
-| MES operation view for a group | Single "produced quantity" + "material consumed" input, with copy explaining it splits evenly across N jobs; a **Complete group** action replaces per-operation Finish |
-| Job detail | Badge on the shared operation showing group membership + a link to ungroup (guarded) |
-
-## Acceptance Criteria
-
-- [ ] Setting both flags (item + operation) makes an operation eligible to appear in the group picker; missing either flag hides it.
-- [ ] Grouping 3 unstarted operations (same process + work center, different jobs — including jobs for different items) creates a `jobOperationGroup`, tags all 3 ops with the same `operationGroupId`, and the schedule board/MES show one card for all three.
-- [ ] Grouping operations that differ in process or work center, are already started, already grouped, or would exceed 10 members is rejected server-side with a specific error per rule.
-- [ ] Logging 10 produced units + 9kg material on a 3-member group splits as 4/3/3 units (largest remainder) and 3/3/3 kg, one `productionQuantity` row and one `issue` call per member operation, all referencing the same `productionEvent`; `jobMaterial` rows are unchanged before and after.
-- [ ] Scrap logged on the group splits evenly across member operations via the same path; each member job's `quantityScrapped` reflects its share.
-- [ ] "Complete group" transitions all 3 member operations to `Done` in one action; each member job's own next operation flips from `Waiting`/blocked to `Ready` independently (no cross-job coupling required for this to work).
-- [ ] Estimates-vs-actuals / job costing for each member job shows 1/3 of the shared operation's time and cost, not the full amount.
-- [ ] Ungrouping before any production event clears `operationGroupId` on all members and deletes the group; ungrouping after a production event is blocked with an error naming the recovery route (complete the group).
-- [ ] Jobs/operations that were never grouped behave byte-for-byte as before; `pnpm run typecheck` and `pnpm run test` pass.
-
-## Risks
-
-| Risk | Severity | Mitigation |
-|------|----------|------------|
-| Even (not proportional) cost split silently misleads a planner comparing job margins | Med | Costing/estimates UI explicitly labels grouped-operation cost as "1/N of shared operation," not folded silently into the job's own numbers |
-| Cross-item grouping surprises someone expecting same-item scope (widening from the literal requirement text) | Med | Decided deliberately (see Open Questions) and documented; double opt-in flags prevent accidental use; picker UI makes the mixed-item membership visible before confirming |
-| Rounding on indivisible units (e.g. 10 units / 3 jobs) | Low | Largest-remainder allocation; acceptance test with non-divisible splits |
-| Multi-row `Done` transition doesn't fire per-row triggers as expected in some edge case (e.g. a trigger written assuming single-row UPDATE) | Low | Verify `finish_job_operation` against a real multi-row UPDATE in a migration test before relying on it |
-| Group completion partially fails mid-transaction (some member posts succeed, others don't) | Low | Whole `complete` action runs in one Kysely transaction — standard rollback semantics, no partial state possible |
-
-## Open Questions
-
-> All resolved 2026-07-02. Gate cleared — spec is ready for `/plan` / `/feature`.
-
-- [x] **Which operations are "the prep"?** — **Answer:** explicit
- `methodOperation.stitchable` flag, propagates to `jobOperation` via
- `get-method`. Confirmed in conversation — load-bearing for the eligibility
- gate itself, not just a UI hint.
-- [x] **Output/material allocation rule.** — **Answer:** even split across
- member operations, computed and posted at execution time; `jobMaterial`/
- `jobMakeMethod` never touched. Confirmed with Sid directly.
-- [x] **Scrap ownership on a grouped operation.** — **Answer: even split,
- identical mechanism to production quantity; NCR workflow unchanged.** Scrap
- is just a `productionQuantity` type, so the even split reuses the exact
- same posting path with zero extra machinery. Domain practice supports the
- default: a bad furnace cycle condemns the whole load (MRB/Nadcap treat the
- lot as one), so process failure — the common case — splits evenly by
- construction. For the rarer part-specific defect, member ops are all real
- rows, so quality can raise an NCR against the specific member operation
- exactly as today; no NCR schema or workflow change in v1.
-- [x] **Same-item restriction.** — **Answer: ship the wider rule — same
- process + same work center, any items.** The double opt-in (item-level
- `workOrderStitching` AND operation-level `stitchable`) means every member's
- item owner deliberately enabled grouping; accidental cross-item groups
- can't happen. Wider matches physical reality (a furnace doesn't care whose
- parts are loaded) and the requirement's intent (eliminate redundant prep),
- even though its example assumed same-item.
-- [x] **Ungroup boundary.** — **Answer: all-or-nothing; blocked after any
- production event on any member op.** Error names the recovery route:
- complete the group, after which member jobs proceed independently. Partial
- member removal is v2 if ever requested.
-- [x] **Planning integration scope.** — **Answer: manual only in v1** —
- grouping happens from the jobs list / schedule board. Purchasing's silent
- supplier+period auto-grouping is a UX precedent to avoid; an explicit
- suggestion in `ProductionPlanningOrderDrawer` is the natural v2 follow-up.
-- [x] **Group size ceiling.** — **Answer: hard cap of 10 members, a constant
- in the `stitch` edge function validator.** Purely a blast-radius bound — no
- capacity semantics implied. Not a company setting: no demand for tunability
- yet; promoting a constant to config later is a one-line change. Real
- furnace/bath capacity modeling is a separate future spec.
-
-## Changelog
-
-- 2026-07-02: Created. Research grounded in 9 codebase-exploration passes + adversarially verified ERP prior art (SAP Combined Production Orders, Odoo merge/split, Dynamics 365 TCA); notes at `.ai/scratch/research/work-order-stitching.md`.
-- 2026-07-02: Open questions upgraded from proposals to researched recommended paths (3 further codebase passes: scrap/quality attribution, planning UI + methodOperation config, standard-factor batch semantics; plus manufacturing-practice research on load-level nonconformance and batch-machine scheduling).
-- 2026-07-02: Redesigned from an execution-overlay-on-jobs model to an **operation-group model** after clarifying with Sid that jobs are never combined — only specific job operations are. Dropped: lead job / deactivated shadow operations, cross-job `jobOperationDependency` edges, proportional-by-quantity cost/output split. Adopted: a plain `jobOperationGroup` join over real operations, multi-row completion relying on existing per-row triggers, and an even split of time/cost/material/output posted at execution time without ever touching the BOM.
-- 2026-07-02: All remaining open questions resolved (scrap = even split with unchanged NCR workflow; eligibility = cross-item allowed, same process + work center; ungroup = all-or-nothing before first production event; planning = manual-only v1; group cap = constant 10). Status → in-progress; spec ready for `/plan` or `/feature`.
diff --git a/.ai/specs/2026-07-03-job-operation-batching.md b/.ai/specs/2026-07-03-job-operation-batching.md
new file mode 100644
index 0000000000..76a7a86ba6
--- /dev/null
+++ b/.ai/specs/2026-07-03-job-operation-batching.md
@@ -0,0 +1,385 @@
+# Job Operation Batching
+
+> Status: in-progress
+> Author: Claude (with Brad)
+> Date: 2026-07-03
+> Research: `.ai/research/job-operation-batching.md`
+> Requirement: REQ-FUN-PRODUCTION-005 (Must, Daily)
+> Tracking issue: https://github.com/crbnos/carbon/issues/1010 (suggest retitling to "Job Operation Batching")
+> Supersedes: the never-merged prior design (commit `d6c7ad3de`, branch-only)
+
+## TLDR
+
+Some processes can run several jobs at once — a laser table nests parts from many
+work orders on one sheet, a furnace treats many jobs in one cycle, a paint booth
+coats whatever fits. Other processes can't: a brake press runs exactly one job at
+a time. **Batchability is a property of the process**, so this spec adds a single
+`batchable` flag to the `process` master record. Every job operation whose process
+is batchable is thereby batchable — no per-item flags, no per-routing-step markers.
+
+A planner composes an **operation batch** (`jobOperationBatch`) on a new
+drag-and-drop **batch planning board**: pick a batchable process, filter the
+unstarted job operations by the material properties of their BOM lines ("show me
+everything on the laser that uses 1/4-inch A36 steel sheet"), and drag them into a
+batch. The batch runs as one card in MES; completing it records per-member produced
+quantities, splits the shared run time **proportionally to each member operation's
+quantity**, issues material per each job's own BOM, and finishes every member
+operation in one action. **Jobs are never merged** — each keeps its identity, cost,
+and downstream operations; the bill of materials is never modified. There is no
+batch size limit.
+
+Terminology note: an operation batch is unrelated to **lot/batch tracking**
+(`batchNumber`, `trackedEntity`, `requiresBatchTracking`). Same word, different
+concept — the same collision SAP lives with ("Batch Management" = material lots vs
+combined orders). UI copy and docs must keep the two distinct.
+
+## Problem Statement
+
+When several jobs need time on the same batch-capable machine, Carbon forces one
+run per job: N setups on the laser table for N jobs that could have shared one
+nest; N furnace cycles where the furnace only needed to run once. The operator
+signs in and out of every job, the machine time is over-reported N-fold or
+misattributed, and the planner has no way to see which queued operations *could*
+share a run — finding "everything on the laser in 1/4-inch A36" means opening
+every job.
+
+Carbon has no concept of one run serving many jobs: `jobOperation.jobId` is a
+required FK, and every schedule/MES/costing query assumes an operation runs alone
+on its work center.
+
+The prior design (commit `d6c7ad3de`) modeled eligibility wrong: it required a
+per-item opt-in (`itemReplenishment` flag) plus a per-routing-step marker. That puts the flag on the part, but the part doesn't determine
+batchability — the machine does. A laser-cut bracket is batchable at the laser and
+not at the brake press. Industry practice agrees: SAP multi-activity resources,
+Asprova's furnace resource class, and PlanetTogether's resource-level batching all
+put the capability on the resource (see research §1). This spec replaces that
+design entirely; the double opt-in, the propagated flags, and the even splits are
+gone.
+
+## Proposed Solution
+
+**The process is what's batchable; the batch is a group of real job operations.**
+N jobs stay N separate jobs. One specific operation from each job — all on the
+same batchable process — is tagged into a `jobOperationBatch`: a lightweight join
+over N real `jobOperation` rows. No lead job, no shadow rows; every member
+operation remains a first-class row on its own job.
+
+```
+process "Laser Cutting" (batchable = true)
+ │
+jobOperationBatch BAT000001 · work center: Laser 2
+ │
+ ├── Job A · op "Laser Cut" (qty 5) ──┐ members — same process, grouped
+ ├── Job B · op "Laser Cut" (qty 20) ──┤ by the planner from the batch
+ └── Job C · op "Laser Cut" (qty 10) ──┘ planning board, never merged
+
+Job A's next op (Deburr, qty 5) ─┐ each job's OWN downstream operations and
+Job B's next op (Brake, qty 20) ─┤ dependency chain are untouched — they
+Job C's next op (Weld, qty 10) ─┘ release on their own job, same as today
+
+process "Brake Press" (batchable = false) → its operations never batch
+```
+
+### Key behaviors
+
+1. **Flag** (master data): a checkbox on the process record — "Batchable —
+ multiple jobs can run on this process at the same time". Laser cutting,
+ heat treat, plating, painting: on. Brake press, manual mill: off.
+2. **Plan** (batch planning board): pick a batchable process at a location; the
+ board lists every unstarted, unbatched job operation for that process with the
+ material properties of its BOM lines (form, substance, grade, dimension,
+ finish) as filterable facets and visible chips. The planner filters — e.g.
+ substance Steel, grade A36, dimension 1/4" — and drags operations into an
+ existing batch or a "new batch" drop zone. Dragging into a batch that has a
+ work center assigns that work center to the member operation (same effect as
+ dragging a card between schedule-board columns today). Operations can be
+ dragged out again, and batches dissolved, any time before the run starts.
+3. **Run** (MES): the batch renders as one card (member count + summed quantity).
+ The operator starts one set of Setup/Labor/Machine timers for the whole batch —
+ `productionEvent` rows tagged with the batch id.
+4. **Complete** (one action): a member table pre-filled with each operation's
+ quantity; the operator confirms per-member produced quantity (and optional
+ per-member scrap). The system then, in order: closes open batch timers; slices
+ each recorded `productionEvent` into per-member events with durations
+ **proportional to member operation quantity** (largest-remainder on seconds,
+ contiguous sub-windows of the recorded span); inserts per-member
+ `productionQuantity` rows; issues material for each member via the existing
+ `issue` edge function — so consumption follows **each job's own BOM**, scaled
+ by its own produced quantity; sets every member operation `Done` in one
+ multi-row update (the existing per-row `sync_finish_job_operation` interceptor
+ releases each job's downstream operation independently — no cross-job
+ dependency edges); marks the batch `Completed`. GL posting then runs per
+ member event via the existing `post-production-event` flow.
+5. **Cost**: because the split is materialized as per-member production events,
+ every existing surface — job costing, estimates-vs-actuals, WIP/GL — shows each
+ job its proportional share with **zero special-casing**. A 20-part job absorbs
+ 4× the shared run time of a 5-part job.
+
+### Eligibility gate (enforced server-side on create/add)
+
+- The operation's process has `batchable = true`.
+- All members share one process (`jobOperation.processId` equal across members —
+ it is NOT NULL, so this is a plain equality check; nothing propagates).
+- Candidate operation is unstarted: status in `Todo`/`Ready`/`Waiting` and no
+ `productionEvent` recorded.
+- Candidate not already in a batch (`jobOperationBatchId IS NULL`).
+- **No size cap** (min 1 member so a batch always has content; no maximum).
+- No item/work-center/material restrictions: material filters are a planning aid,
+ not a constraint — the planner owns nesting compatibility (matches SigmaNEST/
+ Lantek, where material match is workflow, not schema).
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Where batchability lives | **`process.batchable` boolean** — job operations derive it via their NOT NULL `processId`; no flags on item, methodOperation, quoteOperation, or jobOperation, and no get-method propagation | The machine determines simultaneity (laser vs brake press). Matches SAP multi-activity resources / Asprova furnace class (research §1). Supersedes the requirement's literal "Manufacturing tab" framing — confirmed by Brad 2026-07-03. Precedent: `process.completeAllOnScan` boolean flag |
+| What gets combined | **Operations, not jobs** — `jobOperationBatch` is a plain join over real `jobOperation` rows via a nullable FK | SAP Order Combination / DM process-lot pattern; jobs keep identity, status, cost, downstream chain |
+| Entity naming | Table `jobOperationBatch`, FK `jobOperation.jobOperationBatchId`, readable prefix `BAT`, UI noun "batch" | Convention-true FK naming (`{table}Id`). Explicitly documented as distinct from lot-tracking "batch" (`batchNumber`, `requiresBatchTracking`, the `issue` fn's `jobOperationBatchComplete` case = *lot*-tracked completion) |
+| Batch size | **No cap** (min 1) | Brad 2026-07-03: no size constraints. No surveyed system caps member count; capacity is physical, and modeling it (PlanetTogether Batch Volume) is a separate future spec |
+| Time/cost split | **Proportional to member operation quantity** (weight = `operationQuantity` / Σ; equal weights only as a Σ=0 fallback), materialized at completion by slicing each batch `productionEvent` into per-member events (largest-remainder rounding on seconds) | Brad 2026-07-03: proportional, not even. SAP quantity-distribution / CADTALK weighted-ratio pattern. Materializing per-member events makes GL posting, job costing, and estimates-vs-actuals correct with no downstream changes — the prior design's single-event approach would have posted 100% of WIP to one job while displaying 1/N |
+| Weight basis | Planned `operationQuantity`, not produced actuals, not part area | Defined before and during the run; zero-produced members still absorb their share (scrapped parts consumed table time). Area/cut-time weights arrive with nesting import (v2) |
+| Produced quantity | **Entered per member** (pre-filled with operation quantity), optional per-member scrap; NOT one total split across members | Each job's parts are distinct — a nest cuts 5 of A and 20 of B; splitting one number across heterogeneous parts is meaningless. One screen, one action still satisfies "aggregated output" (Fulcrum confirm-parts pattern) |
+| Material consumption | Per member via the existing `issue` edge fn (`type: "jobOperation"`, member's produced quantity) at batch completion — each job consumes per **its own BOM**; `jobMaterial`/`jobMakeMethod` never rewritten | Nesting write-back pattern (research §5); reuses the exact machinery MES per-op completion uses today; cross-item batches make "split one consumed number" ill-defined |
+| Membership lifecycle | `create` (≥1 op), `add`, `remove` while no production event exists; `dissolve` deletes the batch and clears members (blocked after any event — error names the recovery: complete the batch); removing the last member dissolves | Drag-and-drop planning implies incremental add/remove; all pre-start operations are pure FK writes with nothing to unwind |
+| Work center | Batch carries nullable `workCenterId`; assigning it (at create or later) writes it to all member operations; adding an op to a batch with a work center sets the op's `workCenterId` | Physically true — batching puts the job on that machine. Same write the schedule board's drag already performs. Members need NOT pre-match |
+| Completion mechanism | One transaction: slice events → insert quantities → multi-row `Done` → batch `Completed`; caller then issues material + posts GL per event | `trg_event_sync_jobOperation` is BEFORE/FOR EACH ROW (re-verified 2026-07-03), so each member's downstream op releases independently; no cross-job dependency edges anywhere |
+| Planning integration | Manual board only in v1; no MRP/scheduler auto-suggestions | APS auto-grouping is solver territory (v2); manual composer matches the MES precedent (Critical Manufacturing) |
+| Multi-tenancy (heuristic 1) | `jobOperationBatch` composite PK `("id","companyId")`, `id` TEXT default `id()`, `companyId` on every query | Carbon convention |
+| Service shape (heuristic 2) | `(client, ...) → {data, error}` wrappers in `production.service.ts`; multi-row mutations via a `batch-operations` edge function (Kysely transaction) | `.ai/rules/conventions-services.md`; one service/models file per module |
+| RLS (heuristic 3) | Policies named `SELECT`/`INSERT`/`UPDATE`/`DELETE`: view = employee role, mutations = `production_create/update/delete`, `::text[]` casts per current idiom | Matches `job`/`jobOperation`; copy the newest migration's idiom |
+| Permission scoping (heuristic 4) | Routes + edge fn: `view: "production"` for reads, `update: "production"` for batch mutations | Batching mutates job operations — production scope |
+| Form pattern (heuristic 5) | Process form: `Boolean` field in existing `ValidatedForm`; batch completion: `ValidatedForm` + zod validator in MES | House pattern; clone `completeAllOnScan` |
+| Module layout (heuristic 6) | Validators in `production.models.ts`, services in `production.service.ts`; process flag in `resources.models.ts`/`resources.service.ts`; no new files beyond UI components/routes | One service/models per module |
+| Backward compatibility (heuristic 7) | All columns additive/nullable (or defaulted); inert until a process is flagged batchable; `get_active_job_operations_by_location` re-declared additively (both boards read it); `processes` view recreated from newest definition | No FROZEN surface touched; unflagged behavior byte-for-byte unchanged |
+
+## Data Model Changes
+
+```sql
+-- 1. The capability flag (master data)
+ALTER TABLE "process" ADD COLUMN "batchable" BOOLEAN NOT NULL DEFAULT false;
+-- Recreate the "processes" view from its NEWEST definition including the column.
+
+-- 2. The operation batch
+CREATE TYPE "jobOperationBatchStatus" AS ENUM ('Active', 'Completed', 'Cancelled');
+
+CREATE TABLE "jobOperationBatch" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "readableId" TEXT NOT NULL, -- BAT000001 (getNextSequence)
+ "companyId" TEXT NOT NULL,
+ "processId" TEXT NOT NULL, -- every member matches this
+ "workCenterId" TEXT, -- where the batch runs; propagated to members
+ "locationId" TEXT NOT NULL, -- planning board is per-location
+ "status" "jobOperationBatchStatus" NOT NULL DEFAULT 'Active',
+ "notes" TEXT,
+ "customFields" JSONB,
+ "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,
+ CONSTRAINT "jobOperationBatch_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "jobOperationBatch_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobOperationBatch_processId_fkey" FOREIGN KEY ("processId")
+ REFERENCES "process"("id"),
+ CONSTRAINT "jobOperationBatch_workCenterId_fkey" FOREIGN KEY ("workCenterId")
+ REFERENCES "workCenter"("id") ON DELETE SET NULL,
+ CONSTRAINT "jobOperationBatch_locationId_fkey" FOREIGN KEY ("locationId")
+ REFERENCES "location"("id"),
+ CONSTRAINT "jobOperationBatch_readableId_unique" UNIQUE ("readableId", "companyId")
+);
+-- RLS: SELECT employee role; INSERT/UPDATE/DELETE production_create/update/delete
+-- (policy names "SELECT" etc., ::text[] casts — copy the newest migration idiom).
+
+-- 3. Membership — one nullable FK on jobOperation
+ALTER TABLE "jobOperation" ADD COLUMN "jobOperationBatchId" TEXT;
+ALTER TABLE "jobOperation" ADD CONSTRAINT "jobOperation_jobOperationBatchId_fkey"
+ FOREIGN KEY ("jobOperationBatchId", "companyId")
+ REFERENCES "jobOperationBatch"("id", "companyId") ON DELETE SET NULL;
+CREATE INDEX "jobOperation_jobOperationBatchId_idx"
+ ON "jobOperation" ("jobOperationBatchId") WHERE "jobOperationBatchId" IS NOT NULL;
+
+-- 4. Batch-tagged timers (while running; slices keep the tag for auditability)
+ALTER TABLE "productionEvent" ADD COLUMN "jobOperationBatchId" TEXT;
+-- + same composite FK shape (ON DELETE SET NULL) + partial index
+
+-- 5. Sequence for readable ids (existing companies via migration,
+-- new companies via the seed-company sequences seed)
+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")
+SELECT 'jobOperationBatch', 'Operation Batch', 'BAT', NULL, 0, 6, 1, "id"
+FROM "company" ON CONFLICT DO NOTHING;
+```
+
+Also required (behavioral, not new tables):
+
+- **`get_active_job_operations_by_location`** (feeds the ERP schedule board AND
+ the MES kanban; newest definition `20260531084723_rework-serial-flow.sql`):
+ re-declare from the newest definition adding `processBatchable`,
+ `jobOperationBatchId`, `batchReadableId` (LEFT JOIN `jobOperationBatch`).
+- **New RPC `get_batchable_operations`** `(location_id, process_id)` for the
+ planning board: unstarted, unbatched operations of that (batchable) process at
+ the location, joined to job/item, plus a `materials` JSONB array per operation —
+ each element `{itemReadableId, description, quantity, formName, substanceName,
+ gradeName, dimensionName, finishName, formId, substanceId, gradeId, dimensionId,
+ finishId}` — built from `jobMaterial.jobOperationId → item → material`
+ (`material.id = item.readableId`) → the five property lookups. Operations whose
+ BOM lines lack material rows return an empty array and group under "No material
+ properties" in the UI. Also returns current members of Active batches for the
+ process (to render batch lanes).
+- After migration: `pnpm run generate:types` before typecheck.
+
+## API / Service Changes
+
+### New edge function: `batch-operations` (`packages/database/supabase/functions/batch-operations/`)
+
+Follows `.ai/rules/workflow-edge-function.md`: CORS preflight, zod discriminated
+union, `requirePermissions(req, companyId, userId, { update: "production" })`,
+module-scope Kysely pool, one transaction per request. Payload types:
+
+- `{ type: "create", jobOperationIds: string[] (min 1), workCenterId?, locationId, companyId, userId }`
+ — validates the eligibility gate (batchable process via join, single process,
+ unstarted, unbatched); derives `processId` from the members; `getNextSequence`
+ → `BAT...`; inserts the batch; tags members; writes `workCenterId` to members
+ when provided. Returns `{ id, readableId }`.
+- `{ type: "add", batchId, jobOperationIds, companyId, userId }` — same gate per
+ candidate + batch must be `Active` with no production events; tags members;
+ propagates the batch's work center if set.
+- `{ type: "remove", batchId, jobOperationIds, companyId, userId }` — blocked once
+ any batch production event exists; clears the FK; removing the last member
+ deletes the batch.
+- `{ type: "update", batchId, workCenterId, companyId, userId }` — assigns (or
+ clears) the batch's work center; when set, writes it to every member
+ operation's `workCenterId`.
+- `{ type: "dissolve", batchId, companyId, userId }` — blocked once any batch
+ production event exists (error: "production has been recorded — complete the
+ batch instead"); clears all members; deletes the batch.
+- `{ type: "complete", batchId, members: [{ jobOperationId, quantity, scrapQuantity? }], companyId, userId }`
+ — in one transaction: close open batch-tagged `productionEvent`s (`endTime = NOW()`);
+ slice every batch-tagged event into contiguous per-member events with durations
+ ∝ member `operationQuantity` (update the original row to the first slice, insert
+ the rest; slices keep `jobOperationBatchId`, `postedToGL = false`); insert
+ `productionQuantity` rows per member (`Production` + optional `Scrap`);
+ multi-row `UPDATE ... SET status = 'Done'` on members (per-row interceptor
+ releases each job's next operation); set batch `Completed`. Returns
+ `{ memberIds, eventIds }` for the caller's follow-ups.
+
+### `production.service.ts` additions (`apps/erp/app/modules/production/`)
+
+```typescript
+getJobOperationBatch(client, batchId, companyId) // batch + member ops + jobs
+getBatchableOperations(client, { locationId, processId, companyId }) // rpc wrapper
+getActiveBatchesByProcess(client, { processId, locationId, companyId })
+createJobOperationBatch(client, payload) // invoke("batch-operations", { type: "create" })
+addToJobOperationBatch(client, payload) // type: "add"
+removeFromJobOperationBatch(client, payload) // type: "remove"
+dissolveJobOperationBatch(client, payload) // type: "dissolve"
+```
+
+`production.models.ts`: `jobOperationBatchStatus` const,
+`createJobOperationBatchValidator`, `updateJobOperationBatchValidator` (add/
+remove/dissolve intents), `completeJobOperationBatchValidator` (member rows with
+int quantities ≥ 0). **No max-size validation anywhere.**
+
+MES (`apps/mes/app/services/`): `getJobOperationBatch`, batch completion
+validator in `models.ts`; the complete action invokes `batch-operations` then,
+per member, the existing `issue` (`type: "jobOperation"`) and, per returned
+event, `post-production-event` — mirroring `finishJobOperation`'s GL pattern.
+
+### `resources` module
+
+`processValidator` gains `batchable: zfd.checkbox()`; `upsertProcess` passes it
+through; `ProcessForm` gains the Boolean field (clone `completeAllOnScan`).
+
+## UI Changes
+
+| Surface | Change |
+|---------|--------|
+| Process form (`resources/ui/Processes/ProcessForm.tsx`) | "Batchable" checkbox — "Multiple jobs can run on this process at the same time (laser table, furnace, plating bath)" |
+| Processes table | `Batchable` boolean column/badge |
+| **Batch planning board** (new: `x/schedule/batching`) | Location + batchable-process pickers; left pane = filterable candidate operations (cards: job, item, quantity, due date, material chips), faceted URL-param filters on form/substance/grade/dimension/finish + search (clone the operations board's `Filter`/`ActiveFilters`/`useFilters` pattern; pickers reuse the existing material-lookup comboboxes); right pane = Active batch lanes (readableId, work center, members, summed qty) + "New batch" drop zone; `@dnd-kit` drag in/out; work-center assignment on the lane; dissolve action. Persists via fetcher to an action route calling the service wrappers |
+| Schedule board (`ui/Schedule/Kanban/ItemCard.tsx`) | Batched ops render a `BAT000001` badge; card menu gains "Batch planning" (nav, process pre-filtered) for batchable unbatched ops and "Remove from batch" (guarded) for batched ones |
+| MES kanban (`apps/mes/.../ItemCard.tsx` + operations loader) | Rows sharing `jobOperationBatchId` collapse to one card: member count, summed quantity, batch readableId; card links to the batch view |
+| MES batch view (new: `x/batch/$batchId`) | Member table (job, item, quantity, due date, link to each member op for per-op flows), Start/Stop timers (events tagged with the batch), **Complete Batch** form: per-member produced quantity (pre-filled) + optional scrap, copy stating time splits proportionally to quantity |
+| Job detail | Member operation shows the batch badge; estimates-vs-actuals needs **no math change** (per-member events) — optional "part of BAT…" badge only |
+
+## Acceptance Criteria
+
+- [ ] Toggling `batchable` on a process makes its unstarted job operations appear on the batch planning board; unflagged processes are absent from the process picker and their operations never offer batch actions.
+- [ ] Filtering candidates by substance=Steel + grade=A36 + dimension=1/4" shows exactly the operations whose BOM lines resolve to those material properties; an operation consuming aluminum disappears; operations with no material-bearing BOM lines group under "No material properties".
+- [ ] Dragging 3 operations (different jobs, different items) into "New batch" creates a `jobOperationBatch` with a `BAT`-sequence readableId, tags all 3, and both boards render one card; dragging one out again untags it; a 30-member batch is accepted (no cap).
+- [ ] Assigning the batch a work center writes that `workCenterId` to every member operation; adding an op to a work-centered batch sets the op's work center.
+- [ ] Server rejects (with a specific error per rule): mixing processes, a non-batchable process, a started operation, an already-batched operation, and add/remove/dissolve after any batch production event (dissolve error names the recovery: complete the batch).
+- [ ] Starting the batch in MES creates `productionEvent` rows tagged with `jobOperationBatchId`; the batch card shows the running timer.
+- [ ] Completing a batch (members qty 5/20/10, one 70-minute machine event) yields per-member events of 10/40/20 minutes (largest-remainder on seconds, contiguous windows), per-member `productionQuantity` rows matching the entered quantities (+ scrap rows where entered), one `issue` call per member consuming that job's own BOM (no `jobMaterial` row rewritten), all members `Done` in one action, each member job's next operation independently flipping to `Ready`, batch `Completed`, and `post-production-event` posting GL per member event.
+- [ ] Job costing / estimates-vs-actuals for each member job shows its proportional share with no special-case code path (verified by reading each member op's own events).
+- [ ] Jobs/operations never batched behave byte-for-byte as before; `pnpm exec turbo run typecheck --filter=erp --filter=mes`, lint, and tests pass.
+- [ ] The superseded feature's terminology (case-insensitive grep pattern `st[i]tch`) appears nowhere in the shipped code, migrations, or docs for this feature.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Quantity weights distort cost when parts differ wildly in size (20 washers vs 5 large panels on one sheet) | Med | Documented limitation; weights live in one function in the edge fn — area/cut-time weights via nesting import is the designed v2 upgrade path |
+| Sliced event windows are temporal approximations (contiguous sub-spans, not the "real" simultaneous run) | Low | Durations sum exactly to the recorded span; slices keep `jobOperationBatchId` so provenance is queryable; documented in AGENTS.md |
+| `get_active_job_operations_by_location` re-declaration regresses a board (two apps consume it) | Med | Fork the newest definition verbatim, additive columns only; smoke both boards |
+| Ops whose `jobMaterial` rows lack `jobOperationId` show no material chips | Low | Column exists since `20260120132502` (with backfill); "No material properties" bucket keeps them visible/batchable |
+| Planner batches metrically incompatible materials (filters are advisory) | Low | Deliberate (research: material match is workflow, not schema); chips make membership visible; hard constraints would fight real shop exceptions |
+| Terminology confusion with lot/batch tracking | Low | Naming decision documented; UI copy says "operation batch"; AGENTS.md and glossary spell out the distinction |
+
+## Open Questions
+
+> HARD STOP satisfied 2026-07-03: Brad pre-delegated resolution (combined
+> spec+plan request); each answer below is a documented recommendation applied to
+> this spec — veto any of them and the spec+plan will be revised.
+
+- [x] **Weight basis for the proportional split?** — **Answer: planned
+ `operationQuantity`** (share = member qty / Σ). Defined before/during the run;
+ zero-produced members still absorb time (their parts occupied the machine).
+ Produced-actuals weighting rejected (undefined mid-run, zero-yield edge); part
+ area/cut-time rejected for v1 (needs nesting import — v2).
+- [x] **Must members share a work center?** — **Answer: no — the batch owns the
+ work center.** Adding an op to a batch (or assigning the batch a work center)
+ writes the member's `workCenterId`, exactly like a schedule-board drag. Requiring
+ pre-matching would block the planner for no physical reason.
+- [x] **Which material facets filter the board?** — **Answer: form, substance,
+ grade, dimension, finish** (+ text search) — the normalized `material` FKs that
+ exist today, with existing combobox components; matches the industry keys
+ (material + thickness + machine). An op matches if ANY of its BOM lines match
+ all active facets. `materialType` omitted from facets in v1 (derivable from
+ form+substance; add later if asked).
+- [x] **Minimum batch size?** — **Answer: 1** (a batch must contain at least one
+ operation; removing the last member dissolves it). No maximum, per Brad. A
+ 1-member batch is transitional drag-and-drop state, not an error.
+- [x] **Scrap at batch completion?** — **Answer: optional per-member scrap input**
+ on the completion form (posts `Scrap`-type `productionQuantity` per member).
+ Even-split scrap (prior design) is wrong under per-member quantities; NCR/quality
+ workflows unchanged (member ops are real rows).
+- [x] **Where do timers live while the batch runs?** — **Answer: `productionEvent`
+ rows on the first member operation, tagged `jobOperationBatchId`, sliced into
+ per-member events at completion.** Events require a `jobOperationId`; the tag
+ makes the batch timer queryable, and slicing materializes the proportional
+ split so GL/costing need no batch awareness. (The alternative — batch-aware
+ query-time division everywhere — was the prior design's latent GL bug.)
+- [x] **Auto-suggest batches during planning/MRP?** — **Answer: manual board only
+ in v1**; solver-style grouping (Opcenter operation aggregation) is v2.
+- [x] **Capacity semantics (how much fits on the table/in the furnace)?** —
+ **Answer: out of scope** — separate future spec (PlanetTogether Batch Volume
+ pattern); v1 batches are unbounded by design.
+
+## Changelog
+
+- 2026-07-03: Created, superseding the prior spec (commit `d6c7ad3de`) after
+ Brad's redesign direction: (1) terminology is batch/batchable throughout — the
+ old feature name is eliminated; (2) batchability is a **process** property (laser
+ batchable, brake press not) — the per-item Manufacturing-tab flag and per-
+ routing-step marker are deleted, along with all get-method propagation; (3) a
+ material-property-filtered drag-and-drop batch planning board is core scope
+ ("all job operations on the laser table using 1/4-inch A36 steel").
+- 2026-07-03: Brad: no batch size constraint (old ≤10 cap removed) and cost split
+ proportional to job quantity (old even split removed). Consequence adopted:
+ proportional split materialized as per-member `productionEvent` slices at
+ completion, fixing the prior design's GL misattribution; produced quantity and
+ material consumption become per-member (own-BOM) rather than even splits.
+- 2026-07-03: Research refreshed at `.ai/research/job-operation-batching.md`
+ (SAP order combination/process lots, APS batchable resources, sheet-metal
+ nesting workflow); all open questions resolved with recommendations pending
+ Brad's veto; status → in-progress, ready for `/plan`.