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.
Sub-assembly staging — implementation plan
Spec / source: .ai/specs/2026-09-28-assembly-subassembly-staging.md
Research: .ai/research/2026-09-28-assembly-subassembly-staging.md
Branch: feat/asembly-view-isolation (worktree /Users/aashu/work/carbon/carbon-feat-asembly-view-isolation)
Rules for the executor:
- Never
git commit(the user commits by hand). - Never rebuild or reset the database. No migration is needed.
- New user-facing copy uses Lingui (
<Trans>ort`…`). - Validation commands are scoped. Whole-repo typecheck runs out of memory.
Progress
- Task 1: Viewer contract —
joinStepIdreplacesphase - Task 2: Viewer
staging.tspure helpers + tests - Task 3:
buildStepClipglide option + tests - Task 4: Wire staging into
AssemblyPlayer - Task 5: ERP service — join validation, reorder cleanup, mapper
- Task 6: ERP join route + path helper
- Task 7: ERP step Details — "Build off to the side" select + join summary
- Task 8: ERP explorer badge, Regenerate warning, own-parts in route
- Task 9: MES select + mapper
- Task 10: Lingui extraction
- Task 11: Docs (viewer + production AGENTS.md)
- Task 12: End-to-end verification
Dependencies
Tasks 1 → 2 → 3 → 4 run in order (all viewer). Task 5 needs 1. Task 6 needs 5. Tasks 7 and 8 need 2, 5 and 6. Task 9 needs 1 and is independent of 5–8. Task 10 needs 7 and 8. Task 11 can run any time after 4. Task 12 comes last.
Task 1: Viewer contract — joinStepId replaces phase
Depends on: none Files:
- Modify:
packages/viewer/src/types.ts: inAssemblyStep(~line 117), replace thephasefield and its doc comment.
Steps:
- Delete the
phase?: { id: string; name: string; join: boolean } | null;field and its comment block. - Add in its place:
/** * Built off to the side: the id of the later JOIN step where the group this * step builds is carried into the main assembly (DB `parentStepId`). * `null`/absent = built in place. See `staging.ts`. */ joinStepId?: string | null; - Leave
StepPhaseandassignStepPhasesinplan.tsuntouched. They are a separate, unused plan-side type.
Verify:
pnpm --filter @carbon/viewer typecheck
# Expected: exits 0 with no errors
Out of scope: plan.ts, CURRENT_PLAN_VERSION, and any geometry-service contract.
Task 2: Viewer staging.ts pure helpers + tests
Depends on: 1 Files:
- Create:
packages/viewer/src/staging.ts - Create:
packages/viewer/src/staging.test.ts - Modify:
packages/viewer/src/index.ts: export the new helpers and types - Copy from (precedent):
packages/viewer/src/visibility.ts+visibility.test.ts(a pure module with a vitest file), andgraph.test.tsfor building anAssemblyGraphIndexfixture viaindexAssemblyGraph
Steps:
- Create
staging.ts. It must have nothreeimports. It usesAssemblyGraphIndexfrom./graphandAssemblyStep/Vec3from./types./** Seconds the staged group takes to glide from its staging spot to the insertion start. */ export const STAGING_GLIDE_SECONDS = 1.2; /** Gap between the main model and a staging lane, and between lanes, as a fraction of the assembly diagonal. */ const STAGING_GAP_FRACTION = 0.25; export type StagingJoin = { /** Index of the join step */ joinIndex: number; /** Every node installed by this join's staged steps, in step order (no dedupe loss: first occurrence wins) */ nodeIds: string[]; /** Pure world translation from seat to staging spot */ offset: Vec3; }; export type Staging = { /** Keyed by join step index */ joins: Map<number, StagingJoin>; /** staged step index → its join step index */ stagedToJoin: Map<number, number>; }; export const EMPTY_STAGING: Staging = { joins: new Map(), stagedToJoin: new Map() }; /** Ids of the parts a join step carries in: every componentNodeId of the steps pointing at it. */ export function stagedGroupNodeIds( steps: Pick<AssemblyStep, "id" | "componentNodeIds" | "joinStepId">[], joinStepId: string ): string[]; export function buildStaging( steps: Pick<AssemblyStep, "id" | "componentNodeIds" | "joinStepId">[], graphIndex: AssemblyGraphIndex | null ): Staging; /** nodeId → offset for every node that sits at its staging spot while step `activeIndex` is shown. */ export function parkedOffsetsAt( staging: Staging, steps: Pick<AssemblyStep, "componentNodeIds">[], activeIndex: number ): Map<string, Vec3>; buildStagingrules. Each one is defensive: the viewer ignores bad links rather than throwing.- A link counts only when: the join id resolves to a step index
j;j > i(the staged index);i !== 0; stepjhas nojoinStepIdof its own; and stepiis not itself a join target of another step. Otherwise, ignore the link (treat it as built in place). - Group
nodeIds: concatenatecomponentNodeIdsof the valid staged steps in index order, and drop duplicates. - Offset: with
graphIndexnull, returnEMPTY_STAGING. Otherwiseroot = graphIndex.graph.root.bbox,diag = hypot(max-min), andgap = diag * STAGING_GAP_FRACTION. Walk joins in ascendingjoinIndexwithcursor = root.max[0] + gap. For each join, compute the group bbox (union ofgraphIndex.nodesById.get(id)?.bboxfor its nodeIds, skipping unknown ids; skip the join entirely if none resolve). Setoffset = [cursor - groupMin[0], 0, 0], thencursor += (groupMax[0] - groupMin[0]) + gap.
- A link counts only when: the join id resolves to a step index
parkedOffsetsAt(staging, steps, a): for each[i, j]ofstagedToJoinwherei <= a && a < j, map every id insteps[i].componentNodeIdstostaging.joins.get(j).offset(skip if the join is missing).staging.test.tsmust cover these cases:- Two staged steps pointing at step 3 give one join.
nodeIdsholds the union and the offset x is greater than 0. - A link pointing backwards, from the first step, to a staged step (nesting), or to an unknown id is ignored.
- Two joins get non-overlapping lanes: the second lane's
min x + offsetis at least the first'smax x + offset + gap. parkedOffsetsAtreturns nothing before a staged step, includes the staged step's own nodes when it is active, includes earlier staged nodes on later staged steps, and returns nothing at or after the join index.stagedGroupNodeIdsreturns the union for a join id and[]for others.
- Two staged steps pointing at step 3 give one join.
- Export from
index.ts:buildStaging,parkedOffsetsAt,stagedGroupNodeIds,STAGING_GLIDE_SECONDS,EMPTY_STAGING,type Staging, andtype StagingJoin. Also addstagedGroupNodeIdstosteps.ts(the three-free subpath) so server code can use it.
Verify:
pnpm --filter @carbon/viewer test -- staging
# Expected: all staging tests pass
pnpm --filter @carbon/viewer typecheck
# Expected: exits 0
Out of scope: rendering code and AssemblyPlayer.tsx.
Task 3: buildStepClip glide option + tests
Depends on: 2 Files:
- Modify:
packages/viewer/src/motion.ts:StepClipOptionsandbuildStepClip(~line 467) - Modify:
packages/viewer/src/motion.test.ts: add cases indescribe("buildStepClip")(~line 325)
Steps:
- Extend
StepClipOptionswith:/** Join step: prepend a straight glide from seat+offset to the insertion start. */ glide?: { offset: Vec3; seconds: number }; - In
buildStepClip:- The early return becomes
if ((step.motion.type === "none" && !options.glide) || step.componentNodeIds.length === 0) return null;. - Per node, compute the insertion keyframes as today. If the motion is
none, use a single keyframe at the seated pose (times [0]). - If
glideis set:glideStart = seat + offset,glideEnd = first insertion keyframe position(the quaternion stays the seated one). BuildEASE_SAMPLES + 1eased samples witheaseInOutCubicoverglide.seconds, then append the insertion keyframes with times shifted byglide.seconds(skip the insertion's t=0 frame because it duplicatesglideEnd). - Clip duration becomes
glide.seconds + insertion duration (0 for none) + hold.
- The early return becomes
- Add these tests:
- A glide on a linear motion: the first keyframe position is
seat + offset, the frame att = secondsequals the linear start, the last non-hold frame equals the seat, andclip.durationequalsseconds + motionDuration + hold. - A glide on
none: the clip is not null, it starts atseat + offset, and it ends at the seat. - Without a glide, the output is unchanged (existing tests still pass).
- A glide on a linear motion: the first keyframe position is
Verify:
pnpm --filter @carbon/viewer test -- motion
# Expected: all motion tests pass, including the new glide cases
Out of scope: naturalizeMotion (the glide is never clamped), motionToKeyframes and stepTimelineSeconds.
Task 4: Wire staging into AssemblyPlayer
Depends on: 3 Files:
- Modify:
packages/viewer/src/AssemblyPlayer.tsx
Steps:
- Top-level component (where
displayStepsis built, ~line 325):const staging = useMemo(() => buildStaging(steps, graphIndex), [steps, graphIndex]);- In
displaySteps: for a step index instaging.joins, the display step'scomponentNodeIds=[...own, ...join.nodeIds](deduped) BEFORE fallback and naturalize. This way the fallback motion, the naturalized travel, the hidden-set exclusion and the camera all cover the moving group. Addstagingto the memo deps. segments:displaySteps.map((s, i) => stepTimelineSeconds(s) + (staging.joins.has(i) && !(s.durationSeconds && s.durationSeconds > 0) ? STAGING_GLIDE_SECONDS : 0)).- Pass
stagingtoAssemblySceneas a new propstaging: Staging, typed in the props block with a doc comment.
AssemblySceneclip effect (~line 1289):- Add to
clipKey:JSON.stringify([...parkedOffsetsAt(staging, steps, activeStepIndex)].sort())andJSON.stringify(staging.joins.get(activeStepIndex)?.offset ?? null), and addcomponentPickerActive. - At the top of the effect body (after the seek bookkeeping and the
!stepreturn), if!isEditingActive && !componentPickerActive, computeparked = parkedOffsetsAt(staging, stepsLiveRef.current, activeStepIndex). Reduce it to TOP-MOST nodes: skip a node whoseObject3Dancestor chain contains another parked node (walknode.parentand checkuserData.nodeId). For each top-most node, save{node, position, quaternion}, then move it: compute the world position, add the offset, and convert back to parent-local withnode.parent.worldToLocal(...). Callnode.updateWorldMatrix(true, true)afterwards. - Every return path after this point must return a cleanup that restores the parked nodes. Restore the clip's
restorelist FIRST and the parked list SECOND. Restructure the early returns (editing, no clip) so they return a cleanup that restoresparked. - Build the clip with
buildStepClip(step, nodesById, glide), whereglide = staging.joins.get(activeStepIndex) ? { glide: { offset: join.offset, seconds: STAGING_GLIDE_SECONDS } } : {}. Pass the glide only when not editing and not picking.
- Add to
- Fade effect (~line 1411): add
&& !staging.joins.has(activeStepIndex)tofadesIn, because a join step glides and never fades. - Camera framing effect (~line 1670):
- Add a JSON of
parkedOffsetsAt(...)and the join offset toframingKey. - When building
componentBox, translate each node's seated bbox by its parked offset (if any). - For a join step, also push the 8 corners of
componentBoxtranslated byjoin.offsetinto bothlookPointsandactionPoints, so the frame covers the staging spot and the seat. - Where
getAssemblyBox()is used for the framing center/radius, expand a clone of it by those translated corners when the step is staged or a join.
- Add a JSON of
- Leave the visual pass (
stepIndexByNode,visualForComponent) unchanged. It already claims the first installing step, and staged steps come before their join.
Verify:
pnpm --filter @carbon/viewer typecheck
# Expected: exits 0
pnpm --filter @carbon/viewer test
# Expected: all suites pass (camera, fallback, graph, motion, plan, staging, visibility)
If the parked-restore ordering cannot be made correct inside the single clip effect (for example, a second effect also moves nodes), STOP and report. Do not add a second position-writing effect.
Out of scope: MotionPathEditor, visibility.ts view modes, and the fallback algorithm.
Task 5: ERP service — join validation, reorder cleanup, mapper
Depends on: 1 Files:
- Modify:
apps/erp/app/modules/production/production.models.ts: add a validator next toassemblyInstructionStepHiddenComponentsValidator(~line 1473) - Modify:
apps/erp/app/modules/production/production.service.ts: newupdateAssemblyStepJoinafterupdateAssemblyStepHiddenComponents(line 7288); changeline 7490); mapupdateAssemblyInstructionStepOrder(joinStepIdintoViewerStep(~line 9263) - Modify:
apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx: passparams.id
Steps:
- Validator:
Match whateverexport const assemblyInstructionStepJoinValidator = z.object({ joinStepId: zfd.text(z.string().optional()) });zfd/zimport style the file already uses. An empty value means "build in place". - Service function. It uses the supabase client and is scoped by
companyId:export async function updateAssemblyStepJoin( client: SupabaseClient<Database>, data: { stepId: string; joinStepId: string | null; companyId: string; updatedBy: string } ): Promise<{ error: string | null }>- Load the step (
id, assemblyInstructionId, sortOrder) with.eq("id").eq("companyId"). If it is missing, return{ error: "Step not found" }. - If
joinStepIdis set: load all steps of the instruction (id, sortOrder, parentStepId) with one query, ordered bysortOrder. Reject when:- the join is not in that list: "The join step is not in this instruction";
- the step is the first in the list: "The first step is the base and can't be built aside";
join.sortOrder <= step.sortOrder: "The join step must come after this step";join.parentStepIdis not null: "The join step is itself built aside";- any row has
parentStepId === step.id: "This step is a join step, so it can't be built aside".
- Update
parentStepId,updatedByandupdatedAton the step. Return{ error: update.error?.message ?? null }. - Doc comment: "parentStepId = the join step this step is built aside for (see the sub-assembly staging spec)."
- Load the step (
updateAssemblyInstructionStepOrder(db, assemblyInstructionId, updates): after the sortOrder loop, inside the same transaction, clear the links that now point backwards:
Update the only caller,await trx .updateTable("assemblyInstructionStep as s") .set({ parentStepId: null }) .where("s.assemblyInstructionId", "=", assemblyInstructionId) .where("s.parentStepId", "is not", null) .where(({ exists, selectFrom }) => exists( selectFrom("assemblyInstructionStep as j") .select("j.id") .whereRef("j.id", "=", "s.parentStepId") .whereRef("j.sortOrder", "<=", "s.sortOrder") ) ) .execute();$id.steps.order.tsx, to passparams.id. Confirm with agrep -rn "updateAssemblyInstructionStepOrder" apps packagesthat there is no other caller. If there is one, STOP and report.toViewerStep: addjoinStepId: step.parentStepId ?? null.- Regenerate the MCP digest only if the repo's check requires it after adding a service function: run
pnpm run generate:mcpifapps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonis stale. The digest was regenerated in the previous commit on this branch, so follow the same practice.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: typecheck task for erp succeeds
Out of scope: the DB trigger, migrations and reassignAssemblyStepComponents.
Task 6: ERP join route + path helper
Depends on: 5 Files:
- Create:
apps/erp/app/routes/x+/assembly+/$id.steps.join.$stepId.tsx - Modify:
apps/erp/app/utils/path.ts: addassemblyInstructionStepJoinnext toassemblyInstructionStepHiddenComponents(~line 376) - Copy from (precedent):
apps/erp/app/routes/x+/assembly+/$id.steps.hidden.$stepId.tsx
Steps:
- Path helper:
assemblyInstructionStepJoin: (id: string, stepId: string) => generatePath(\${x}/assembly/${id}/steps/join/${stepId}`)`. - Route: copy the hidden route. Use
requirePermissions(request, { update: "production" })and also takecompanyIdfrom its result. Validate withassemblyInstructionStepJoinValidatorand callupdateAssemblyStepJoin(client, { stepId, joinStepId: validation.data.joinStepId || null, companyId, updatedBy: userId }). Onerror, returndata({ success: false, message: error }, await flash(request, error(null, message))). On success, return{ success: true }.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: succeeds
Out of scope: any other step route.
Task 7: ERP step Details — "Build off to the side" select + join summary
Depends on: 2, 5, 6 Files:
- Modify:
apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx - Modify:
apps/erp/app/routes/x+/assembly+/$id.tsx: pass the new props - Copy from (precedent):
StepStatusControlinapps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx:928-1000(autosavinguseFetcher+DropdownMenuRadioGroup, optimistic value). For the box styling, copy the "Camera" box inAssemblyInstructionProperties.tsx:~562.
Steps:
- New props on
AssemblyInstructionProperties:steps: AssemblyInstructionStepRow[](all steps, sortOrder-ordered), plusonSelectStep: (stepId: string) => void. Pass them from$id.tsx, which already has the steps list and a select-step handler. Find the existing handler name used by the Explorer and reuse it. - New component
StepJoinEditorin the same file, rendered inStepFormdirectly after the Camera box:- Label:
<Trans>Build off to the side</Trans>. - Options: "No, build in place" (value
""), then for each VALID join step (the same rules as the service, computed client-side fromsteps):t\Yes, joins at step ${n}: ${title}`. UsedescribeStep` for untitled steps, the same way the header title does. - Disabled (plain text chip instead of a dropdown) when
isDisabled, when this is the first step, or when this step is itself a join step. In those last two cases, show a muted one-line reason:t\The first step is the base.`/t`This step brings in a group, so it's built in place.``. - On change,
fetcher.submit({ joinStepId }, { method: "post", action: path.to.assemblyInstructionStepJoin(instructionId, step.id) }). Show the optimistic value fromfetcher.formData.
- Label:
- On a join step (other steps point at it), render inside the same box a read-only line:
<Trans>Brings in the group from steps</Trans>followed by step-number buttons (Button variant="link" size="sm") that callonSelectStep(id). - Helper text under the select (muted,
text-xs):<Trans>Its parts are built beside the model, then carried in at the join step.</Trans>
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: succeeds
Out of scope: the Components and Hidden boxes (Task 8 changes only what they receive).
Task 8: ERP explorer badge, Regenerate warning, own-parts in route
Depends on: 2, 5 Files:
- Modify:
apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx: step row (line 1100) and Regenerate modal (line 815) - Modify:
apps/erp/app/routes/x+/assembly+/$id.tsx:selectedOwnNodeIds(~line 298) - Copy from (precedent): the
needsSupporticon span in the same step row, for badge placement;Badgefrom@carbon/react
Steps:
- Step row: when
step.parentStepIdis set, render<Badge variant="secondary" className="shrink-0"><Trans>Built aside</Trans></Badge>before the×countspan. - Regenerate modal body: when any step has
parentStepId, add a paragraph:<Trans>Regenerating removes "Build off to the side" settings.</Trans> $id.tsx: extendselectedOwnNodeIdsto include the staged group when the selected step is a join step:
(const selectedOwnNodeIds = useMemo(() => { const own = draftComponentNodeIds ?? selectedStep?.componentNodeIds ?? []; if (!selectedStep) return own; const staged = stagedGroupNodeIds(viewerSteps, selectedStep.id); return staged.length === 0 ? own : [...new Set([...own, ...staged])]; }, [draftComponentNodeIds, selectedStep, viewerSteps]);viewerStepsis defined further down at ~line 432. Move itsuseMemoabove this one.) Check every consumer ofselectedOwnNodeIds(grep in the file). It must only feed the "This step" badge, the hide eligibility and the hidden-list filter. If it also feeds a SAVE ofcomponentNodeIds, STOP and report.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: succeeds
Out of scope: the BOM-tree "Move / Add a copy" modal.
Task 9: MES select + mapper
Depends on: 1 Files:
- Modify:
apps/mes/app/services/operations.service.ts:~640: addparentStepIdto the select string - Modify:
apps/mes/app/components/AssemblyView.tsx:190-230: addparentStepId: string | nullto theAssemblyPlaybackstep type, andjoinStepId: step.parentStepId ?? nullintoViewerStep
Verify:
pnpm exec turbo run typecheck --filter=mes
# Expected: succeeds
Out of scope: any MES UI.
Task 10: Lingui extraction
Depends on: 7, 8 Steps:
- Run
pnpm run lingui:extract. git diff --stat packages/localemust show only the ERP catalogs (packages/locale/locales/*/erp.po) plus any lines the extract touched for the new strings. If unrelated catalogs churn heavily, revert that churn withgit checkout -- <file>and keep only the new msgids.- Run
pnpm run lingui:cleanif the headers changed (the repo's own script).
Verify:
grep -c "Build off to the side" packages/locale/locales/en/erp.po
# Expected: 1 or more
Task 11: Docs
Depends on: 4 Files:
- Modify:
packages/viewer/AGENTS.md:- In the Step concept, replace "subassembly
phase" with "joinStepId(built off to the side, seestaging.ts)". - Fix the stale "must contain an
isolateview" rule to matchvisibility.ts(Isolate was dropped on this branch). - Add
staging.tsto the key building blocks, and the staging test to the test list.
- In the Step concept, replace "subassembly
- Modify:
apps/erp/app/modules/production/AGENTS.md: one line under Assembly Instructions: "assemblyInstructionStep.parentStepId= the join step a step is built aside for (sub-assembly staging); written byupdateAssemblyStepJoin, cleared on reorder when it points backwards."
Verify:
grep -n "joinStepId" packages/viewer/AGENTS.md
# Expected: at least one match
Task 12: End-to-end verification
Depends on: all Steps:
- Run:
Expected: all pass. Report any failure with its output.pnpm --filter @carbon/viewer test pnpm --filter @carbon/viewer typecheck pnpm exec turbo run typecheck --filter=erp --filter=mes pnpm run lint - Browser check (ask the user first, per AGENTS.md "With the user's permission, use the /auth and /test skill"): on an assembly with at least 5 steps, run acceptance criteria 1–5 and 7 from the spec. Take screenshots of step 4 (group at the side) and mid-glide on step 6. Check criterion 6 (MES) only if the MES app is running locally.
- Tick the Progress list, and add a changelog line to the spec ("implemented").
- Do NOT commit. Report to the user in 1–3 lines.