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.

feat(spec): add work order stitching plans

Sidwebworksd6c7ad3de156
diff --git a/.ai/plans/work-order-stitching-plan.md b/.ai/plans/work-order-stitching-plan.md
new file mode 100644
index 0000000000..54116c76be
--- /dev/null
+++ b/.ai/plans/work-order-stitching-plan.md
@@ -0,0 +1,921 @@
+# 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/specs/2026-07-02-work-order-stitching.md b/.ai/specs/2026-07-02-work-order-stitching.md
new file mode 100644
index 0000000000..70cb8bd76d
--- /dev/null
+++ b/.ai/specs/2026-07-02-work-order-stitching.md
@@ -0,0 +1,308 @@
+# 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`.