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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
docs(ai): build-orientation spec and plan, specs moved to implemented, playbook and viewcube lesson
aashu62819748e900
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 4481534051..ff06a33468 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3383,3 +3383,13 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf**Rule:** Set `AGENT_BROWSER_SESSION` to the worktree's own name, `agent-browser close` and reopen after ~40 shots, and reload the login page once if Continue stays disabled. Drive the canvas with `mouse move/down/up`, not `click`. Radix menus ignore synthetic clicks there — move the mouse off the menu and use the arrow keys plus Enter.**Applies to:** browser verification of `packages/viewer` features in the ERP editor; `.ai/playbooks/assembly-sub-assembly-motion-path.md`.++## drei GizmoHelper resets camera.up after a viewcube click++**Context:** The assembly player shows a step's build orientation by rolling the camera (`camera.up` = the bench's up in the model frame, `packages/viewer/src/orientation.ts`).++**Problem:** drei's `GizmoHelper` writes `camera.up` on every frame of a face-click tween and resets it to the value it saw at mount when the tween ends (`core/GizmoHelper.js`). After one viewcube click the build stood upright again, and every later turn started from the wrong up.++**Rule:** Do not patch drei. Anything that owns `camera.up` must re-assert it in its own frame loop whenever it drifts outside its own animation.++**Applies to:** `packages/viewer/src/useBuildFrame.ts` (its `useFrame`), any code that sets `camera.up` under `GizmoHelper` or `OrbitControls`.diff --git a/.ai/plans/2026-10-09-build-orientation.md b/.ai/plans/2026-10-09-build-orientation.mdnew file mode 100644index 0000000000..d8c380c36e--- /dev/null+++ b/.ai/plans/2026-10-09-build-orientation.md@@ -0,0 +1,316 @@+# 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.md` are the source of truth. Later changes moved the ERP wiring into the `useBuildOrientation` and `useStepMotionEditor` hooks, 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+- [x] Task 1: Add the `orientation` column and regenerate the types+- [x] Task 2: Add the pure orientation module to the viewer, with tests+- [x] Task 3: Show the orientation in the player as a camera frame+- [x] Task 4: Save the orientation through the motion route+- [x] Task 5: Wire the turn and Reset handlers in the assembly route+- [x] Task 6: Add the Orientation row to the step's Playback panel+- [x] Task 7: Pass the orientation to the MES player+- [x] Task 8: Update the docs, AGENTS.md files, catalogs and MCP digest+- [x] 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.ts` and the other generated files — regenerated, never hand-edited+- Copy from (precedent): `packages/database/supabase/migrations/20260925063121_assembly-step-hidden-components.sql`++**Steps:**+1. Run `pnpm db:migrate:new assembly-step-orientation`.+2. Write this SQL into the new file:+ ```sql+ -- 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;+ ```+3. Run `pnpm db:migrate`.+4. 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:**+```bash+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` — add `orientation?: Quat | null` to `AssemblyStep`, 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:**+1. Start the file with the AGPL SPDX header, as in `subassembly.ts`.+2. Export `type BuildTurn = "tipForward" | "tipBack" | "turnLeft" | "turnRight"`.+3. Export `IDENTITY_ORIENTATION: Quat = [0, 0, 0, 1]`.+4. Export `isOrientation(value: unknown): value is Quat`. It accepts 4 finite numbers with a length within 1e-3 of 1.+5. Export `sameOrientation(a: Quat, b: Quat): boolean`. It compares `|dot(a, b)| > 1 - 1e-6`, so `q` and `-q` match.+6. Export `snapOrientation(q: Quat): Quat`. Build the rotation matrix with three's `Matrix4`. Round each entry to -1, 0 or 1. Convert the matrix back with `Quaternion.setFromRotationMatrix`.+7. Export `upForOrientation(q: Quat): Vec3`. It returns `inverse(q) · (0, 0, 1)`.+8. Export `resolveOrientations(steps)`. Each step has the shape `Pick<AssemblyStep, "id" | "orientation" | "parentStepId" | "usedInStepId" | "isSubAssembly">`. The function returns `{ orientation: Quat; sourceStepId: string | null }[]` in step order:+ 1. Keep a `Map<string | null, { orientation; sourceStepId }>`, keyed by `worldOf(steps, step.id)` from `subassembly.ts`.+ 2. If `isOrientation(step.orientation)`, set the map entry of the step's build to `{ step.orientation, step.id }`.+ 3. Push the build's entry, or `{ IDENTITY_ORIENTATION, null }` when the build has none.+9. Export `turnOrientation(current: Quat, turn: BuildTurn, view: { position: Vec3; target: Vec3 }): Quat`:+ 1. Get the camera direction `d = position - target` in the model frame. Turn it into the bench frame: `d_b = current · d`.+ 2. Set `h` to `d_b` with `z = 0`, then normalize it.+ 3. If the length of `h` is below 1e-6, the camera looks straight down. Use `h = (0, -1, 0)`, the CAD front.+ 4. For turnLeft, use axis (0,0,1) and angle −π/2. For turnRight, use axis (0,0,1) and +π/2.+ 5. For tipForward, use axis `Z × h` and +π/2. For tipBack, use the same axis and −π/2.+ 6. Return `snapOrientation(R · current)`.+10. Write tests in `orientation.test.ts`:+ 1. `resolveOrientations`: a main-build step sets a flip. The next main step inherits it with `sourceStepId` of the setter.+ 2. `resolveOrientations`: a sub-assembly member after that flip gets `IDENTITY_ORIENTATION` and `sourceStepId: null`. Use the row shapes of `subassembly.test.ts`.+ 3. `resolveOrientations`: a turn on a sub-assembly member does not change the next main-build step.+ 4. `turnOrientation`: camera at (0, -10, 0), target at the origin, `tipForward` from 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.+ 5. `turnOrientation`: `turnLeft` then `turnRight` gives a result `sameOrientation` to identity.+ 6. `turnOrientation`: `tipForward` twice gives a 180° turn. The model's top points to (0, 0, -1) in the bench frame.+ 7. `snapOrientation`: a quaternion 1° off a right angle snaps exactly to that right angle.+ 8. `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:**+```bash+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 `useFrame` at `AssemblyPlayer.tsx:2048` and the per-step framing effect at `:2093`++**Steps:**+1. In `AssemblyPlayer`, compute `orientations = useMemo(() => resolveOrientations(steps), [steps])`.+2. Pass `orientation={orientations[activeStepIndex]?.orientation ?? IDENTITY_ORIENTATION}` to `AssemblyScene`. Add the prop to its type.+3. In `AssemblyScene`, add `frameRef = useRef<{ applied: Quaternion; from: Quaternion; to: Quaternion; start: number } | null>(null)`.+4. Add an effect on `[orientation, controls]`:+ 1. If `frameRef.current` is null, snap. Rotate the camera offset about `controls.target` by `inverse(orientation)`. Set `camera.up` to `upForOrientation(orientation)`. Store `applied = from = to = orientation`. Call `controls.update()`.+ 2. Else, if `to` equals `orientation` (`sameOrientation`), do nothing.+ 3. Else set `from = applied`, `to = orientation`, `start = performance.now()`.+5. In the transition `useFrame`, before the desired-pose code:+ 1. If `applied` is not `to`, compute `t = ease(clamp((now - start) / 900))` with a cubic ease-in-out.+ 2. Set `next = from.clone().slerp(to, t)`.+ 3. Set `delta = next⁻¹ · applied`. Apply `delta` to the camera offset from `controls.target`, and to `camera.up`.+ 4. Set `applied = next`. Call `controls.update()`.+ 5. If `t < 1`, return. The desired-pose approach waits for the end of the turn.+6. In the controls `onStart` handler, finish a turn at once. Set `applied` to `to` through the same `delta` step.+7. In the framing effect, replace `camera.up.clone()` at line 2224 with `new Vector3(...upForOrientation(orientation))`.+8. Add `orientation.join(",")` to `framingKey` and `orientation` to the effect deps.+9. Make `captureCameraPose` return 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:**+```bash+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`, and `orientation` in `assemblyInstructionStepMotionValidator`+- Modify: `apps/erp/app/modules/production/production.service.ts` — `updateAssemblyStepMotion` and `toViewerStep`+- Modify: `apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx` — pass `orientation`+- Copy from (precedent): the `camera` field in the same three places++**Steps:**+1. In `production.models.ts`, export `orientationSchema = unitQuaternion`. Place it after `cameraSchema`.+2. Add `orientation: jsonField(orientationSchema.nullable().optional())` to `assemblyInstructionStepMotionValidator`.+3. Add `orientation?: z.infer<typeof orientationSchema> | null` to the `updateAssemblyStepMotion` data type.+4. Spread `orientation` into the update when it is not `undefined`, as `camera` is spread.+5. Extend the doc comment: `orientation: null` clears the step's own orientation.+6. In `toViewerStep`, parse `step.orientation` with `orientationSchema.safeParse`. Map a failure to `null`.+7. In the route action, pass `orientation: validation.data.orientation`. Add `hasOrientation` to the log call.++**Verify:**+```bash+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 to `StepForm`+- Copy from (precedent): `onSetCamera` / `onClearCamera` in `$id.tsx` (around line 711)++**Steps:**+1. Add `orientationFetcher = useFetcher<{ success: boolean }>()`.+2. Read the pending value: if `orientationFetcher.formData` exists, read `stepId` and `orientation` from it.+3. In the `viewerSteps` memo (line 322), replace that step's `orientation` with the pending value. This is the optimistic display.+4. Add `onTurnBuild(stepId, turn)`:+ 1. Read the pose with `playerRef.current?.captureCameraPose()`. If it is null, show the same toast as `onSetCamera`.+ 2. Find the step's resolved orientation with `resolveOrientations(viewerSteps)`.+ 3. Compute `next = turnOrientation(current, turn, pose)`.+ 4. Find the orientation the step gets from earlier steps: resolve the steps with this step's `orientation` set to `null`.+ 5. If `next` is `sameOrientation` to that inherited value, post `null`. Else post `next`.+5. Post with `orientationFetcher.submit`. Send `stepId` and `orientation` (JSON) to `path.to.assemblyInstructionStepMotion(id, stepId)`.+6. Add `onResetOrientation(stepId)`. It posts `orientation` as the string `null`.+7. Pass the handlers to `AssemblyInstructionProperties` as one grouped `orientation` prop (`BuildOrientationControls`: `onTurn`, `onReset`, `isSaving`). In the final code, `useBuildOrientation` (`ui/Assemblies/useBuildOrientation.ts`) owns the fetcher, steps 1–6 and this object. `$id.tsx` only calls the hook.+8. Thread the `orientation` prop through `AssemblyInstructionProperties` to `StepForm`. Do not pass it to `AssemblySubAssemblyProperties`.++**Verify:**+```bash+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 in `StepForm`+- Modify: `docs/content/src/glossary/terms.ts` — the term `assembly-build-orientation`+- Copy from (precedent): the Camera `PlaybackRow` in `StepForm` (around line 751) and the `assembly-step-camera` glossary term++**Steps:**+1. Add the glossary term `assembly-build-orientation` next to `assembly-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."+2. In `StepForm`, compute `resolved = useMemo(() => resolveOrientations(viewerSteps), [viewerSteps])`. Take the entry at this step's index.+3. Set `ownsOrientation = entry.sourceStepId === step.id`.+4. Set `turned = !sameOrientation(entry.orientation, IDENTITY_ORIENTATION)`.+5. Choose the value text:+ 1. If `ownsOrientation`: `<Trans>Turned</Trans>`.+ 2. Else if `turned`: `<Trans>Same as step {number}</Trans>`, with the number from `subPlan.get(entry.sourceStepId)?.number`.+ 3. Else: `<Trans>Upright</Trans>`.+6. Add the `PlaybackRow` after the Camera row. Use `LabelWithHelp termId="assembly-build-orientation"` with the label `<Trans>Orientation</Trans>`.+7. If `!isDisabled`, render an `HStack` of 4 icon buttons and Reset:+ 1. Use `IconButton` from `@carbon/react`, `variant="ghost"`, `size="sm"`. Grep an existing `IconButton` use in `apps/erp/app/modules/production/ui/Assemblies/` and copy its props.+ 2. Labels and tooltips: t`Tip forward`, t`Tip back`, t`Turn left`, t`Turn right`.+ 3. Icons from `react-icons/lu`: `LuArrowUpFromLine`, `LuArrowDownToLine`, `LuRotateCcw`, `LuRotateCw`. Check that each one exists in `node_modules/react-icons/lu/index.d.ts` first.+ 4. Each button calls `onTurnBuild(step.id, turn)` and has `isDisabled={isSavingOrientation}`.+ 5. If `ownsOrientation`, add a ghost `Button` `<Trans>Reset</Trans>` that calls `onResetOrientation(step.id)`.++If `LabelWithHelp` rejects the new term id at typecheck, STOP and report how term ids are typed.++**Verify:**+```bash+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` — the `steps` type and `toViewerStep`+- Copy from (precedent): `hiddenComponentNodeIds` in the same two files++**Steps:**+1. Add `orientation` to the select string after `camera`.+2. Add `orientation: Json | null` to the `AssemblyPlayback["steps"]` type.+3. In `toViewerStep`, set `orientation: isOrientation(step.orientation) ? step.orientation : null`. Import `isOrientation` from `@carbon/viewer`.++**Verify:**+```bash+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` — the `orientation` column 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` — by `generate:mcp` only, if it changes+- Copy from (precedent): the Camera and Motion field text in the same `.mdx` file++**Steps:**+1. In the `.mdx` reference, describe the Orientation field after the Camera field. Name the four buttons, Reset, the carry-forward rule and the sub-assembly rule.+2. In `packages/viewer/AGENTS.md`, add an "Orientation" concept bullet. Say that the player shows it as a camera frame, and why.+3. In the production `AGENTS.md`, add `orientation` to the `assemblyInstruction` / `assemblyInstructionStep` row.+4. Run `pnpm lingui:extract`. Leave the non-English `msgstr` values empty. The user fills them.+5. Run `pnpm run generate:mcp`.++**Verify:**+```bash+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:**+1. Run `/test` on the seeded satellite instruction, Draft Version 2 (`db3o5hb3i0gh4nc6mmv0`).+2. Use one `AGENT_BROWSER_SESSION`. Restart it about every 40 screenshots.+3. Check each acceptance criterion of the spec, one by one.+4. Check the viewcube risk: click a viewcube face on a turned step, then note what `up` does.+5. Record the results as a pass/fail table in the run record.++**Verify:**+```bash+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.diff --git a/.ai/playbooks/assembly-sub-assembly-motion-path.md b/.ai/playbooks/assembly-sub-assembly-motion-path.mdindex 4fcf40cd90..051fb6383f 100644--- a/.ai/playbooks/assembly-sub-assembly-motion-path.md+++ b/.ai/playbooks/assembly-sub-assembly-motion-path.md@@ -16,3 +16,13 @@ Route: /x/assembly/:id — seeded "ESPA Smallsat — Integration Sequence" (Publ## Notes- The 3D page grows the renderer to 3 GB+ after ~40 screenshots and snapshots hang — `agent-browser close`, reopen, log in again.- A "Failed to fetch" route error after a long session is the dev server dropping a revalidation; "Try again" recovers.++## Build orientation (tested 2026-10-09)+1. Select a step through "Search steps", then click the row's title element. The Orientation row is the last Playback row.+2. Click the turn buttons through `aria-label` ("Flip over", "Tip toward you", "Tip away from you", "Spin left", "Spin right"). They stay disabled while each save runs, so wait about 2.5 s between clicks.+3. Read the row text: "Upright", "Upside down" or "On its side". An inherited pose reads "Upside down, from step N" or "On its side, from step N". Reset shows only on the step that set the orientation.+4. Read the Camera row. If the step had no saved view, a turn that leaves the build turned also saves the current view, so the row reads "Saved view". A turn back to the inherited orientation keeps that view. "Clear" returns the step to automatic framing. A step with only a planner hint (`camera` = `{"source":"plan",…}`) reads "Automatic" and shows no Clear.+5. Check the DB (the Draft made in step 2 of the section above): `select s."sortOrder", s.orientation, s.camera from "assemblyInstructionStep" s join "assemblyInstruction" i on i.id = s."assemblyInstructionId" and i."companyId" = s."companyId" where i.name = 'ESPA Smallsat — Integration Sequence' and i.status = 'Draft' and s.orientation is not null order by s."sortOrder"`.+6. The viewer's prev and next arrows sit at about (397, 486) and (1229, 486) at 1600×1000. Step from 7 to 8 and take screenshots at about 0.45 s to catch the turn mid-way.+7. The viewcube corner sits at about (1205, 165).+8. Reset every turned step at the end, and Clear the views the turns saved. Leave the DB with 0 orientations.diff --git a/.ai/specs/2026-10-08-sub-assembly-motion-path.md b/.ai/specs/implemented/2026-10-08-sub-assembly-motion-path.mdsimilarity index 92%rename from .ai/specs/2026-10-08-sub-assembly-motion-path.mdrename to .ai/specs/implemented/2026-10-08-sub-assembly-motion-path.mdindex c34a0f7da6..7e5e156726 100644--- a/.ai/specs/2026-10-08-sub-assembly-motion-path.md+++ b/.ai/specs/implemented/2026-10-08-sub-assembly-motion-path.md@@ -73,9 +73,9 @@ There's no schema change. Every `assemblyInstructionStep` row already has `"moti### ERP UI (`apps/erp/.../Assemblies`)-- **Using step's panel** (`AssemblyInstructionProperties.tsx`, Playback section at `:644-720`): under the step's own Motion row, one row per sub-assembly this step carries in, labelled "{Sub-assembly name} path". The row shows "Automatic" or "Custom path" and has an `Edit Path` / `Done Editing Path` button and a `Reset` action that sets `none`.+- **Using step's panel** (`AssemblyInstructionProperties.tsx`, the Playback section of `StepForm`; the row is `AssemblySubAssemblyPathRow.tsx`): under the step's own Motion row, one row per sub-assembly this step carries in, labelled "{Sub-assembly name} path". The row shows "Automatic" or "Custom path" and has an `Edit Path` / `Done Editing Path` button and a `Reset` action. Reset posts `reset`, which puts back the header's motion from before the first drawn path (`warnings.plannedMotion`, else `none`).- **Unused sub-assembly's panel** (`AssemblySubAssemblyProperties.tsx`): the same row when `usedInStepId` is null. That sub-assembly joins at its own row, and `subassembly.ts:187` already puts it in its own `carriesIn`.-- **Route** (`apps/erp/app/routes/x+/assembly+/$id.tsx:613-680`): `onEditMotion(stepId, { unitHeaderId? })`. Saving goes through the existing `$id.steps.motion.$stepId` action with the header id. That action calls `updateAssemblyStepMotion`, which updates by id, so headers work with no new route.+- **Route** (`apps/erp/app/routes/x+/assembly+/$id.tsx`, through `ui/Assemblies/useStepMotionEditor.ts`): `motionEditing.onEdit(stepId, unitHeaderId?)`. Saving goes through the existing `$id.steps.motion.$stepId` action with the header id. That action calls `updateAssemblyStepMotion`, which updates by id, so headers work with no new route.- Every new string uses Lingui `<Trans>`/`t`. There's a new help term for the unit path row, next to the existing `assembly-step-motion` term.### MES@@ -106,7 +106,7 @@ There's no MES-specific code beyond the `playerMotionTypes` allow-list. MES alre6. A rigid-group step rotated at a waypoint turns as one body about its centroid. Parts keep their positions relative to each other.7. Paths with no rotation are saved as `linear`/`L` (check the row's `motion` JSON). Rotated ones are saved as `waypoints`.8. The MES operation view plays the same unit paths and rotations as the ERP editor.-9. Reset on a unit path sets the header's `motion` back to `none`, and playback returns to the fallback.+9. Reset on a unit path puts back the header's motion from before the first drawn path (`none` for a header the planner never moved), and playback returns to the fallback.10. `npm run typecheck` passes and viewer unit tests cover `waypoints` keyframes, the round-trip, and unit sequencing timing.## Verification (2026-10-08)diff --git a/.ai/specs/implemented/2026-10-09-build-orientation.md b/.ai/specs/implemented/2026-10-09-build-orientation.mdnew file mode 100644index 0000000000..2c43cac4eb--- /dev/null+++ b/.ai/specs/implemented/2026-10-09-build-orientation.md@@ -0,0 +1,307 @@+# Per-step build orientation++> Status: implemented (built and browser-tested)+> Author: Claude (feature pipeline, autonomous mode)+> Date: 2026-10-09++## TLDR++An author can turn the whole build on a step of an assembly instruction. For+example, they can flip the build to fit parts on its underside. The+orientation stays on the later steps of the same build until a step sets a new+one. Playback shows the turn as an animation, so the operator sees the build+turn over the way it turns over at the bench. The author sets it with five+turn buttons in a new Orientation row of the step's Playback panel: Flip over+turns the build 180°, and the other four turn it 90°. The ERP editor and the+MES player show the same turn.++## Overview diagram++```mermaid+sequenceDiagram+ participant A as Author+ participant P as Playback panel+ participant R as Motion route+ participant D as assemblyInstructionStep+ participant V as AssemblyPlayer+ A->>P: Click Flip over+ P->>V: Read the live camera pose+ P->>R: Post the orientation, plus the pose if turned with no saved view+ R->>D: Write orientation (and camera)+ D-->>V: Steps with orientation+ V->>V: Animate the turn under a still camera+```++## Problem Statement++The author can show a step from any camera angle, and can turn the part that+goes in. The author cannot turn the build that the part goes into.++| Tool today | What it does | What it cannot do |+|------------|--------------|-------------------|+| Camera, "Use Current View" | Looks at the build from any side, below included | Turn the build. `OrbitControls` keeps `camera.up` fixed (`AssemblyViewer.tsx:81`), so the build always stands upright on screen |+| Waypoint rotation | Turns the incoming part along its path | Turn the base that the part goes into |++So a step that fits a part on the underside shows the build from below,+hanging over the viewer. At the bench, the person flips the build and fits the+part from above. The two components cannot be shown together at the angle the+person works at.++Example: a demo assembly has a base plate. Step 1 fits a bracket on top. Step 2+fits a cover under the plate. Today step 2 shows the plate from below. With+this feature, step 2 flips the plate over, and the cover drops in from above.++## Proposed Solution++1. Add a nullable `orientation` column to `assemblyInstructionStep`. It holds+ a quaternion `[x, y, z, w]`. Null means "same as the previous step in this+ build".+2. Add a pure module `packages/viewer/src/orientation.ts`. It resolves the+ orientation of each step, and it applies one turn.+3. Make the player show a step's orientation as a camera frame. The player+ animates the turn when the orientation changes between steps.+4. Add an Orientation row to the step's Playback panel in the ERP. It has five+ turn buttons and a Reset button.+5. Pass the column to the MES player.++### How the player shows an orientation++An orientation `Q` turns the model frame into the bench frame. The bench frame+is Z-up, like the model. The player does not turn the model. It moves the+camera instead:++- `camera.up` becomes `Q⁻¹ · (0, 0, 1)`.+- When the orientation changes from `Q0` to `Q1`, the player turns the camera+ about the build's center: the center of the whole-assembly bounds. It moves+ the camera through the frames `Q(t) = slerp(Q0, Q1, t)` over about 0.9+ seconds. On each frame it applies `Q(t)⁻¹ · Q(t-1)` to the camera position,+ to the controls target and to `camera.up`.+- The pivot is the build's center, not the controls target. A turn about the+ target swung an off-center build round in an arc.+- The camera stays still in the bench frame during the turn. So on screen the+ build turns in place, and the camera does not move.+- A turn does not re-frame the step. The framing key leaves out the+ orientation, so the camera stays where the turn left it.+- When the active step moves to another build (the main build to a+ sub-assembly, or back), the player snaps the camera frame to the new+ build's orientation with no turn animation. The two builds are on different+ benches, so nobody turns one into the other.+- When the scene unmounts, the player clears its turn state and puts+ `camera.up` back to Z-up. The camera outlives a remounted scene, so the next+ scene starts from an upright frame.++Why the camera and not the model: the motion code works in world space.+`worldPoseOf` and `nodeTracks` (`motion.ts`), `seatedBoundsCenter`, the path+editor and the box select all read `matrixWorld` or the graph bounds. If the+player turned a root node, each of them would need a frame change. A turned+camera gives the same picture, because the key light follows the camera+(`HeadLight`, `AssemblyViewer.tsx`).++The motion data and the plan hint stay in the model frame. A saved view uses the bench frame:++| Data | Frame | Effect of an orientation |+|------|-------|--------------------------|+| Step motion and waypoints | Model | None. The path turns with the build on screen |+| Saved view (`CameraPose`) | Bench | The view stays where the viewer stands. A turn of the step turns the build under it |+| Plan hint (`direction`) | Model | Used only on an upright build |+| Live framing on a turned build with no saved view | Bench | The camera keeps its direction on the bench. Only the target and the distance follow the step. It does not re-frame from above |+| Live AABB framing on an upright build | Model | The candidate rings go around the step's `up`, not `camera.up` |++### Resolving each step's orientation++`resolveOrientations(steps)` walks the steps in play order. It keeps one+current orientation for each build:++1. Find the build of the step with `worldOf(steps, stepId)`. The main build is+ `null`. A sub-assembly member gets its header id.+2. If the step has an `orientation`, make it the current orientation of that+ build.+3. Give the step the current orientation of its build, with the id of the step+ that set it.++Each build starts with no turn (the identity quaternion). A person builds a+sub-assembly on its own bench, so it starts upright. A finished sub-assembly joins+the main build in the main build's orientation.++### Turning from the Playback panel++Each button turns the build about an axis in the bench frame:++| Button | Axis | Angle |+|--------|------|-------|+| Flip over | the square axis nearest `Z × h` | 180° |+| Tip toward you | the square axis nearest `Z × h` | +90° |+| Tip away from you | the square axis nearest `Z × h` | −90° |+| Spin left | Z (bench up) | −90° |+| Spin right | Z (bench up) | +90° |++`h` is the horizontal direction from the target to the camera, in the bench+frame. "Tip toward you" moves the top of the build toward the viewer. A+square axis (±X or ±Y) keeps every turn a clean right angle from a slanted+view. If the camera looks straight down, `h` is the CAD front `(0, -1, 0)`.++`turnOrientation(current, turn, pose)` returns `R · current`. Then it snaps+the result to the nearest of the 24 right-angle orientations, so repeated+turns do not drift. If the result equals the orientation the step gets from+the previous step, the panel saves `null`. So a turn and its opposite turn+leave the orientation as it was.++The same post can also save a view. `useBuildOrientation` (ERP) applies one+rule:++1. If the turn leaves the step turned (the saved orientation is not `null`),+ and the step has no saved view, post the live camera pose as `camera`.+2. Otherwise, post the orientation only.++A plan hint (`{ source: "plan" }`) does not count as a saved view. Only a+manual pose (`position`, `target`, no `source`) counts. `isSavedView`+(`@carbon/viewer`) makes this check for the turn rule and for the Camera row.+The pinned view makes playback land on what the author saw. A turn back to the inherited+orientation keeps the pinned view. Reset on the Orientation row posts+`orientation: null` only. "Clear" on the Camera row returns the step to+automatic framing.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Turn controls | Five buttons in screen terms: Flip over (180°), Tip toward you, Tip away from you, Spin left, Spin right (90° each). They sit on their own line under the row | The user chose screen terms. A UX review added Flip over, the most common need, and plain names |+| Tip axis | The bench axis that runs most nearly left-right on screen | A slanted view gave a slanted axis, and the snap then jumped to an unexpected pose |+| Camera after a turn | Stays still; the turn does not re-frame the step | Re-framing to the model-frame plan hint swung the camera after the build and undid the turn on screen |+| Turn pivot | The center of the whole-assembly bounds | A turn about the controls target swung an off-center build round in an arc |+| View after a turn | A turn that leaves the step turned saves the live view, unless the step has a saved view | Playback then lands on what the author saw. A saved view is never overwritten |+| Turned step with no saved view | Keeps the camera's direction on the bench | A re-aim by geometry undid a spin and showed a pose the author never chose |+| Move between builds | Snap to the new build's orientation, no animation | The main build and a sub-assembly are on different benches |+| Row text | The pose: Upright, Upside down, On its side, with "from step N" when inherited | "Turned" did not say how the build sits |+| Chain per build | Main build and each sub-assembly have their own chain. A sub-assembly starts upright | The user chose it. The player builds a sub-assembly on its own (`subassembly.ts`) |+| Storage | New nullable JSONB column `orientation` | The user chose it. `warnings` holds planner output, and a re-plan rewrites it |+| Absolute or relative value | Absolute (model to bench) | A later step stays correct when an earlier step changes. Reset is a `null` write |+| Mechanism | Camera frame (`camera.up` and offset), not a turned root node | The motion, editor and box-select code all work in world space. The picture is the same |+| Turn animation | Slerp over 0.9 s with ease-in-out, then the step's framing | The operator sees the build turn over, as at the bench |+| Free camera mode | The turn still plays | The orientation is a fact of the step, not a framing choice |+| Viewcube | Shows the model axes, so "Bottom" can be at the top. A face click looks at that face and keeps the build turned | This matches a CAD viewer. See Risks for the `camera.up` reset |+| Optimistic display | The route reads the pending value from the fetcher's `formData` | No `useState` copy of loader data (`coding-conventions.md`) |+| Double clicks | The turn buttons are disabled while the save is in flight | Two posts in flight can land in the wrong order |+| Multi-tenancy (heuristic 1) | No new table. The column is on a table that already has `companyId` | — |+| Service shape (heuristic 2) | `updateAssemblyStepMotion` takes one more optional field. It returns `{ data, error }` as before | — |+| Atomic path save | `updateAssemblyStepMotion` takes the Kysely handle and writes each patch as one `UPDATE`. A path edit and a Reset read `motion` and `warnings` from the row they write | A read and a separate write let a drag save and a Reset that reach the server together lose `warnings.plannedMotion`. Reset then put back the wrong path |+| Camera row value | "Saved view" only for a manual view. A plan hint reads "Automatic" and has no Clear | A plan hint only aims the automatic framing. Clear on it would delete the planner's view direction |+| RLS (heuristic 3) | No change. The existing `assemblyInstructionStep` policies cover the column | — |+| Permissions (heuristic 4) | The motion route keeps `update: "production"` | — |+| Form pattern (heuristic 5) | The route validates with `assemblyInstructionStepMotionValidator` | The viewer buttons post with a fetcher, like the camera buttons |+| Module layout (heuristic 6) | Validator in `production.models.ts`, service in `production.service.ts` | — |+| Backward compatibility (heuristic 7) | The new column is nullable. Old steps play as before | Version copy carries the column through `...rest` (`copyAssemblyInstructionAsVersion`) |++## Data Model Changes++One migration, `assembly-step-orientation`:++```sql+-- The build's orientation from this step on: a unit quaternion [x, y, z, w]+-- that turns the model frame into the bench frame. NULL = same as the+-- previous step in the same build (a sub-assembly starts upright).+ALTER TABLE "assemblyInstructionStep"+ ADD COLUMN IF NOT EXISTS "orientation" JSONB;+```++No new table, so no RLS or index change. Run `pnpm db:migrate`, then+`pnpm run generate:types`.++The demo datasets build their INSERTs from `information_schema`+(`datasets/sql.ts`). A nullable column needs no dataset change.++## API / Service Changes++| Place | Change |+|-------|--------|+| `packages/viewer/src/types.ts` | `AssemblyStep.orientation?: Quat \| null` |+| `packages/viewer/src/orientation.ts` (new) | `BuildTurn`, `IDENTITY_ORIENTATION`, `resolveOrientations`, `upForOrientation`, `turnOrientation`, `snapOrientation`, `sameOrientation`, `isOrientation` |+| `packages/viewer/src/index.ts` | Export the new module |+| `packages/viewer/src/AssemblyPlayer.tsx` | Resolve the active step's orientation. Animate the turn in the camera `useFrame`. Use the step's `up` in the framing effect |+| `production.models.ts` | `orientationSchema` (unit quaternion). `assemblyInstructionStepMotionValidator` gets `orientation` |+| `production.service.ts` | `updateAssemblyStepMotion` writes `orientation` when the caller sends it, in the same single `UPDATE` as the motion and camera patch. `toViewerStep` maps it |+| `$id.steps.motion.$stepId.tsx` | Pass `orientation` to the service. Pass `getDatabaseClient()` as the service's `db` |+| `ui/Assemblies/useBuildOrientation.ts` | The orientation fetcher, the pending orientation on the viewer steps, `onTurn`, `onReset`, `isSaving` |+| `ui/Assemblies/assembly-step-patch.ts` | `stepPatchFormData`, the one form body for the motion route (motion, camera, orientation, reset) |+| `ui/Assemblies/AssemblyOrientationRow.tsx` | The Orientation row: pose text, five turn buttons, Reset |+| `$id.tsx` (assembly route) | Builds the viewer steps and passes them through `useBuildOrientation` |+| `apps/mes/app/services/operations.service.ts` | Select `orientation` |+| `apps/mes/app/components/AssemblyView.tsx` | Map `orientation` through `isOrientation` |++The route posts `orientation` as JSON. The string `null` clears the value.++## UI Changes++The step's Playback panel gets an Orientation row under the Camera row. It+uses `PlaybackRow` and `LabelWithHelp` with a new glossary term+`assembly-build-orientation`.++| State | Value text | Buttons |+|-------|------------|---------|+| The build is upright | Upright | 5 turn buttons (Reset when this step set it) |+| The build is upside down | Upside down, or "Upside down, from step {number}" when inherited | 5 turn buttons (Reset when this step set it) |+| The build lies on a side | On its side, or "On its side, from step {number}" when inherited | 5 turn buttons (Reset when this step set it) |+| Instruction is not a Draft | The value text only | None |++The turn buttons are icon buttons on their own line, with a tooltip each:+Flip over, Tip toward you, Tip away from you, Spin left, Spin right. Reset+saves `null`, so the step takes the orientation of the previous step. The row+does not show on a sub-assembly header panel.++After a turn that leaves a step with no saved view turned, the Camera row+reads "Saved view".++The Camera row reads "Saved view" only for a manual view. A step with a plan+hint reads "Automatic", like a step with no camera, and the row offers no+Clear for it. "Use Current View" replaces the plan hint with a manual view.++All text uses Lingui. The non-English translations stay empty for the user to+fill.++## Acceptance Criteria++- [ ] On a Draft, the author selects a step with no saved view and clicks Flip over. The build turns over in place, the camera stays still, and the row reads "Upside down". The Camera row reads "Saved view".+- [ ] After a reload, the step still shows the build turned over.+- [ ] The next step of the same build reads "Upside down, from step {number}" and shows the build turned over.+- [ ] Reset on the turning step gives it the orientation of the step before it. Reset does not change the camera.+- [ ] Spin left, then Spin right, saves `null` for the orientation, and the Orientation row reads as before. The Camera row keeps the view that Spin left saved. "Clear" returns it to automatic.+- [ ] Playback from step 1 shows the turn as an animation at the turning step. The step's part then goes in along its path, turned with the build.+- [ ] A step with a saved view keeps that view after a turn, and the build turns under it.+- [ ] A later step of a turned build with no saved view keeps the camera's direction on the bench. It does not re-frame from above.+- [ ] Moving from a turned main-build step to a sub-assembly step shows the sub-assembly upright at once, with no turn animation.+- [ ] A sub-assembly member step starts upright, even after a main-build step that flips the build.+- [ ] A turn on a sub-assembly member does not change the main-build steps.+- [ ] New Version copies the orientation of every step.+- [ ] The MES player shows the same orientation for the step.+- [ ] `pnpm --filter @carbon/viewer test` passes, with tests for `resolveOrientations`, `turnOrientation` and `snapOrientation`.+- [ ] The viewer and ERP typecheck pass. Biome passes.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| The viewcube resets `camera.up` to Z when the author clicks a face (drei `GizmoHelper.js:73`) | Med | Confirmed in the browser. The player's frame loop sets `camera.up` back to the build's up after the tween |+| The hemisphere and back fill lights stay fixed in the model frame, so the turned build has slightly different shading | Low | The key light follows the camera. Accept it |+| An orbit during the turn fights the turn animation | Low | The player stops the turn when the user grabs the controls, as it does for the framing transition, and snaps to the target orientation |+| A turn while the camera looks straight down has no horizontal direction | Low | `turnOrientation` uses the CAD front `(0, -1, 0)` |+| A saved view taken before a turn now looks at the other side of the model | Low | This is the intent: the viewer stays put and the build turns. The author can take the view again |++## Open Questions++> HARD STOP: Do not proceed with implementation until these are answered.++- [x] Which controls turn the build? — **Answer:** buttons in screen terms. The user chose this. A later UX review renamed them and added Flip over: Flip over, Tip toward you, Tip away from you, Spin left, Spin right.+- [x] Does a sub-assembly share the main build's orientation? — **Answer:** no. Each build has its own chain, and a sub-assembly starts upright. The user chose this.+- [x] Where does the orientation live? — **Answer:** a new nullable `orientation` JSONB column. The user chose this.+- [x] Does the player turn the model or the camera? — **Autonomous:** the camera. The motion, editor and box-select code all work in world space (`motion.ts` `worldPoseOf`, `nodeTracks`; `seatedBoundsCenter`; box select). The picture is the same, because the key light follows the camera.+- [x] Does the turn play in free camera mode? — **Autonomous:** yes. The orientation belongs to the step, and the free mode only stops the per-step framing.+- [x] Do the saved view and the plan hint follow the build? — **Autonomous:** the plan hint is about the parts, so it stays in the model frame. The player uses it only on an upright build. The saved view does not follow the build. `captureCameraPose` stores it in the bench frame, so it stays where the viewer stands. The browser test showed why: a model-frame view swung the camera under the bench after a flip. Existing views come from upright steps, where the two frames are the same.++## Changelog++- 2026-10-13: Review fixes. `updateAssemblyStepMotion` writes each patch as one atomic `UPDATE`. The Camera row reads "Saved view" only for a manual view; a plan hint reads "Automatic" and has no Clear. `isSavedView`, `hasCustomMotion` and `isPlanFlagged` now live in `@carbon/viewer` only, and the MES player uses `isPlanFlagged` too.+- 2026-10-13: Spec brought in line with the code. The turn pivots about the build's center. A turned step with no saved view keeps the camera's bench direction. The straight-down fallback is the CAD front. A turn that leaves a step with no saved view turned also saves the view. A move between builds snaps to the new build's orientation, and the player resets `camera.up` on unmount. The ERP side moved into `useBuildOrientation`, `useStepMotionEditor`, `AssemblyOrientationRow` and the shared `stepPatchFormData`.+- 2026-10-09: UX review after user feedback ("it turns and then goes back"): no re-frame after a turn, square tip axes, a robust snap, Flip over, plain button names, pose wording, plan hints skipped on a turned build.+- 2026-10-09: Browser-test fixes: on a turned build the player does not use the plan hint, and it restores `camera.up` after a viewcube click. The test found a plan hint that looked from under the bench. The fix drops the plan hint on every turned build, and a turned build keeps the camera's direction on the bench.+- 2026-10-09: Saved views moved to the bench frame after the browser test (autonomous decision, see Open Questions).+- 2026-10-09: Created. The user resolved the controls, the chain per build and the storage. The camera mechanism, the free-mode turn and the model-frame views are autonomous decisions.