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(nav): spec and plan for a shared ERP/MES navigation rail
aashuf65cd249b11f
diff --git a/.ai/plans/2026-09-29-shared-nav-rail.md b/.ai/plans/2026-09-29-shared-nav-rail.mdnew file mode 100644index 0000000000..f50ba7e84f--- /dev/null+++ b/.ai/plans/2026-09-29-shared-nav-rail.md@@ -0,0 +1,484 @@+# Shared Nav Rail (ERP + MES) — implementation plan++**Spec / source:** `.ai/specs/2026-09-29-shared-nav-rail.md` (approved 2026-09-29)+**Research:** `.ai/research/shared-sidebar.md`+**Branch:** `feat/shared-sidebar` (worktree `/Users/aashu/work/carbon/carbon-feat-shared-sidebar`)++## Progress+- [x] Task 1: Create `NavRail` components in `@carbon/react` (+ tests, barrel export) — deviation: pure helpers live in `packages/react/src/utils/navRail.ts` and the test covers only them (importing `NavRail.tsx` under vitest pulls the hooks barrel → `@carbon/env`, which throws without server env; the markup render test was dropped)+- [x] Task 2: Mount `SidebarProvider` in the ERP layout+- [x] Task 3: Rebuild ERP `PrimaryNavigation` on `NavRail`+- [x] Task 4: Replace ERP mobile drawer with the shared rail drawer+- [x] Task 5: Move MES tool buttons to `NavRailButton`+- [x] Task 6: Rebuild MES `AppSidebar` on `NavRail`+- [x] Task 7: Extract Lingui strings+- [x] Task 8: Sync docs (AGENTS.md, carbon-design references)+- [ ] Task 9: End-to-end verification in the browser (ERP + MES) — PARTIAL: ERP collapsed 56px / hover 208px / leave 56px / ⌘B pin+unpin verified; OrbStack (Docker) quit mid-run, rest blocked. A "Maximum update depth exceeded" client warning appeared in the ERP log right after a `g`,`s` go-to — cause not yet determined++## Deviations+- Task 2: no inner `TooltipProvider` — `TooltipProvider` already defaults to delay 0 (`packages/react/src/Tooltip.tsx:29`), so nesting changes nothing.+- Task 3: ⌘K binding + `SearchModal` moved to a `GlobalSearch` sibling outside `NavRail` (on phones the rail is a drawer that unmounts when closed). Escape uses a new named constant `navigationEditCancelShortcut` in `apps/erp/app/shortcuts.ts`.+- Task 5: `closeOnClick` NOT set on AdjustInventory / EndShift — their modals live inside the drawer and would unmount with it (old MES did not close the drawer for these either).+- Task 6: MES rail gets `className="sticky top-0 h-svh"` — below lg the MES page scrolls as a whole and the old sidebar was `fixed`.++- Thermo-nuclear review fixes (all blockers + should-fixes applied):+ `NavRailContext`, `NavRailButton`, `closeOnClick`, `data-collapsible`, `utils/navRail.ts` + its test are gone; one `NavRailItem` (button / `asChild`) + thin `NavRailLink`;+ drawer closes on pathname change inside `NavRail`; rail owns `sticky top-0 h-svh`; MES queues + ⌥ shortcuts come from one `QUEUES` list;+ `UserNav` moved to `apps/mes/app/components/UserNav.tsx`; the 2px `group-has-[[data-collapsible=icon]]` header variant removed from 10 MES headers.++## Dependencies+- Task 1 must be done before everything else.+- Tasks 2 → 3 → 4 run in order (ERP).+- Tasks 5 → 6 run in order (MES).+- The ERP chain (2–4) and the MES chain (5–6) are independent of each other.+- Task 7 needs Tasks 3–6.+- Task 8 needs Tasks 3 and 6.+- Task 9 needs all the others.++## Stop-points+The user asked for check-ins between big steps. Stop and report after Task 1, after Task 4 (ERP done) and after Task 6 (MES done).++## Conventions (all tasks)+- Use `cn()`. Scope transitions to specific properties; never use `transition-all`.+- Every user-facing string goes through Lingui (`Trans` / `t` from `@lingui/react/macro`).+- Shortcut combos must be named constants. Never hand-roll `document.addEventListener("keydown")`.+- Never import from deep `@carbon/react/src/...` paths.+- Never name customers or sources in code or comments.++---++## Task 1: Create `NavRail` components in `@carbon/react`++**Depends on:** none++**Files:**+- Create: `packages/react/src/NavRail.tsx`+- Create: `packages/react/src/__tests__/NavRail.test.tsx`+- Modify: `packages/react/src/index.tsx`. Add the NavRail exports next to the existing `./Sidebar` import/export blocks (~:292-316 and ~:591-662).+- Precedents to copy from:+ - Markup and classes: `apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx` (wrapper :118-125, nav :126-139, `NavigationIconLink` :333-381, search button :273-311).+ - Context: `packages/react/src/Sidebar.tsx` (`useSidebar`, :33-53).+ - Test style: `packages/react/src/__tests__/Number.test.tsx` (`renderToStaticMarkup`, node env).++**Steps:**++1. In `NavRail.tsx`, export the pure helpers first, so they can be tested without a DOM:+ ```ts+ export function isNavRailExpanded(s: { forceExpanded?: boolean; pinned: boolean; hovered: boolean }) {+ return Boolean(s.forceExpanded || s.pinned || s.hovered);+ }+ // Taps must not hover-expand the rail on touch tablets.+ export function shouldHoverExpand(pointerType: string) {+ return pointerType === "mouse";+ }+ ```++2. Export `navRailItemClasses`: the shared base class list for the item geometry. Copy it verbatim from `NavigationIconLink`'s `classes`, without the active/inactive lines:+ `relative text-foreground/70 hover:text-foreground`, `h-10 w-10 group-data-[state=expanded]:w-full`, `flex items-center rounded-md`, `group-data-[state=collapsed]:justify-center`, `group-data-[state=expanded]:-space-x-2`, `font-medium shrink-0 inline-flex items-center justify-center select-none`, `disabled:opacity-50`, `transition-[background-color,color,width] duration-100 ease-out`, `focus:!outline-none focus:!ring-0 active:!outline-none active:!ring-0`, the `after:` focus-ring string, and `group/item`.++ Export `navRailItemStateClasses(isActive: boolean)`, which returns:+ - active: `bg-active text-active-foreground dark:shadow-button-base`+ - inactive: `hover:bg-active/60 hover:text-active-foreground`++3. Internal pieces:+ - **`NavRailIcon({children})`**: `<span className="absolute left-2 top-2 flex size-6 items-center justify-center [&>svg]:size-4">`. A 16px icon centred in this 24px box sits exactly where the ERP's `left-3 top-3` icon sits, and the box also fits an `Avatar size="xs"`.+ - **`NavRailLabel({children})`**: copy the ERP label span (`min-w-[128px] text-sm text-left absolute left-7 group-data-[state=expanded]:left-12 opacity-0 group-data-[state=expanded]:opacity-100`) with `aria-hidden` set **only when collapsed**. Read the state from `NavRailContext` (step 4).+ - **`NavRailTag({children})`**: copy the ERP pill (`absolute top-1 right-1 min-w-4 h-4 px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-medium leading-4 text-center tabular-nums`).+ - **`trailing` slot**: copy the ERP ⌘K hint wrapper classes (`pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 opacity-0 transition-opacity duration-100 group-data-[state=expanded]:opacity-100`).++4. Create `NavRailContext = createContext<{ expanded: boolean; inDrawer: boolean }>({ expanded: false, inDrawer: false })`.++5. **`NavRail`** props:+ `{ children: ReactNode; footer?: ReactNode; className?: string; forceExpanded?: boolean; disableHover?: boolean; drawerTitle?: ReactNode }`.++ Body:+ - `const { open, isMobile, openMobile, setOpenMobile } = useSidebar();`+ - `const [hovered, setHovered] = useState(false);`+ - When `disableHover` becomes true, `setHovered(false)`.+ - When it goes from true back to false, run `requestAnimationFrame(() => setHovered(false))` and cancel it in cleanup. This moves in the ERP's phantom-`mouseenter` fix from `PrimaryNavigation.tsx:82-96`; keep its comment.+ - `expanded = isNavRailExpanded({ forceExpanded, pinned: open, hovered })`.+ - The inner content is a `VStack spacing={1} className="flex flex-col justify-between h-full px-2"` holding two `VStack spacing={1}`: `children` on top, `footer` at the bottom (same as the ERP :144-145).+ - **Mobile** (`isMobile`): render `<Drawer open={openMobile} onOpenChange={setOpenMobile}>` → `<DrawerContent position="left" size="content" className="w-[17rem] max-w-[85vw] p-0">` → `<DrawerTitle className="px-6 py-4">{drawerTitle ?? <Trans>Navigation</Trans>}</DrawerTitle>` → `<nav data-state="expanded" className="group flex-1 overflow-y-auto py-2">`. The inner content uses context `{expanded: true, inDrawer: true}`. Copy the Drawer usage from `apps/erp/app/components/Layout/Navigation/MobileNavigation.tsx:56-72`.+ - **Desktop**: copy the ERP wrapper and nav exactly.+ - Wrapper: `h-full flex-col z-50 hidden md:flex shrink-0 w-14 data-[state=expanded]:w-[13rem] transition-[width] duration-200`, with `data-state` and `data-collapsible={open ? undefined : "icon"}`. MES page headers read `group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12`; the attribute follows the *pinned* state, not hover, so headers do not jump on hover.+ - Nav: `bg-background py-2 group z-10 h-full w-full flex flex-col justify-between hide-scrollbar overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent`, with `data-state`.+ - Handlers: `onPointerEnter={(e) => !disableHover && shouldHoverExpand(e.pointerType) && setHovered(true)}` and `onPointerLeave={(e) => shouldHoverExpand(e.pointerType) && setHovered(false)}`.+ - Context: `{expanded, inDrawer: false}`.++6. **`NavRailLink`**: a `forwardRef<HTMLAnchorElement>`.++ Props: `{ to: string; icon: ReactNode; label: ReactNode; isActive?: boolean; tag?: ReactNode; external?: boolean; onClick?: MouseEventHandler<HTMLAnchorElement>; className?: string } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "children">`.++ Render the react-router `<Link>` with:+ - `role="button"`, `aria-current={isActive ? "page" : undefined}`+ - `aria-label={typeof label === "string" ? label : undefined}`+ - `to`, `prefetch={external ? "none" : "intent"}`+ - classes `cn(navRailItemClasses, navRailItemStateClasses(isActive), className)`++ Children: `NavRailIcon`, `NavRailTag` (when `tag`), `NavRailLabel`.++ `onClick`: call the prop, then call `setOpenMobile(false)` when `isMobile`.++7. **`NavRailButton`**: a `forwardRef<HTMLButtonElement>`.++ Props: `{ icon: ReactNode; label: ReactNode; isActive?: boolean; tag?: ReactNode; trailing?: ReactNode } & ButtonHTMLAttributes<HTMLButtonElement>`.++ - Render `<button type="button" aria-label={typeof label === "string" ? label : undefined} {...rest}>` with the same classes.+ - Spread `...rest` **before** `className` and `onClick` handling, so that when Radix passes `onClick` and `data-state` through `asChild` triggers, they are kept.+ - On mobile, close the drawer after `onClick` only when `closeOnClick` (default `false`) is set. MES Time Card uses it; Popover/Dropdown triggers must not close the drawer.++8. **`NavRailDivider`**: `<Separator className="my-1 mx-auto w-6 group-data-[state=expanded]:w-full transition-[width] duration-200" />`. Reuse `Separator` from `./Separator`.++9. In `index.tsx`, import and export `NavRail`, `NavRailButton`, `NavRailDivider`, `NavRailLink`, `navRailItemClasses`, `navRailItemStateClasses`, `isNavRailExpanded` and `shouldHoverExpand`.++10. Write the test `NavRail.test.tsx`:+ - `isNavRailExpanded`: covers all combinations (forceExpanded wins; pinned or hovered expand; none collapses).+ - `shouldHoverExpand`: `"mouse"` → true, `"touch"` and `"pen"` → false.+ - Render `<MemoryRouter><SidebarProvider defaultOpen={false}><NavRailLink to="/x/sales" icon={<svg/>} label="Sales" isActive tag="3" /></SidebarProvider></MemoryRouter>` with `renderToStaticMarkup`. Expect the output to contain `aria-current="page"`, `bg-active`, `>3<` and `aria-label="Sales"`.++ If `SidebarProvider`/`useIsMobile` throws under the node test environment, STOP and report. Do not add jsdom.++**Verify:**+```bash+pnpm --filter @carbon/react test -- NavRail+# Expected: NavRail.test.tsx passes, 0 failed+pnpm --filter @carbon/react typecheck+# Expected: exits 0, no errors+pnpm exec biome check packages/react/src/NavRail.tsx packages/react/src/__tests__/NavRail.test.tsx packages/react/src/index.tsx+# Expected: "Checked 3 files" with no errors+```++**Out of scope:** changing `Sidebar.tsx` primitives or `SidebarProvider`'s API; `apps/starter`.++---++## Task 2: Mount `SidebarProvider` in the ERP layout++**Depends on:** Task 1++**Files:**+- Modify: `apps/erp/app/routes/x+/_layout.tsx` (~:495-503)+- Precedent: `apps/mes/app/routes/x+/_layout.tsx:503-504`++**Steps:**++1. Replace `<div className="flex h-screen">…</div>` (which wraps `<PrimaryNavigation />` and the content panel) with:+ ```tsx+ <SidebarProvider defaultOpen={false} className="h-screen min-h-0">+ {/* SidebarProvider sets a 0ms tooltip delay; restore ERP's default for everything inside. */}+ <TooltipProvider>+ <PrimaryNavigation />+ <div className="…unchanged content panel classes…">…</div>+ </TooltipProvider>+ </SidebarProvider>+ ```+ Import `SidebarProvider` from `@carbon/react`. `TooltipProvider` renders no DOM, so the flex row is unchanged.++2. Do not add the content inset to the rail (`.ai/lessons.md` ~1470-1490).++**Verify:**+```bash+pnpm --filter erp typecheck+# Expected: exits 0+```+Manual check in Task 9: the ERP shell looks identical, and ⌘B toggles the rail.++**Out of scope:** `TrainingPanel`, `AgentRoot`, `ShortcutHelp`, `TimeCardWarning` placement.++---++## Task 3: Rebuild ERP `PrimaryNavigation` on `NavRail`++**Depends on:** Task 2++**Files:**+- Modify: `apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx`+- Modify: `apps/erp/app/components/Layout/Navigation/SortableNavItem.tsx`. Replace its duplicated geometry classes with `navRailItemClasses` plus its drag-specific extras.++**Steps:**++1. Keep all of the existing logic: modules, settings, implementation nav, `matchedModules`, `goToModules`/`useShortcutSequence`, `editMode`, `sensors`, `getModule` (still exported and used by `MobileNavigation`).++2. Remove:+ - `useDisclosure`+ - The wrapper `<div>` and `<nav>`+ - The hover handlers+ - The rAF effect (it now lives inside `NavRail`)+ - `NavigationIconLink`++3. Return:+ ```tsx+ <NavRail+ forceExpanded={editMode.isEditing}+ disableHover={editMode.isEditing || isSearchModalOpen}+ footer={…settings NavRailLink (not editing) + NavigationEditBar or Customize NavRailButton…}+ >+ {permissions.is("employee") && <NavigationSearchButton />}+ {!editMode.isEditing && implementationNav ? <NavRailLink … /> : null}+ {editMode.isEditing ? <DndContext…>…SortableNavItem…</DndContext> : links.map(link => <NavRailLink key={link.name} to={link.to} icon={<link.icon />} label={link.name} tag={link.tag} external={link.external} isActive={…same calc…} />)}+ {editMode.isEditing && <HiddenModulesPopover … />}+ </NavRail>+ ```++4. **Customize button**: `<NavRailButton icon={<LuSettings2 />} label={t\`Customize\`} onClick={editMode.enterEditMode} className="hover:bg-accent hover:text-accent-foreground" />`. The ERP's Customize and Search hover used `bg-accent`, not `bg-active/60`; keep that.++ Customize is hidden on mobile, as it is today. Wrap it in `useSidebar().isMobile ? null : …`.++5. **`NavigationSearchButton`**: keep `useShortcutKeys(searchShortcut)` and `<SearchModal />`, and render:+ ```tsx+ <NavRailButton icon={<LuSearch />} label={t`Search`} onClick={openSearchModal} className="hover:bg-accent hover:text-accent-foreground" trailing={<ShortcutKey shortcut={searchShortcut} variant="small" className="mx-0" />} />+ ```+ On mobile, close the drawer before `openSearchModal`. The old `MobileNavigation` did `disclosure.onClose(); openSearchModal()`, so use `closeOnClick`.++6. **Escape during edit mode**: replace the hand-rolled `document.addEventListener` effect (:103-110) with `useShortcutKeys({ shortcut: SHORTCUTS.escape ?? "escape", action: editMode.cancelEditMode, disabled: !editMode.isEditing })`.++ First check `packages/react/src/shortcuts.ts` and `packages/react/src/hooks/useShortcutKeys.ts` for the exact escape constant name and the `disabled` option. If neither an escape constant nor a disable option exists, STOP and report. Do not add a new listener.++7. **`SortableNavItem`**: import `navRailItemClasses` and use `cn(navRailItemClasses, "hover:bg-accent hover:text-accent-foreground border border-transparent", isDragging && "opacity-50 border-primary")`. Keep its custom `left-8`/`left-12` icon and label offsets (drag handle). Remove `text-foreground/70` via `cn` override only if the visual differs. Compare in Task 9.++**Verify:**+```bash+pnpm --filter erp typecheck+# Expected: exits 0+pnpm exec biome check apps/erp/app/components/Layout/Navigation/+# Expected: no errors+grep -n "addEventListener\|NavigationIconLink\|onMouseEnter" apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx+# Expected: no output+```++**Out of scope:** `useModules`, `useNavigationEditMode`, `HiddenModulesPopover` (its untranslated "Add module" is a separate fix), `CollapsibleSidebar`.++---++## Task 4: Replace ERP mobile drawer with the shared rail drawer++**Depends on:** Task 3++**Files:**+- Modify: `apps/erp/app/components/Layout/Navigation/MobileNavigation.tsx`. Reduce it to a trigger.+- Precedent: `packages/react/src/Sidebar.tsx:279-300` (`SidebarTrigger` calling `toggleSidebar`).++**Steps:**++1. Replace the whole component body with:+ ```tsx+ const { t } = useLingui();+ const { toggleSidebar } = useSidebar();+ return <IconButton aria-label={t`Open navigation`} icon={<LuMenu />} variant="ghost" onClick={toggleSidebar} />;+ ```+ On mobile, `toggleSidebar` flips `openMobile`, which `NavRail` renders as the drawer holding the same items as the desktop rail.++2. Delete `NavRow`, the drawer imports and the unused hooks. Update the doc comment: the drawer is now rendered by the shared `NavRail`, and this is only its trigger.++3. `Topbar.tsx:28` needs no change; it still renders `<MobileNavigation />`.++**Verify:**+```bash+pnpm --filter erp typecheck+# Expected: exits 0+pnpm exec biome check apps/erp/app/components/Layout/+# Expected: no errors+```++**🛑 Stop-point:** report to the user that the ERP side is done and ask before starting MES.++**Out of scope:** the Topbar "Sections" content sub-nav (`useUIStore.toggleSidebar`, a different sidebar).++---++## Task 5: Move MES tool buttons to `NavRailButton`++**Depends on:** Task 1++**Files:**+- Modify: `apps/mes/app/components/AdjustInventory.tsx` (:113-121)+- Modify: `apps/mes/app/components/EndShift.tsx` (:71-76)+- Modify: `apps/mes/app/components/Suggestion.tsx` (:141-146)+- Modify: `apps/mes/app/components/TimeCardButton.tsx` (all `SidebarMenuItem`/`SidebarMenuButton` usages)+- Precedent: the ERP Customize button from Task 3++**Steps:**++1. **AdjustInventory**: `<NavRailButton icon={add ? <LuGitPullRequestCreateArrow /> : <LuGitBranchPlus />} label={add ? t\`Add Inventory\` : t\`Remove Inventory\`} onClick={modal.onOpen} closeOnClick />`.++2. **EndShift**: `<NavRailButton icon={<LuCircleStop />} label={t\`End Operations\`} onClick={openModal} closeOnClick />`.++3. **Suggestion**: `<PopoverTrigger ref={popoverTriggerRef} asChild><NavRailButton icon={<LuMailbox />} label={t\`Suggestion\`} /></PopoverTrigger>`. No `closeOnClick`, because the popover anchors to the button.++4. **TimeCardButton**:+ - Remove `SidebarMenuItem` wrappers and return a fragment of rail items.+ - Clock In: `NavRailButton icon={<LuPlay />} label={t\`Clock In\`} onClick={handleClockIn} disabled={fetcher.state !== "idle"} closeOnClick`.+ - Clock Out: same with `LuSquare`, `trailing={openClockEntry && <Badge variant="red">{formatElapsed(openClockEntry.clockIn)}</Badge>}`.+ - My Hours: `NavRailLink to={path.to.timeCardPage} icon={<LuClock />} label={t\`My Hours\`} isActive={isOnTimeCardPage}`.+ - Drop the manual `isMobile && setOpenMobile(false)` calls, since `NavRailLink` and `closeOnClick` handle them.+ - Read the entire file first. If it holds rows beyond Clock In, Clock Out and My Hours, convert each the same way.++5. Remove the now-unused `SidebarMenuButton`, `SidebarMenuItem` and `useSidebar` imports.++**Verify:**+```bash+pnpm exec biome check apps/mes/app/components/AdjustInventory.tsx apps/mes/app/components/EndShift.tsx apps/mes/app/components/Suggestion.tsx apps/mes/app/components/TimeCardButton.tsx+# Expected: no errors+```+MES typecheck runs in Task 6, because `AppSidebar` still wraps these in `SidebarMenuItem` until then.++**Out of scope:** the modal and popover contents of these components.++---++## Task 6: Rebuild MES `AppSidebar` on `NavRail`++**Depends on:** Task 5++**Files:**+- Modify: `apps/mes/app/components/AppSidebar.tsx`+- Modify: `apps/mes/app/routes/x+/_layout.tsx` (:503). Change `<SidebarProvider defaultOpen={false} touch>` to `<SidebarProvider defaultOpen={false}>`.+- Precedent: the ERP `PrimaryNavigation` from Task 3++**Steps:**++1. Change the `AppSidebar` props type from `ComponentProps<typeof Sidebar> & {…}` to just the explicit `{…}` data props. Render:+ ```tsx+ <NavRail footer={<>{timeCardEnabled && <Suspense…><Await…><TimeCardButton…/></Await></Suspense>}<UserNav …/></>}>+ <OperationsNav activeEvents={activeEvents} activeMaintenanceCount={activeMaintenanceCount} />+ <NavRailDivider />+ <ToolsNav />+ </NavRail>+ ```+ Keep the existing `Suspense`/`Await` block as-is.++2. Delete `TeamSwitcher`. Grep for other importers first: `grep -rn "TeamSwitcher" apps/mes/app`. If anything else imports it, STOP and report.++3. **`OperationsNav`**:+ - Keep the shortcut map and `go()`.+ - Build `links` with `{ key, title, icon, to, count? }`, and add `match: path.to.operations.split("?")[0]` for Schedule (other items: `match = to`).+ - `isActive = pathname.startsWith(item.match)`. This removes the `item.title === "Schedule"` check, which was the translated-title bug.+ - Render `<NavRailLink key={item.key} to={item.to} icon={<item.icon />} label={item.title} isActive={isActive} tag={item.count ? String(item.count) : undefined} />`.+ - No `SidebarGroup`/`SidebarGroupLabel`, and no emerald class.++4. **`ToolsNav`**: return a fragment with `<AdjustInventory add />`, `<AdjustInventory add={false} />`, `<EndShift />`, `<Suggestion />`, `<DisplaysLink />`.++ `DisplaysLink` becomes `<NavRailLink to={path.to.displays} icon={<LuMonitorPlay />} label={t\`Displays\`} external target="_blank" rel="noreferrer" />`. Check that `NavRailLink` passes `target`/`rel` through `...rest`.++5. **`UserNav`**:+ - Keep all dropdown content unchanged.+ - Replace the trigger with `<DropdownMenuTrigger asChild><NavRailButton icon={<Avatar size="xs" src={displayAvatar ?? undefined} name={displayName} />} label={displayName} trailing={<LuChevronDown className="size-4" />} /></DropdownMenuTrigger>`.+ - Change `side={isMobile ? "bottom" : "right"}` to keep using `useSidebar().isMobile`.+ - Replace the trigger-width class on `DropdownMenuContent` with `min-w-56 rounded-lg`; the rail is only 56px when collapsed.+ - Replace the outer `SidebarMenu`/`SidebarMenuItem` wrappers with a fragment. Keep `<ItarDisclosure>`.++6. Remove unused imports (`Sidebar*`, `BsFillHexagonFill`, `ERP_URL` if now unused, `cn` if unused).++7. `SidebarTrigger` in the MES page headers needs no change: it calls `toggleSidebar`, which pins the rail on desktop and opens the drawer on mobile.++**Verify:**+```bash+pnpm --filter mes typecheck+# Expected: exits 0+pnpm exec biome check apps/mes/app/components/ apps/mes/app/routes/x+/_layout.tsx+# Expected: no errors+grep -n "SidebarMenuButton\|SidebarGroup\|TeamSwitcher\|=== \"Schedule\"" apps/mes/app/components/AppSidebar.tsx+# Expected: no output+```++**🛑 Stop-point:** report to the user that the MES side is done and ask before continuing.++**Out of scope:** MES page headers, `MES_NAV_SHORTCUTS`, the `display+` layout, and `apps/mes/app/styles/tailwind.css` `--sidebar-width`.++---++## Task 7: Extract Lingui strings++**Depends on:** Tasks 3–6++**Files:**+- Modify (generated): `packages/locale/locales/*/*.po`++**Steps:**+1. Run the extract.+2. Confirm the new and moved msgids exist in both the erp and mes catalogs: "Navigation", "Customize", "Search", "Displays" and "My Hours".+3. Leave filling non-English msgstrs to the `/translate` skill, which runs at commit time (check-and-commit). Do not hand-write translations.++**Verify:**+```bash+pnpm run lingui:extract+# Expected: completes; the summary table lists erp and mes with 0 errors+grep -c 'msgid "Navigation"' packages/locale/locales/en/mes.po+# Expected: 1 (if the catalog file names differ, `ls packages/locale/locales/en/` and use the mes catalog)+```++**Out of scope:** changing `lingui.config.js`.++---++## Task 8: Sync docs++**Depends on:** Tasks 3, 6++**Files:**+- Modify: `packages/react/AGENTS.md`. Add a one-line entry: app shells use `NavRail*` for the primary left nav; the `Sidebar*` primitives remain for other layouts.+- Modify: `.claude/skills/carbon-design/references/page-archetypes.md`:+ - §1: the rail is the shared `NavRail`, used by ERP and MES.+ - §14: below md the rail's own drawer opens from the Topbar hamburger (ERP) or the page-header trigger (MES).+- Modify: `.claude/skills/carbon-design/references/shop-floor-mes.md`:+ - The ERP/MES nav row now says both use `NavRail`.+ - The exemplar points to `apps/mes/app/components/AppSidebar.tsx` on `NavRail`.+ - The no-hover rule becomes "hover-expand is mouse-only; touch uses the pin toggle (header trigger / ⌘B)".++**Steps:**+1. Before editing, `grep -rn "PrimaryNavigation\|AppSidebar" .claude/ packages/react/AGENTS.md apps/*/AGENTS.md` and update every hit that describes the old behaviour.+2. Keep the edits to the minimum wording change.++**Verify:**+```bash+grep -rn "NavRail" packages/react/AGENTS.md .claude/skills/carbon-design/references/page-archetypes.md .claude/skills/carbon-design/references/shop-floor-mes.md+# Expected: at least one hit in each of the three files+```++**Out of scope:** the docs site (`docs/`).++---++## Task 9: End-to-end verification in the browser++**Depends on:** Tasks 1–8++**Files:** none (evidence goes to `.ai/scratch/e2e/`, which is gitignored)++**Steps:**+1. Boot the stack from the worktree: `crbn up` (both ERP and MES).+2. Log in with the `/auth` skill.+3. Walk each acceptance criterion in the spec using `agent-browser`, and take a screenshot for each:+ - ERP desktop:+ - Rail at 56px, 208px on hover.+ - Active module highlighted.+ - Get Started pill.+ - Customize → drag → Save persists after reload.+ - ⌘K opens search.+ - `g` `s` goes to Sales.+ - ⌘B pins and unpins the rail.+ - MES desktop:+ - Same widths and hover.+ - Active highlights on `/x/active`.+ - Schedule highlights on `/x/operations` after switching locale to Spanish via the ERP avatar menu → Language.+ - Pill counts; no pill at 0.+ - Header toggle and ⌘B pin the rail.+ - Alt+1 goes to Schedule.+ - MES footer:+ - Clock In, then Clock Out.+ - Avatar menu: company, location, dark mode, console mode, sign out.+ - MES tools: each modal or popover opens; Displays opens a new tab.+ - Phone width: `agent-browser set viewport 390 844` in both apps. The trigger opens the drawer, and clicking a link closes it.+ - Touch: `agent-browser set device "iPad"` (or the closest available). Tapping a MES item navigates without the rail expanding first.+4. On any error screen, use the `/error` skill and fix the cause before continuing.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/react --filter=erp --filter=mes+# Expected: 3 successful tasks, 0 failed+pnpm --filter @carbon/react test+# Expected: all tests pass+```+Every acceptance-criteria box in the spec is ticked, each with a screenshot path.++**Out of scope:** committing. The user commits only on explicit request (check-and-commit).diff --git a/.ai/research/shared-sidebar.md b/.ai/research/shared-sidebar.mdnew file mode 100644index 0000000000..d120c4f445--- /dev/null+++ b/.ai/research/shared-sidebar.md@@ -0,0 +1,198 @@+# Shared Sidebar Research: ERP `PrimaryNavigation` vs MES `AppSidebar`++Repo root: worktree `carbon-feat-shared-sidebar` (branch `feat/shared-sidebar`, from origin/main at cad42b9499). All paths are relative to the repo root. Findings come from a read-only codebase survey; citations are file:line.++TL;DR: ERP builds its own hover-expand icon rail. MES uses the `@carbon/react` `Sidebar` primitives. No shared app-nav component exists. `@carbon/react` already peers on `react-router`, `@lingui/react` and `react-icons`, and its strings are extracted into both the erp and mes catalogs, so a shared sidebar can live there.++## 1. ERP sidebar (apps/erp)++### Files+- `apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx`: the desktop icon rail, which expands on hover. Default export is `memo(PrimaryNavigation)` (:383). `getModule(link)` = `link.split("/")[2]` (:385-387).+- `apps/erp/app/components/Layout/Navigation/MobileNavigation.tsx`: below `md`, a hamburger opens a left `Drawer` (:31-129). `NavRow` is at :142-191.+- `SortableNavItem.tsx`: draggable row for Customize mode (`@dnd-kit/sortable`, :13-92).+- `HiddenModulesPopover.tsx`: the "Add module" popover. The "Add module" label is not translated (:40).+- `NavigationEditBar.tsx`: Save/Cancel bar (:11-45).+- `useNavigationEditMode.tsx`: draft, reorder and hide state. It POSTs to `/api/module-preferences` (:94-109).+- `CollapsibleSidebar.tsx`: not the primary nav. It is the module content sub-nav; its state lives in zustand `useUIStore`.++### Data+- `apps/erp/app/hooks/useModules.tsx`:+ - `useModuleDefinitions()` (:47-157): hard-coded `{key, permission|role, name (t), to, icon}`.+ - `filterByPermissions` (:32-45).+ - `PINNED_MODULES = {"settings"}` (:159).+ - `useModules()` (:161-192): sorted, then reordered and hidden by `modulePreferences`.+ - `useSettingsModule()` (:194-203).+ - `useAllModules()` (:205-227).+- `apps/erp/app/hooks/useImplementationNavItem.tsx:46-66`: the "Get Started" item, with a `tag` badge.+- Types (`apps/erp/app/types/index.ts`): `NavItem` (:64-69), `Route` with `tag?` and `isActive?` (:78-94).+- Persistence:+ - `getModulePreferences` and `upsertModulePreferences` (`apps/erp/app/modules/users/users.server.ts:882-901`), table `userModulePreference`.+ - Route: `routes/api+/module-preferences.tsx`.+ - Loaded in `x+/_layout.tsx:195`.++### Behaviour+- Hover-expand: `onMouseEnter`/`onMouseLeave` → `useDisclosure` (:133-138). Hover is ignored during edit mode and while search is open.+- Width goes from `w-14` (56px) to `w-[13rem]` (208px), with `transition-[width] duration-200` (:118-125). Content is pushed, not overlaid.+- Labels are absolutely positioned and animate opacity from 0 to 100 (:368-377).+- Edit mode forces the rail open (:112).+- Search-modal phantom-mouseenter fix (:82-96).+- Nothing is persisted: no cookie, no toggle.+- ⌘B is listed in `ShortcutHelp.tsx:62-65`, but the ERP never mounts `SidebarProvider`, so it has no binding.++### Search and shortcuts+- `NavigationSearchButton` (:262-316) is shown for employees only. It binds ⌘K (:266-269) and mounts `SearchModal` (`Topbar/Search.tsx:71`).+- `apps/erp/app/shortcuts.ts` defines `g` + letter per module (`MODULE_GO_TO`, :70-85). It is bound with `useShortcutSequence` (:62-80).+- Escape is handled by a hand-rolled keydown listener (:103-110), which goes against the rules.++### Styling+- Rail: `bg-background` (:129).+- Item: 40px square, `rounded-md`, `text-foreground/70`, hover `bg-active/60`.+- Active: `bg-active text-active-foreground dark:shadow-button-base`.+- Focus: custom `after:` blue-500 ring.+- Tag badge: a pill at `top-1 right-1`, `bg-primary`, 10px text (:362-366).+- A11y quirk: label `aria-hidden={isOpen || undefined}` looks inverted (:369).++### User and company+The ERP user menu and company switcher are in the **Topbar**, not the rail:+- `AvatarMenu.tsx:50-276`+- `Topbar/Breadcrumbs.tsx:139+` (`CompanyBreadcrumb`)+- `Topbar/CompanySwitcher.tsx` (mobile)+- `Topbar.tsx:15-62`++### Primitives+From `@carbon/react`: `cn`, `ShortcutKey`, `useDisclosure`, `useShortcutKeys`, `useShortcutSequence`, `VStack`, `Popover*`, `Button`, `Drawer*`, `IconButton`, `useRouteData`, `useOptimisticLocation`.++The ERP does not use the `Sidebar*` primitives. It also uses `@dnd-kit/*` and `@carbon/onboarding`.++## 2. MES sidebar (apps/mes)++### Files+- `apps/mes/app/components/AppSidebar.tsx` (681 lines):+ - `Sidebar collapsible="icon"`, with a className override for a `bg-background`, borderless look (:111-115).+ - Header: `TeamSwitcher` (:162-195). This is only a link to the ERP with the company logo and name; it is not actually a switcher.+ - Content: `OperationsNav` (:197-340) and `ToolsNav` (:342-378).+ - Footer: `TimeCardButton` (:127-146) and `UserNav` (:400-681).+ - `SidebarRail` (:157).+- Tool buttons that open modals: `AdjustInventory.tsx:113-121`, `EndShift.tsx:71-76`, `Suggestion.tsx:141-146`, `TimeCardButton.tsx:70-97`.++### Data+- Items are inline in `OperationsNav` (:255-293): Schedule, Assigned, Active (count), Recent, Jobs, Maintenance (count), Picking.+- Tools: Add/Remove Inventory, End Operations, Suggestion, Displays (opens in a new tab).+- All data comes from `x+/_layout` loader props.+- **No permission gating in the sidebar.** Each route is auth-only.+- Conditional parts:+ - `timeCardEnabled`+ - The console switch (`consoleEnabled && (consoleMode || canEnterConsoleMode)`)+ - The location submenu (only when there is more than one location)+ - The simplified menu when an operator is pinned in++### Behaviour (from `packages/react/src/Sidebar.tsx`)+- `SidebarProvider defaultOpen={false} touch` (mes `x+/_layout.tsx:503`). It writes the cookie `sidebar:state`, but nothing reads it back.+- ⌘B toggles (:108-114).+- Widths:+ - Expanded: 16rem.+ - Collapsed: 4rem (touch).+ - Mobile: a Drawer, 18rem.+ - MES `tailwind.css:30` sets `--sidebar-width: 240px`, but it is overridden.+- Toggle sources:+ - `SidebarTrigger` in each page header (active, operations, assigned, recent, jobs, maintenance, picking, dispatch, job, `AssemblyView`, `InspectionView`, `JobOperation`)+ - `SidebarRail`+ - ⌘B+- Tooltips on items when collapsed.+- Touch sizing:+ - Collapsed buttons are 48px.+ - Expanded rows are at least 44px.++### Styling+- Active: `bg-sidebar-accent/50 text-foreground font-medium`, which is subtle.+- Counts above 0 turn the row emerald. Counts are right-aligned and muted.+- Uppercase group labels: Operations, Inventory Adjustments, Tools.++### Shortcuts+- alt+1..7 (`apps/mes/app/shortcuts.ts:15-23`). No bare letters, because scanners type into the page.+- ⌘B.++### User menu+The footer `UserNav` contains:+- Switch Operator / Station+- Account Settings (link to the ERP)+- Company submenu+- Location submenu+- Dark Mode+- Console Mode+- About (ITAR)+- Sign Out++### Bugs spotted+- The Schedule highlight relies on `item.title === "Schedule"`, which is a translated string (:307). It breaks in any locale other than English.+- `useIsMobile` is false during SSR, so MES flashes the desktop sidebar before switching to the drawer.++## 3. Differences++| Aspect | ERP | MES |+|---|---|---|+| Impl | Hand-rolled `<nav>` | `@carbon/react` `Sidebar*` |+| Collapsed / expanded width | 56px / 208px | 64px / 256px |+| Expand trigger | Hover | Toggle (header trigger, rail, ⌘B) |+| Item size | 40px | 48px collapsed, 44px rows |+| Collapsed labels | Opacity fade on hover | Hidden, with tooltips |+| Active style | Solid `bg-active` | Subtle `bg-sidebar-accent/50` |+| Active match | Path segment [2] or `handle.module` | `pathname.includes` plus the Schedule hack |+| Badges | `bg-primary` pill at top-right | Right-aligned count, row turns emerald |+| Groups | Flat list, Settings pinned at the bottom | Labelled groups |+| Header | None | Company logo and name |+| Top | ⌘K Search, Get Started | none |+| Footer | Settings and Customize (drag-and-drop) | TimeCard and user dropdown |+| User menu / company switch | Topbar | Sidebar footer |+| Shortcuts | `g`+letter, ⌘K | alt+1..7, ⌘B |+| Mobile | Separate hamburger Drawer in the Topbar | Same `Sidebar` becomes a Drawer |+| Actions | Nav only | Modal-opening tool buttons and an external link |++## 4. ERP modules++The modules are accounting, documents, inventory, invoicing, parts (Items), people, production, purchasing, quality, resources, sales, settings (pinned), shopFloor (role employee, external link to MES), users and workflows. Each module is gated by `permissions.can("view", key)`. Commercial-licensing rule 3 says gated features stay visible in the nav.++## 5. Shared packages+- `@carbon/react`:+ - Peer dependencies: `react-router`, `@lingui/react`, `react-icons`, `framer-motion`.+ - No `@dnd-kit`. Adding it is an Ask First item.+ - No build step; each app compiles the source directly.+ - It already imports `react-router` in 9 files and `@lingui/react/macro` in 9 files.+- `lingui.config.js` extracts `packages/react/src` into both the erp and mes catalogs. `packages/onboarding` and `packages/ee` go to erp only.+- Tailwind: `packages/config/tailwind/theme.css` uses `@source "../../"`, which scans all packages.+- Components already shared between the apps:+ - `ItarDisclosure` (`packages/react/src/Acknowledge.tsx`)+ - `PrintingProvider`+ - `SHORTCUTS` and `ShortcutHelpOverlay`+- Components that are copy-pasted instead:+ - `SessionLockOverlay`+ - `Suggestion`+ - `OperationStatusIcon`+- `packages/react/src/Sidebar.tsx` exports the full shadcn-style primitive set. It is used by MES and `apps/starter`.++## 6. Layouts++### ERP: `apps/erp/app/routes/x+/_layout.tsx:483-502`+- `TooltipProvider` → `div.flex.h-screen` → `PrimaryNavigation` plus the inset content panel (`md:rounded-2xl ... shadow-md`) → `Topbar` and `main`.++### MES: `apps/mes/app/routes/x+/_layout.tsx:491-522`+- `SidebarProvider defaultOpen={false} touch` → `TooltipProvider` → `AppSidebar` plus the inset panel (no `shadow-md`).+- MES has no global topbar. Each page has a sticky header with `SidebarTrigger`.++## 7. Guidance+- `.claude/skills/carbon-design/references/shop-floor-mes.md`:+ - MES uses **no hover-reveal**, **no bare-letter shortcuts**, and touch-sized controls. This conflicts with the ERP rail.+ - Rule 9: "Where MES and ERP share a concept, share the component … MES is converging on ERP's visual language."+- `packages/react/AGENTS.md`, Ask First:+ - Barrel export changes+ - New primitive dependencies+- `packages/react/AGENTS.md`, Never:+ - `transition-all`+ - Icon-only buttons without `aria-label`+- `.claude/rules/conventions-ui.md`:+ - Shortcut constants must be named.+ - No hand-rolled keydown listeners.+ - Hit areas must be about 40px or more.+- `.claude/rules/keep-sources-in-sync.md`: shell or nav changes must update `packages/react/AGENTS.md` and the carbon-design references (page-archetypes §1/§14, shop-floor-mes).+- `.ai/lessons.md` (~1470-1490): do not add the content inset to `PrimaryNavigation`.+- No existing spec covers a shared sidebar.diff --git a/.ai/specs/2026-09-29-shared-nav-rail.md b/.ai/specs/2026-09-29-shared-nav-rail.mdnew file mode 100644index 0000000000..0d7dc55885--- /dev/null+++ b/.ai/specs/2026-09-29-shared-nav-rail.md@@ -0,0 +1,170 @@+# Shared Nav Rail (ERP + MES)++> Status: draft+> Author: Aashu+> Date: 2026-09-29+> Research: [.ai/research/shared-sidebar.md](../research/shared-sidebar.md)++## TLDR++The ERP and MES each build their own left sidebar, and the two look and behave differently. This spec moves the ERP's icon rail into `@carbon/react` as a set of `NavRail*` components. Both apps then render the rail from that one source. MES is rebuilt on it, so it matches the ERP: same widths, item look, active style, hover-to-expand, badges and mobile drawer. MES adds a tap/⌘B toggle for touch tablets. The ERP keeps its app-specific pieces, such as the module list, Customize, search and `g`+letter shortcuts. It passes them to the shared rail as children, so they are not baked into the package.++## Problem Statement++- ERP `PrimaryNavigation` (`apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx`):+ - A hand-rolled rail.+ - 56px collapsed and 208px when expanded on hover.+ - A solid `bg-active` active style and a `bg-primary` tag pill.+ - A separate `MobileNavigation` drawer on phones.+- MES `AppSidebar` (`apps/mes/app/components/AppSidebar.tsx`, 681 lines):+ - Built on the shadcn-style `Sidebar*` primitives.+ - 64px collapsed and 256px expanded, toggle-only.+ - A subtle `bg-sidebar-accent/50` active style.+ - Labelled groups, an emerald count highlight, a company header and a user dropdown in the footer.+- Result: moving between the two apps feels like two products. Any styling fix has to be made twice and drifts. The carbon-design rule "where MES and ERP share a concept, share the component" (`.claude/skills/carbon-design/references/shop-floor-mes.md`, rule 9) is not being followed.+- Bugs found along the way:+ - The MES "Schedule" item never highlights outside English. `AppSidebar.tsx:307` compares a translated title.+ - The ERP lists ⌘B in its shortcut help (`ShortcutHelp.tsx:62-65`), but nothing binds it, because the ERP never mounts `SidebarProvider`.+ - The ERP rail labels use an inverted `aria-hidden` (`PrimaryNavigation.tsx:293, :369`).++## Proposed Solution++### Units++1. **`packages/react/src/NavRail.tsx`** (new): the presentational rail. It is the single source of truth for look and behaviour.+ - **`NavRail`**: the container, lifted from `PrimaryNavigation`'s wrapper and `<nav>`.+ - Desktop: an animated-width wrapper (`w-14` → `w-[13rem]`, `transition-[width] duration-200`) and `bg-background`.+ - It has two slots, `children` (top list) and `footer` (bottom list).+ - It sets `data-state="expanded|collapsed"` for the item styles.+ - On mobile (`useSidebar().isMobile`), it renders the same slots inside a left `Drawer` (`w-[17rem]`, forced expanded). The drawer is driven by `openMobile`.+ - Props: `className`, `disableHover?: boolean` (used by ERP edit mode and while its search modal is open), `forceExpanded?: boolean` (ERP edit mode).+ - **`NavRailLink`**: lifted from `NavigationIconLink`. It wraps react-router `Link`.+ - Props: `to`, `icon: IconType`, `label: ReactNode`, `isActive`, `tag?: ReactNode`, `external?`, `onClick?`.+ - Same classes as the ERP today. The label's `aria-hidden` bug is fixed: labels are hidden from assistive technology only while collapsed, and the link gets `aria-label` from the label so the collapsed state stays accessible.+ - On mobile, clicking a link closes the drawer.+ - **`NavRailButton`**: same visual as `NavRailLink`, but a `<button>` that forwards its ref.+ - Used for Search, Customize, MES tools and the Time Card.+ - It can be a `DropdownMenuTrigger`/`PopoverTrigger` child via `asChild` at the call site.+ - Props: `icon`, `label`, `isActive?`, `tag?`, `trailing?: ReactNode` (for the ⌘K hint), plus button props.+ - **`NavRailDivider`**: a thin separator between item groups. It replaces MES group labels.+ - Exported from `packages/react/src/index.tsx`.+2. **Rail state: reuse `SidebarProvider` / `useSidebar`** (`packages/react/src/Sidebar.tsx`).+ - `open` means pinned-open (⌘B, the header `SidebarTrigger`).+ - `isMobile` and `openMobile` drive the drawer.+ - `NavRail` keeps a local `hovered` flag.+ - Expanded = `forceExpanded || open || hovered`.+ - Hover is tracked with `onPointerEnter`/`onPointerLeave` and only reacts when `event.pointerType === "mouse"`. Taps never trigger hover-expand; on touch, expand happens only through the toggle.+ - Both apps mount `SidebarProvider defaultOpen={false}`. The ERP gains it, which makes the ⌘B listed in its help actually work.+3. **ERP `PrimaryNavigation`** keeps its data, but renders shared parts:+ - `NavRail` → search as a `NavRailButton` (ERP-owned; ⌘K, `SearchModal`), Get Started, then modules as `NavRailLink`.+ - Footer: Settings plus Customize (`NavRailButton`).+ - Edit mode stays ERP-only: the `@dnd-kit` `SortableNavItem`, `HiddenModulesPopover` and `NavigationEditBar`. It passes `forceExpanded`/`disableHover`.+ - `SortableNavItem` reuses the shared item class string. The shared file exports a `navRailItemVariants` (cva) for this.+ - The hand-rolled Escape listener is replaced with `useShortcutKeys`.+4. **ERP mobile**:+ - `MobileNavigation`'s drawer is removed. The Topbar hamburger now calls `useSidebar().toggleSidebar()`.+ - `NavRail` shows the same items in its drawer (search, modules, settings; Customize is hidden on mobile, as it is today).+5. **MES `AppSidebar`**, rebuilt on `NavRail`:+ - Top: Schedule, Assigned, Active (`tag` = count), Recent, Jobs, Maintenance (`tag` = count), Picking.+ - Then `NavRailDivider`, then Add Inventory, Remove Inventory, End Operations, Suggestion and Displays (external).+ - Footer: Time Card (when enabled) and the user menu. The user menu is an avatar `NavRailButton` that opens the existing `UserNav` dropdown content to the right. It keeps company switch, location, dark mode, console mode, switch operator, About and Sign out.+ - The company logo/name header is removed.+ - `AdjustInventory`, `EndShift`, `Suggestion` and `TimeCardButton` swap `SidebarMenuButton` for `NavRailButton`.+ - Active match uses the path without its query string (`path.to.operations` minus `?saved=1`), which fixes the Schedule bug.+ - The MES layout drops `touch` from `SidebarProvider`, since the rail sizes itself.+ - Page-header `SidebarTrigger`s are kept. On desktop they pin the rail open or closed; on phones they open the drawer.+6. **Docs sync** (`.claude/rules/keep-sources-in-sync.md`):+ - `packages/react/AGENTS.md`: add NavRail.+ - `.claude/skills/carbon-design/references/page-archetypes.md` §1/§14: shared rail, mobile drawer.+ - `.claude/skills/carbon-design/references/shop-floor-mes.md`: the nav row and exemplar now point to `NavRail`. The no-hover rule becomes "hover-expand is mouse-only; touch uses the toggle".++### Design Decisions++| Decision | Choice | Rationale |+|---|---|---|+| Where the shared rail lives | `packages/react/src/NavRail.tsx` | `@carbon/react` already peers on `react-router`, `@lingui/react` and `react-icons`. Its source is extracted into both the erp and mes Lingui catalogs, and Tailwind scans all packages (research §5). |+| Base implementation | Lift the ERP markup and classes, not the shadcn `Sidebar` primitives | The target look *is* the ERP. Lifting its classes guarantees the match; restyling shadcn primitives would only approximate it. |+| Rail state | Reuse the `SidebarProvider` context | MES page-header `SidebarTrigger`s, ⌘B and the mobile `openMobile` already run through it. There is no second state store. |+| Expand behaviour | Hover (mouse pointers only) OR pinned toggle | User answer Q1. The pointer-type check stops taps from triggering hover-expand on tablets. |+| App-specific features | Passed as children and slots, not props-driven config | Search, Customize (`@dnd-kit`) and the MES tools/user menu stay in their apps. There are no new deps in `@carbon/react`. |+| Badges | ERP `tag` pill for MES counts, hidden at 0; emerald row highlight dropped | Matches the ERP exactly. |+| MES group labels | Replaced by one `NavRailDivider` between queues and tools | The ERP rail has no labels, and labels are invisible when collapsed anyway. |+| Keyboard shortcuts | Stay app-owned (ERP `g`+letter and ⌘K; MES alt+1..7) | MES must avoid bare letters because scanners type into the page (`apps/mes/app/shortcuts.ts`). |+| ERP mobile nav | Replaced by the shared rail's drawer | One source of truth for the item list on mobile too. The ERP drawer content is unchanged in substance. |+| Rail open-state persistence | Not persisted (unchanged; `defaultOpen={false}`) | Out of scope. The cookie is written but was never read before this change either. |+| Item size on MES | 40px (ERP size) instead of 48px touch | User asked for an exact match. 40px meets the repo's ~40px minimum hit area (`.claude/rules/conventions-ui.md`). |++## Data Model Changes++N/A. UI-only; no tables, migrations or RLS.++## API / Service Changes++N/A. There are no loader or action changes. The MES layout loader already returns every prop the rail needs.++## UI Changes++- **ERP:** no intended visual change on desktop. The only change is that ⌘B now pins the rail open. On phones the drawer is the shared one, with the same items.+- **MES:** the sidebar now looks and behaves like the ERP rail:+ - 56px icon rail that expands to 208px on mouse hover, or when pinned by ⌘B or the header trigger.+ - Solid active item and pill count badges.+ - Time Card and avatar menu at the bottom.+ - No company header.+- All new copy (`Open navigation`, avatar `aria-label`) uses Lingui. Existing translated strings are reused.++## Acceptance Criteria++- [ ] `packages/react/src/NavRail.tsx` exists and is exported. `apps/erp/.../PrimaryNavigation.tsx` and `apps/mes/.../AppSidebar.tsx` both render `NavRail`/`NavRailLink`/`NavRailButton`, and neither defines its own item class strings.+- [ ] ERP desktop:+ - The rail is 56px collapsed and 208px on mouse hover.+ - The active module has `bg-active`.+ - The Get Started pill badge still shows.+ - Customize → drag → Save still persists order.+ - ⌘K opens search.+ - `g` then `s` goes to Sales.+ - ⌘B pins the rail open, and pressing it again collapses it.+- [ ] MES desktop:+ - Same 56px/208px widths and hover expand.+ - Visiting `/x/active` highlights Active.+ - Visiting `/x/operations` highlights Schedule, also with the locale set to a non-English language.+ - With 3 active events, Active shows a "3" pill; with 0, no pill.+ - Header toggle and ⌘B pin the rail.+ - Alt+1 goes to Schedule.+- [ ] MES tablet (touch pointer):+ - Tapping an item navigates without first expanding the rail.+ - The page-header toggle expands the rail.+- [ ] MES footer:+ - The Time Card clocks in and out when enabled.+ - The avatar menu switches company and location, toggles dark mode and console mode, and signs out.+ - When an operator is pinned in, the menu shows Switch Operator and hides Sign out.+- [ ] MES tools: Add Inventory, Remove Inventory, End Operations and Suggestion each open their modal from the rail. Displays opens in a new tab.+- [ ] Phone width (<768px) in both apps:+ - The rail is hidden.+ - The trigger (ERP Topbar hamburger, MES page-header toggle) opens a left drawer with the same items.+ - Clicking a link closes it.+- [ ] `pnpm exec turbo run typecheck --filter=@carbon/react --filter=erp --filter=mes` passes, and biome is clean.+- [ ] `packages/react/AGENTS.md` and the carbon-design references (page-archetypes, shop-floor-mes) are updated.++## Non-goals++- MES module customization (reorder/hide), per the Q3 answer.+- Adding a top bar to MES.+- Persisting the pinned state across reloads.+- Migrating `apps/starter` or other `Sidebar*` users. The shadcn primitives stay for them.++## Open Questions++- [x] How should the rail open on MES, where tablets can't hover? — **Answer:** ERP look plus a tap/⌘B toggle. Mouse hover expands, and touch uses the toggle.+- [x] Where do MES's extras go (company header, tools, Time Card, user menu)? — **Answer:** In rail slots. Queues go on top, tools go under a divider, and Time Card plus the avatar user menu go at the bottom. The company header is dropped to match the ERP.+- [x] Should Customize (drag-and-drop reorder/hide) be shared? — **Answer:** No, it stays ERP-only. The shared rail exposes slots, and `@dnd-kit` stays out of `@carbon/react`.+- [x] What happens to MES page-header sidebar toggles? — **Answer:** They are kept and wired to the rail: they pin it on desktop and open the drawer on phones.++## Risks++- `SidebarProvider` renders a wrapper div (`group/sidebar-wrapper flex min-h-svh w-full`). In the ERP layout it has to take over the `flex h-screen` div's role, or wrap it without breaking the inset content panel (`.ai/lessons.md` ~1470: do not add the inset to the rail).+- The ERP search-modal phantom-`mouseenter` fix (`PrimaryNavigation.tsx:82-96`) must survive. The ERP passes `disableHover` while the modal is open and collapses hover on close. The shared `NavRail` needs a way to clear `hovered`, exposed as a `collapseHover()` on an imperative ref or as a `hoverResetKey` prop. The plan picks one.+- Adding exports to `@carbon/react`'s barrel is an Ask First item in `packages/react/AGENTS.md`. Approving this spec covers it.++## Changelog++- 2026-09-29: Spec written after research and four resolved questions.