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.
Per-step build orientation — implementation plan
Historical — superseded by the implemented spec. This plan records how the work started. The code and
.ai/specs/implemented/2026-10-09-build-orientation.mdare the source of truth. Later changes moved the ERP wiring into theuseBuildOrientationanduseStepMotionEditorhooks, and saved views into the bench frame.
Spec: .ai/specs/implemented/2026-10-09-build-orientation.md Research: N/A. The user gave clear requirements, and this is not ERP-domain logic. The run record logs the skip. Branch: feat/sub-assembly-motion-path
The user forbids commits without permission. Each task ends at its Verify block. Do not commit.
Progress
- Task 1: Add the
orientationcolumn and regenerate the types - Task 2: Add the pure orientation module to the viewer, with tests
- Task 3: Show the orientation in the player as a camera frame
- Task 4: Save the orientation through the motion route
- Task 5: Wire the turn and Reset handlers in the assembly route
- Task 6: Add the Orientation row to the step's Playback panel
- Task 7: Pass the orientation to the MES player
- Task 8: Update the docs, AGENTS.md files, catalogs and MCP digest
- Task 9: Verify in the browser
Dependencies
- Task 4 needs Task 1 (generated types).
- Task 3 needs Task 2.
- Tasks 5 and 6 need Tasks 2 and 4.
- Task 7 needs Tasks 1 and 2.
- Task 8 needs Task 6.
- Task 9 needs every other task.
- Tasks 2 and 1 are independent of each other.
Task 1: Add the orientation column and regenerate the types
Depends on: none Files:
- Create:
packages/database/supabase/migrations/{timestamp}_assembly-step-orientation.sql(the CLI picks the timestamp) - Modify:
packages/database/src/types.tsand the other generated files — regenerated, never hand-edited - Copy from (precedent):
packages/database/supabase/migrations/20260925063121_assembly-step-hidden-components.sql
Steps:
- Run
pnpm db:migrate:new assembly-step-orientation. - Write this SQL into the new file:
-- The build's orientation from this step on: a unit quaternion [x, y, z, w] -- that turns the model frame into the bench frame. Applied by the 3D player -- in the ERP editor and in MES. NULL = same as the previous step in the -- same build (main build or sub-assembly); a sub-assembly starts upright. ALTER TABLE "assemblyInstructionStep" ADD COLUMN IF NOT EXISTS "orientation" JSONB; - Run
pnpm db:migrate. - Run
pnpm run generate:types.
If pnpm db:migrate fails because the local stack is down, STOP and report. Do not apply the SQL with psql (.ai/lessons.md: PostgREST keeps a stale schema cache).
Verify:
grep -n '"orientation"' packages/database/src/types.ts | head -3
# Expected: at least one line inside the assemblyInstructionStep Row type
Out of scope: RLS, indexes, dataset files. The column is nullable, and datasets/sql.ts reads columns from information_schema.
Task 2: Add the pure orientation module to the viewer, with tests
Depends on: none Files:
- Create:
packages/viewer/src/orientation.ts - Create:
packages/viewer/src/orientation.test.ts - Modify:
packages/viewer/src/types.ts— addorientation?: Quat | nulltoAssemblyStep, with a doc comment - Modify:
packages/viewer/src/index.ts— export the new module - Copy from (precedent):
packages/viewer/src/subassembly.ts(pure module),packages/viewer/src/subassembly.test.ts
Steps:
- Start the file with the AGPL SPDX header, as in
subassembly.ts. - Export
type BuildTurn = "tipForward" | "tipBack" | "turnLeft" | "turnRight". - Export
IDENTITY_ORIENTATION: Quat = [0, 0, 0, 1]. - Export
isOrientation(value: unknown): value is Quat. It accepts 4 finite numbers with a length within 1e-3 of 1. - Export
sameOrientation(a: Quat, b: Quat): boolean. It compares|dot(a, b)| > 1 - 1e-6, soqand-qmatch. - Export
snapOrientation(q: Quat): Quat. Build the rotation matrix with three'sMatrix4. Round each entry to -1, 0 or 1. Convert the matrix back withQuaternion.setFromRotationMatrix. - Export
upForOrientation(q: Quat): Vec3. It returnsinverse(q) · (0, 0, 1). - Export
resolveOrientations(steps). Each step has the shapePick<AssemblyStep, "id" | "orientation" | "parentStepId" | "usedInStepId" | "isSubAssembly">. The function returns{ orientation: Quat; sourceStepId: string | null }[]in step order:- Keep a
Map<string | null, { orientation; sourceStepId }>, keyed byworldOf(steps, step.id)fromsubassembly.ts. - If
isOrientation(step.orientation), set the map entry of the step's build to{ step.orientation, step.id }. - Push the build's entry, or
{ IDENTITY_ORIENTATION, null }when the build has none.
- Keep a
- Export
turnOrientation(current: Quat, turn: BuildTurn, view: { position: Vec3; target: Vec3 }): Quat:- Get the camera direction
d = position - targetin the model frame. Turn it into the bench frame:d_b = current · d. - Set
htod_bwithz = 0, then normalize it. - If the length of
his below 1e-6, the camera looks straight down. Useh = (0, -1, 0), the CAD front. - For turnLeft, use axis (0,0,1) and angle −π/2. For turnRight, use axis (0,0,1) and +π/2.
- For tipForward, use axis
Z × hand +π/2. For tipBack, use the same axis and −π/2. - Return
snapOrientation(R · current).
- Get the camera direction
- Write tests in
orientation.test.ts:resolveOrientations: a main-build step sets a flip. The next main step inherits it withsourceStepIdof the setter.resolveOrientations: a sub-assembly member after that flip getsIDENTITY_ORIENTATIONandsourceStepId: null. Use the row shapes ofsubassembly.test.ts.resolveOrientations: a turn on a sub-assembly member does not change the next main-build step.turnOrientation: camera at (0, -10, 0), target at the origin,tipForwardfrom identity. Assert that the bench up of the model's top(0,0,1)moves to (0, -1, 0). The top moves toward the camera.turnOrientation:turnLeftthenturnRightgives a resultsameOrientationto identity.turnOrientation:tipForwardtwice gives a 180° turn. The model's top points to (0, 0, -1) in the bench frame.snapOrientation: a quaternion 1° off a right angle snaps exactly to that right angle.isOrientation:[0,0,0,1]passes.[0,0,0,2]and[1,2,3]fail.
If worldOf does not accept the row shape in step 8, STOP and report.
Verify:
pnpm --filter @carbon/viewer test -- orientation
# Expected: every test in orientation.test.ts passes
pnpm --filter @carbon/viewer typecheck
# Expected: exit 0
Out of scope: the player, the ERP and the MES.
Task 3: Show the orientation in the player as a camera frame
Depends on: Task 2 Files:
- Modify:
packages/viewer/src/AssemblyPlayer.tsx - Copy from (precedent): the camera transition
useFrameatAssemblyPlayer.tsx:2048and the per-step framing effect at:2093
Steps:
- In
AssemblyPlayer, computeorientations = useMemo(() => resolveOrientations(steps), [steps]). - Pass
orientation={orientations[activeStepIndex]?.orientation ?? IDENTITY_ORIENTATION}toAssemblyScene. Add the prop to its type. - In
AssemblyScene, addframeRef = useRef<{ applied: Quaternion; from: Quaternion; to: Quaternion; start: number } | null>(null). - Add an effect on
[orientation, controls]:- If
frameRef.currentis null, snap. Rotate the camera offset aboutcontrols.targetbyinverse(orientation). Setcamera.uptoupForOrientation(orientation). Storeapplied = from = to = orientation. Callcontrols.update(). - Else, if
toequalsorientation(sameOrientation), do nothing. - Else set
from = applied,to = orientation,start = performance.now().
- If
- In the transition
useFrame, before the desired-pose code:- If
appliedis notto, computet = ease(clamp((now - start) / 900))with a cubic ease-in-out. - Set
next = from.clone().slerp(to, t). - Set
delta = next⁻¹ · applied. Applydeltato the camera offset fromcontrols.target, and tocamera.up. - Set
applied = next. Callcontrols.update(). - If
t < 1, return. The desired-pose approach waits for the end of the turn.
- If
- In the controls
onStarthandler, finish a turn at once. Setappliedtotothrough the samedeltastep. - In the framing effect, replace
camera.up.clone()at line 2224 withnew Vector3(...upForOrientation(orientation)). - Add
orientation.join(",")toframingKeyandorientationto the effect deps. - Make
captureCameraPosereturn the pose in the bench frame (buildFrame.toBench). A saved view stays where the viewer stands when the build turns. (The first version kept the model frame. The browser test showed that a flip then swung the camera under the bench.)
If the GizmoViewcube tween sets camera.up back to Z, record it for Task 9. Do not patch drei.
Verify:
pnpm --filter @carbon/viewer typecheck
# Expected: exit 0
pnpm --filter @carbon/viewer test
# Expected: all tests pass (the 158 earlier tests plus the Task 2 tests)
Out of scope: motion.ts, MotionPathEditor.tsx and the box select. They stay in the model frame.
Task 4: Save the orientation through the motion route
Depends on: Task 1 Files:
- Modify:
apps/erp/app/modules/production/production.models.ts—orientationSchema, andorientationinassemblyInstructionStepMotionValidator - Modify:
apps/erp/app/modules/production/production.service.ts—updateAssemblyStepMotionandtoViewerStep - Modify:
apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx— passorientation - Copy from (precedent): the
camerafield in the same three places
Steps:
- In
production.models.ts, exportorientationSchema = unitQuaternion. Place it aftercameraSchema. - Add
orientation: jsonField(orientationSchema.nullable().optional())toassemblyInstructionStepMotionValidator. - Add
orientation?: z.infer<typeof orientationSchema> | nullto theupdateAssemblyStepMotiondata type. - Spread
orientationinto the update when it is notundefined, ascamerais spread. - Extend the doc comment:
orientation: nullclears the step's own orientation. - In
toViewerStep, parsestep.orientationwithorientationSchema.safeParse. Map a failure tonull. - In the route action, pass
orientation: validation.data.orientation. AddhasOrientationto the log call.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: upsertAssemblyInstructionStep. The step form never writes the orientation.
Task 5: Wire the turn and Reset handlers in the assembly route
Depends on: Tasks 2, 4 Files:
- Modify:
apps/erp/app/routes/x+/assembly+/$id.tsx - Modify:
apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx— thread three props toStepForm - Copy from (precedent):
onSetCamera/onClearCamerain$id.tsx(around line 711)
Steps:
- Add
orientationFetcher = useFetcher<{ success: boolean }>(). - Read the pending value: if
orientationFetcher.formDataexists, readstepIdandorientationfrom it. - In the
viewerStepsmemo (line 322), replace that step'sorientationwith the pending value. This is the optimistic display. - Add
onTurnBuild(stepId, turn):- Read the pose with
playerRef.current?.captureCameraPose(). If it is null, show the same toast asonSetCamera. - Find the step's resolved orientation with
resolveOrientations(viewerSteps). - Compute
next = turnOrientation(current, turn, pose). - Find the orientation the step gets from earlier steps: resolve the steps with this step's
orientationset tonull. - If
nextissameOrientationto that inherited value, postnull. Else postnext.
- Read the pose with
- Post with
orientationFetcher.submit. SendstepIdandorientation(JSON) topath.to.assemblyInstructionStepMotion(id, stepId). - Add
onResetOrientation(stepId). It postsorientationas the stringnull. - Pass the handlers to
AssemblyInstructionPropertiesas one groupedorientationprop (BuildOrientationControls:onTurn,onReset,isSaving). In the final code,useBuildOrientation(ui/Assemblies/useBuildOrientation.ts) owns the fetcher, steps 1–6 and this object.$id.tsxonly calls the hook. - Thread the
orientationprop throughAssemblyInstructionPropertiestoStepForm. Do not pass it toAssemblySubAssemblyProperties.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: the motion fetcher and its pending-save logic. Keep the orientation on its own fetcher.
Task 6: Add the Orientation row to the step's Playback panel
Depends on: Task 5 Files:
- Modify:
apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx— the row inStepForm - Modify:
docs/content/src/glossary/terms.ts— the termassembly-build-orientation - Copy from (precedent): the Camera
PlaybackRowinStepForm(around line 751) and theassembly-step-cameraglossary term
Steps:
- Add the glossary term
assembly-build-orientationnext toassembly-step-camera. Copy its shape. Definition: "The way the whole build is turned on a step, for example flipped to fit parts on its underside. Later steps of the same build keep it until a step turns the build again." - In
StepForm, computeresolved = useMemo(() => resolveOrientations(viewerSteps), [viewerSteps]). Take the entry at this step's index. - Set
ownsOrientation = entry.sourceStepId === step.id. - Set
turned = !sameOrientation(entry.orientation, IDENTITY_ORIENTATION). - Choose the value text:
- If
ownsOrientation:<Trans>Turned</Trans>. - Else if
turned:<Trans>Same as step {number}</Trans>, with the number fromsubPlan.get(entry.sourceStepId)?.number. - Else:
<Trans>Upright</Trans>.
- If
- Add the
PlaybackRowafter the Camera row. UseLabelWithHelp termId="assembly-build-orientation"with the label<Trans>Orientation</Trans>. - If
!isDisabled, render anHStackof 4 icon buttons and Reset:- Use
IconButtonfrom@carbon/react,variant="ghost",size="sm". Grep an existingIconButtonuse inapps/erp/app/modules/production/ui/Assemblies/and copy its props. - Labels and tooltips: t
Tip forward, tTip back, tTurn left, tTurn right. - Icons from
react-icons/lu:LuArrowUpFromLine,LuArrowDownToLine,LuRotateCcw,LuRotateCw. Check that each one exists innode_modules/react-icons/lu/index.d.tsfirst. - Each button calls
onTurnBuild(step.id, turn)and hasisDisabled={isSavingOrientation}. - If
ownsOrientation, add a ghostButton<Trans>Reset</Trans>that callsonResetOrientation(step.id).
- Use
If LabelWithHelp rejects the new term id at typecheck, STOP and report how term ids are typed.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
pnpm exec biome check apps/erp/app/modules/production/ui/Assemblies apps/erp/app/routes/x+/assembly+ packages/viewer/src docs/content/src/glossary/terms.ts
# Expected: no errors
Out of scope: the sub-assembly header panel and the step list. The spec puts the row only in StepForm.
Task 7: Pass the orientation to the MES player
Depends on: Tasks 1, 2 Files:
- Modify:
apps/mes/app/services/operations.service.ts— the select at line 664 - Modify:
apps/mes/app/components/AssemblyView.tsx— thestepstype andtoViewerStep - Copy from (precedent):
hiddenComponentNodeIdsin the same two files
Steps:
- Add
orientationto the select string aftercamera. - Add
orientation: Json | nullto theAssemblyPlayback["steps"]type. - In
toViewerStep, setorientation: isOrientation(step.orientation) ? step.orientation : null. ImportisOrientationfrom@carbon/viewer.
Verify:
pnpm exec turbo run typecheck --filter=mes
# Expected: exit 0
Out of scope: MES authoring. The MES only plays the orientation.
Task 8: Update the docs, AGENTS.md files, catalogs and MCP digest
Depends on: Task 6 Files:
- Modify:
docs/content/docs/reference/assembly-instructions.mdx— the Orientation field - Modify:
packages/viewer/AGENTS.md— the orientation concept and the new exports - Modify:
apps/erp/app/modules/production/AGENTS.md— theorientationcolumn in the data model row - Modify:
packages/locale/locales/*/erp.po— by extract only - Modify:
apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json— bygenerate:mcponly, if it changes - Copy from (precedent): the Camera and Motion field text in the same
.mdxfile
Steps:
- In the
.mdxreference, describe the Orientation field after the Camera field. Name the four buttons, Reset, the carry-forward rule and the sub-assembly rule. - In
packages/viewer/AGENTS.md, add an "Orientation" concept bullet. Say that the player shows it as a camera frame, and why. - In the production
AGENTS.md, addorientationto theassemblyInstruction/assemblyInstructionSteprow. - Run
pnpm lingui:extract. Leave the non-Englishmsgstrvalues empty. The user fills them. - Run
pnpm run generate:mcp.
Verify:
git diff --stat -- packages/locale/locales/en/erp.po apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
# Expected: erp.po changed; the digest changed or stayed the same without error
pnpm --filter docs typecheck
# Expected: exit 0
Out of scope: translations. The user fills them.
Task 9: Verify in the browser
Depends on: Tasks 1–8 Files:
- Modify:
.ai/playbooks/assembly-sub-assembly-motion-path.md— add the orientation checks, or create.ai/playbooks/assembly-build-orientation.md
Steps:
- Run
/teston the seeded satellite instruction, Draft Version 2 (db3o5hb3i0gh4nc6mmv0). - Use one
AGENT_BROWSER_SESSION. Restart it about every 40 screenshots. - Check each acceptance criterion of the spec, one by one.
- Check the viewcube risk: click a viewcube face on a turned step, then note what
updoes. - Record the results as a pass/fail table in the run record.
Verify:
grep -c "PASS" .ai/runs/2026-10-09-build-orientation.md
# Expected: one PASS line for each browser-checked acceptance criterion
Out of scope: the MES in the browser, unless an MES operation already links the instruction. The MES typecheck and the shared player cover it.