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(specs): add MES mobile app spec and research
sidgaikwadd9604c889a1e
diff --git a/.ai/research/mes-mobile-app.md b/.ai/research/mes-mobile-app.mdnew file mode 100644index 0000000000..f54316b438--- /dev/null+++ b/.ai/research/mes-mobile-app.md@@ -0,0 +1,329 @@+# MES Mobile App Research: Best Practices Survey++## Summary++Surveyed how ERP and MES vendors put shop-floor operator execution on phones,+tablets and rugged handhelds, and whether Expo + a Tailwind-for-React-Native+library + React Native Reusables is a sound stack for Carbon's small team.+Covered: SAP (Digital Manufacturing, S/4HANA Fiori, SAP Service and Asset+Manager), MES point solutions (Tulip, First Resonance ION, Manufacturo, Fulcrum,+ProShop) and manufacturing ERPs (Odoo, Katana, MRPeasy, Epicor Kinetic, Plex).++Five findings drive the design:++- **Browser-first is the norm for operator screens; native is the exception.**+ SAP's operator dashboard, ION, Fulcrum, ProShop and Katana all run in the+ browser. Native apps come from vendors that need hardware access or one-time+ device registration: Tulip Player, Plex Mobile, SAP Service and Asset Manager,+ and Epicor's partner handheld app.+- **Shared tablets are the dominant device model.** The device is registered+ once, then operators identify themselves quickly by badge, PIN or QR code, and+ labor is attributed to that operator. Seen at Tulip, SAP, Odoo, Fulcrum and+ Katana.+- **Nobody offers offline writes for production execution.** Tulip says so+ outright. Odoo's offline mode is read-only. SAP's offline store exists only+ in its field-service app, and SAP's production execution relies on a+ plant-side edge server instead.+- **Scanning means keyboard-wedge scanners first, camera second.** Label printing+ from the device is weak everywhere and is done server-side or through a relay.+- **Native clients sit behind a mobile-specific backend layer at SAP** (BTP+ Mobile Services in front of the ERP). Fiori web apps call the ERP's OData+ directly.++## Competitors Surveyed++- **SAP S/4HANA + Digital Manufacturing** — the enterprise reference for+ operator execution (Production Operator Dashboard), and for how SAP builds+ native offline apps (Service and Asset Manager on the Mobile Development Kit).+- **Tulip** — the only MES in the survey with native store apps (Tulip Player)+ on iOS, iPadOS and Android.+- **First Resonance ION** — modern hardware-manufacturing MES; browser only,+ QR-to-step flow; its own UI uses its public GraphQL API.+- **Manufacturo** — MES for regulated discrete manufacturing; tablet-driven+ inventory and shop-floor steps.+- **Fulcrum, ProShop** — job-shop ERP/MES with browser shop-floor terminals.+- **Odoo** — Shop Floor module, installable as a PWA, plus an Enterprise store+ wrapper.+- **Katana, MRPeasy** — SMB manufacturing ERPs with shop-floor apps.+- **Epicor Kinetic** — browser MES plus a partner-built native handheld app.+- **Plex (Rockwell)** — native Plex Mobile for iOS and Android with a published+ device support policy.++## Key Consensus Patterns++### 1. Register the device once, then operators switch quickly++- **SAP**: Digital Manufacturing's Badge Access asked for a badge (RFID, barcode+ or typed) on a POD page so shared logins and terminals could be used; labor+ on/off could key on badge numbers. It is deprecated as of 2508 (supported until+ 2611); the replacement was not found.+- **Tulip**: the device is registered once against an instance URL and becomes an+ Interface tied to a Station; operators then sign in by badge ID, RFID or+ credentials, with auto-logout on inactivity.+- **Odoo**: the signed-in user is an operator; others are added with "Edit+ Operators" and an optional numeric PIN. Many can be signed in, one is active,+ and time books to the active one.+- **Fulcrum**: Job Tracking uses a PIN login, which can be replaced by email and+ password plus MFA.+- **Katana**: each operator scans their QR code and types a 6-digit code; for+ shared devices the QR code stays printed at the workstation.+- **Rationale**: shop-floor devices are shared and gloved hands can't type+ passwords, but every labor minute and quantity must still belong to a person.++### 2. Online-first; no offline writes for production++- **SAP**: Service and Asset Manager has a full offline store (an on-device store+ plus an ordered request queue, ETag conflict detection, an ErrorArchive for+ failed requests). Production execution does not: resilience comes from an+ edge server in the plant that rides out "a few hours" of cloud outage.+- **Tulip**: no offline. Staff called it a year-plus effort and suggested WiFi+ extenders. Its docs warn that an unstable network makes the trigger queue drop+ events permanently.+- **Odoo**: offline mode is read-only, limited to views opened earlier.+- **Rationale**: several stations write to the same job at once; replaying+ stale writes later corrupts quantities and time.++### 3. Keyboard-wedge scanning, camera as fallback++- **SAP**: the operator dashboard offers a camera preview plus a manual field+ that also accepts scanner input. SAP's native Android SDK supports Zebra and+ Honeywell built-in scanners through the DataWedge intent API, and Bluetooth+ scanners in keyboard mode only.+- **Tulip / Odoo / ION / Katana web**: USB or Bluetooth scanners acting as+ keyboards that send Enter; Zebra devices set to DataWedge keystroke output.+ Camera scanning in Tulip, Katana's shop-floor app and MRPeasy.+- **Rationale**: keyboard mode works on every device with no native code;+ rugged-device intents are an optimisation.++### 4. Printing happens on the server, not the device++- **SAP**: Digital Manufacturing manages printers and print queues and prints+ server-side; no source found for printing from the device.+- **Tulip**: the Zebra network printer driver is Windows-only, so iPads need an+ edge device or a nearby Windows player.+- **ION**: Zebra Browser Print (a desktop app) or PrintNode relaying through a+ computer.+- **Rationale**: mobile OSes make raw network or Bluetooth printing hard; a+ server or relay already knows the printers.++### 5. The operator action set is consistent++Start, pause and finish an operation with setup/labor/machine time; report+good, scrap and rework quantities; consume or issue material by scan; follow+work instructions; record data and photos; raise a quality issue; clock in and+out. Seen at SAP (yield/scrap/activity confirmations, goods issue, data+collection, NCs), Odoo, Fulcrum, Katana, Epicor's handheld app and Plex.++### 6. Native clients use a mobile backend or the vendor's public API++- **SAP**: native apps go device → BTP Mobile Services (onboarding, auth, app+ lifecycle, offline sync) → Cloud Connector → Gateway OData. Posting from+ Digital Manufacturing to the ERP uses a *sequential* queue for quantity+ confirmations because order matters.+- **ION**: its own clients use the same public GraphQL API.+- **Epicor partner app**: calls Kinetic's REST API and recommends extending the+ token lifetime to 10 hours (a shift).+- **Rationale**: a dedicated layer owns auth, versioning and ordering so the+ ERP core does not have to know about devices.++## Answers to Research Questions++1. **Native app or web?** — Mostly web. Native where hardware access, device+ registration or store distribution matter: Tulip, Plex, SAP Service and+ Asset Manager, Epicor's partner app (native Android). Odoo and MRPeasy ship+ store wrappers around the web client.+2. **Operator identity on shared devices?** — Device registered once, then badge,+ PIN or QR plus code per operator (SAP, Tulip, Odoo, Fulcrum, Katana).+3. **Offline?** — Not for production writes anywhere. SAP's offline store is+ field-service only; Odoo offline is read-only; Tulip has none.+4. **Which operator actions?** — Pattern 5 above.+5. **Hardware?** — Keyboard-wedge scanners plus camera. Printing server-side.+ Bluetooth gauges on mobile: not found for any vendor (Tulip's caliper driver+ is Windows-only).+6. **API architecture?** — SAP puts a mobile backend in front of the ERP and+ orders quantity confirmations; ION and Epicor's partner app use public APIs.+ No vendor documents client-side idempotency keys; SAP relies on ETags and an+ ordered queue.+7. **Distribution?** — Public App Store and Google Play (Tulip, Plex, SAP,+ Odoo, MRPeasy, Epicor partner app). Server URL typed at first launch (Epicor+ partner app, Tulip instance URL; a QR code can carry it). No MDM guidance+ found for any manufacturing vendor.+8. **Is Expo + NativeWind + React Native Reusables sound for Carbon?** — Expo+ yes. NativeWind's stable release only supports Tailwind v3, and Carbon web is+ on Tailwind 4.3; Uniwind supports Tailwind v4 today and is supported by React+ Native Reusables. See the technology section.++## Competitor-Specific Details++### SAP+- The Production Operator Dashboard is a browser (SAPUI5) app that supports+ touch and mobile screens. Each POD has its own URL; operators bookmark it or+ scan a QR code, and URL parameters preset the machine.+- Fiori "Confirm Production Operations" is a responsive web app.+- SAP Mobile Start is SAP's native entry point (iOS 2021, Android 2022),+ rolled out by QR code or MDM.+- Terminology: confirmation (partial/final), yield, scrap, rework, activity+ confirmation, backflush, goods issue/receipt, labor on/off, clock in/out,+ badge, nonconformance, disposition.++### Tulip+- Tulip Player on iPhone, iPad, Apple Silicon Mac (iOS 15.1+, SAML login) and+ Android phones and tablets. The native app is recommended over the web+ player for hardware access and one-time admin authentication.+- In GxP mode a logout cancels the running app without saving; on iOS,+ backgrounding the app counts as closing it.++### Odoo+- Shop Floor replaced the tablet view in 16.4. Store apps do not support SSO.+- Public XML-RPC/JSON-RPC APIs are removed in Odoo 22 in favour of JSON-2 with+ bearer API keys.++### Katana+- "Not a native Android or iOS app"; tablets recommended, phones supported,+ every device needs a camera. One session per account.++### Epicor Kinetic+- Browser MES; the native handheld app (Epicor Kinetic Warehouse, by BISCIT)+ runs on Honeywell and Zebra Android devices. A device licence key, then+ Epicor or Azure AD login; a QR code can carry the username and server URL.++### Plex+- Plex Mobile on iOS and Android since 2018, organised into "applets". Its+ support policy lists tested rugged devices (Honeywell CT60/CK65, Zebra+ MC3400/TC52X and others) and supported OS ranges (Android 11–14, iOS 15–17).++## Technology Findings (checked 24–26 Sep 2026)++- **Expo SDK 57** (stable 30 Jun 2026): React Native 0.86, React 19.2. The New+ Architecture is mandatory. Expo Router is the default for new apps.+- **Expo monorepos**: Metro configures itself for monorepos (SDK 52+); pnpm+ isolated installs are supported from SDK 54. "Duplicate React Native+ versions in a single monorepo are not supported" and "Duplicate React version+ in a single app will cause runtime errors". Different React versions in+ different apps are not forbidden.+- **NativeWind**: stable 4.2.7 supports Tailwind v3 only; v5 (Tailwind v4) is+ a release candidate its docs call "not intended for production use".+ Documented v4 performance issues: a ~4× slowdown against StyleSheet in a+ 1,000-view benchmark, a 4 MB interop cache costing ~250 ms at startup, and a+ memory leak around CSS variables.+- **Uniwind** (from the Unistyles team): Tailwind v4, MIT core, releases+ roughly every two weeks (1.12.0 on 4 Sep 2026). A paid Pro tier adds a C+++ engine; not needed.+- **React Native Reusables**: a shadcn/ui port on `@rn-primitives`, copied into+ the consuming repo. 31 components; no data table, toast, date picker,+ combobox or sheet (the repo points to community libraries). Uniwind supported+ since Dec 2025. Effectively one maintainer (1,114 commits vs 17 for the next+ contributor).+- **Gluestack UI v5** (stable July 2026): the closest alternative to React Native+ Reusables, with more components, supporting both NativeWind v5 and Uniwind.+- **Supabase on Expo**: the official guide persists the session with an+ encrypted SecureStore wrapper (SecureStore caps values at 2 KB); PKCE flow+ for deep-link sign-in.+- **Hardware**: `expo-camera` scans 13 barcode formats. Zebra's own DataWedge+ React Native library has been archived since 2021, so intent-mode scanning+ needs a custom Expo module; keystroke mode needs none.++## Recommended Approach for Carbon++1. **Native app, tablet-first, phone supported** — following Tulip and Plex:+ native is justified by hardware access (camera, keep-awake, later DataWedge+ intents), device registration and store distribution.+2. **Shared-tablet mode in v1, not later** — every surveyed vendor with a+ shop-floor app supports quick operator switching on a shared device (Pattern+ 1). Carbon already has this on web (console mode), so the mobile app should+ ship it, using a server-verified operator identity rather than a cookie.+3. **Online-first with a short ordered outbox** — nobody offers offline+ production writes (Pattern 2). An outbox for brief Wi-Fi drops, sent in+ order per operation (the SAP sequential-queue idea), with server-side+ duplicate protection, is the most any vendor does.+4. **Keyboard-wedge scanning plus camera; printing through the existing+ server path** — Patterns 3 and 4. No native printer code in v1.+5. **A dedicated MES API in front of the backend** — the SAP pattern for native+ clients (Pattern 6), and in Carbon the MES write logic already lives in+ server code that a device cannot call.+6. **Store distribution with a server address at first launch** — the Epicor+ partner app and Tulip pattern; supports Carbon Cloud and self-hosted installs+ from one build.+7. **Uniwind rather than NativeWind** — same Tailwind version as Carbon web.++## Sources++SAP+- https://help.sap.com/docs/sap-digital-manufacturing/execution/production-operator-dashboard-pod+- https://learning.sap.com/courses/exploring-customization-in-sap-digital-manufacturing/providing-pods-to-operators+- https://help.sap.com/doc/saphelp_ssb/1.0/en-US/df/ec39520c3b6160e10000000a423f68/content.htm?no_cache=true+- https://community.sap.com/t5/technology-blog-posts-by-members/sap-mobile-start-the-new-native-entry-point-to-access-applications-contents/ba-p/13514662+- https://learning.sap.com/courses/implementing-sap-service-and-asset-manager/explaining-sap-service-and-asset-manager-features+- https://developers.sap.com/tutorials/cp-mobile-dev-kit-build-client.html+- https://community.sap.com/t5/supply-chain-management-blog-posts-by-sap/enable-faster-user-changes-and-shared-terminals-using-badges-in-sap-digital/ba-p/13789397+- https://community.sap.com/t5/supply-chain-management-blog-posts-by-sap/clock-in-out-and-labor-on-off-with-sap-digital-manufacturing/ba-p/13561374+- https://help.sap.com/doc/13c9f83611f94a5ab2c94f23cacfc217/latest/en-US/SAP_DMC_FSD_enUS.pdf+- https://help.sap.com/doc/f53c64b93e5140918d676b927a3cd65b/Cloud/en-US/docs-en/guides/features/offline/overview.html+- https://help.sap.com/doc/f53c64b93e5140918d676b927a3cd65b/Cloud/en-US/docs-en/guides/features/offline/common/handling-errors-and-conflicts/offline-errors-troubleshooting.html+- https://help.sap.com/docs/sap-digital-manufacturing/setup-and-operations-guide-for-sap-digital-manufacturing-for-edge-computing/basic-concepts-426b451ca7574eb895ea86d93437005d+- https://help.sap.com/doc/f53c64b93e5140918d676b927a3cd65b/Cloud/en-US/docs-en/guides/features/fiori-ui/android/qrcode-view.html+- https://learning.sap.com/courses/implementing-sap-service-and-asset-manager/explaining-the-mobile-application-integration-framework-maif-+- https://help.sap.com/doc/f6b2ab2222794bebad4c0dcd33138e71/latest/en-US/SAP_DMC_Integration_Guide_enUS.pdf++MES point solutions+- https://apps.apple.com/us/app/tulip-player/id1634675541+- https://play.google.com/store/apps/details?id=co.tulip.player+- https://support.tulip.co/docs/tulip-player-overview+- https://support.tulip.co/docs/player-logout-behavior+- https://community.tulip.co/t/offline-apps-connectivity/403+- https://support.tulip.co/docs/tulip-cloud-deployment-networking-requirements+- https://support.tulip.co/docs/set-up-a-barcode-scanner+- https://community.tulip.co/t/support-for-zebra-network-printer-driver-on-ios/9465+- https://manual.firstresonance.io/features/runs/run-execution-overview+- https://manual.firstresonance.io/features/runs/time-tracking+- https://manual.firstresonance.io/features/barcode-labels/scanning+- https://manual.firstresonance.io/features/barcode-labels/printing/configuring-printing-in-ion+- https://manual.firstresonance.io/api/about-graphql+- https://manufacturo.com/manufacturo-manufacturing-management-software/inventory-management/+- https://manufacturo.com/integration/+- https://fulcrumpro.com/manufacturing-software/job-tracking+- https://fulcrumpro.com/article/best-hardware-choices-for-fulcrum-on-the-shop-floor+- https://fulcrumpro.com/product-update/log-in-to-job-tracking-without-a-pin+- https://get.proshoperp.com/++Manufacturing ERPs+- https://www.odoo.com/documentation/17.0/applications/inventory_and_mrp/manufacturing/shop_floor/shop_floor_overview.html+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/manufacturing/shop_floor/shop_floor_tracking.html+- https://www.odoo.com/documentation/19.0/applications/general/offline_mode.html+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/barcode/setup/hardware.html+- https://www.odoo.com/documentation/17.0/administration/mobile.html+- https://www.odoo.com/documentation/19.0/developer/reference/external_api.html+- https://support.katanamrp.com/en/articles/5967150-recommended-devices-for-the-shop-floor-control-app+- https://support.katanamrp.com/en/articles/5967433-how-to-log-into-a-shop-floor-operator-account+- https://support.katanamrp.com/en/articles/5966964-barcode-scanning-hardware+- https://www.mrpeasy.com/resources/user-manual/reporting/internet-kiosk/+- https://apps.apple.com/us/app/mrpeasy/id1179387308+- https://www.epicor.com/en-us/products/enterprise-resource-planning-erp/kinetic/supply-chain-management/ptw-warehouse/+- https://docs.biscit.com/epicor-kinetic-warehouse/epicor-kinetic-warehouse-user-guide/login.md+- https://docs.biscit.com/epicor-kinetic-warehouse/epicor-kinetic-warehouse-installation-guide/ekw-installation-guide.md+- https://apps.apple.com/us/app/plex-mobile/id1410847591+- https://plex.rockwellautomation.com/content/dam/plex/documents/pdf/plex-mobile-support-policy-v4-2025-1.pdf++Technology+- https://expo.dev/changelog/sdk-57+- https://docs.expo.dev/guides/monorepos/+- https://docs.expo.dev/guides/dom-components/+- https://www.nativewind.dev/v5+- https://github.com/nativewind/nativewind/discussions/642+- https://github.com/nativewind/nativewind/issues/1071+- https://docs.uniwind.dev/+- https://github.com/founded-labs/react-native-reusables+- https://github.com/gluestack/gluestack-ui/discussions/3366+- https://supabase.com/docs/guides/getting-started/tutorials/with-expo-react-native+- https://docs.expo.dev/versions/latest/sdk/camera/+- https://developer.zebra.com/blog/integrating-datawedge-your-expo-application++## Not Verified++- What replaces SAP Digital Manufacturing Badge Access after 2611.+- Operator identity at ProShop, Manufacturo and Plex (Plex docs are behind a+ login).+- Offline write queues or client idempotency keys at any vendor other than+ SAP's field-service app.+- Whether MRPeasy's store app is a web wrapper (inferred from a 478 KB iOS+ build and its listing wording).diff --git a/.ai/specs/2026-09-30-mes-mobile-app.md b/.ai/specs/2026-09-30-mes-mobile-app.mdnew file mode 100644index 0000000000..32154fb1ee--- /dev/null+++ b/.ai/specs/2026-09-30-mes-mobile-app.md@@ -0,0 +1,671 @@+# MES Mobile — a native iOS and Android app for the shop floor++> Status: draft+> Author: Claude (with Sid)+> Date: 2026-09-30+> Research: `.ai/research/mes-mobile-app.md`++## TLDR++Build a native MES app for operators on tablets and phones, in this monorepo at+`apps/mes-mobile`, with Expo SDK 57, Expo Router, Uniwind and React Native+Reusables. The app never gets the service-role key and never calls a web route+action. Everything that changes data goes through a new **MES API**+(`apps/mes/app/routes/api+/v1+/`), which runs the *same* server code as today's+web MES routes, because the web actions and the API both call one extracted+module (`commands.server.ts`). The three main screens (operations list,+operation detail, picking) also load through the API, so operators see exactly+what web MES shows them. The app reads simple lookups, subscribes to live+changes and uploads photos straight to Supabase as the signed-in user.++v1 covers core execution: time, good/scrap/rework, material by scan, work+instructions and step records with photos, notes, quality issues, labels,+picking and clock in/out. It supports both personal sign-in (emailed 6-digit+code plus 2FA) and shared tablets, where operators pin in with their console+PIN. It is online-first with a short, ordered, de-duplicated outbox for Wi-Fi+drops.++## Problem Statement++Carbon's MES is a server-rendered web app (`apps/mes`, React Router v7). It+works in a tablet browser, but:++- **No native device features.** A browser can't keep the screen awake on a+ wall-mounted tablet, can't reach Zebra DataWedge scan intents, and loses the+ camera between pages. Vendors that ship native shop-floor apps (Tulip, Plex,+ SAP Service and Asset Manager) cite hardware access and one-time device+ registration as the reason (research, Pattern 1).+- **No store distribution.** Customers who manage devices with MDM want an app+ they can push from the App Store or Google Play, not a bookmark.+- **Nothing a native client can call.** Every MES write is a React Router route+ action behind a cookie session, and most run with the service-role key after a+ sign-in check only (`requirePermissions(request, {})` in `x+/complete.tsx`,+ `x+/start.$operationId.tsx`, `x+/operations.tsx` and 10 others). The ERP's+ public API accepts API keys only and acts as the key's creator, so it can't+ attribute work to individual operators.++## Scope++**In v1** (answer to Q1):++- Operations list and detail for the chosen location and work centers+- Start, pause and finish setup, labor and machine time; end an operation+- Report good, scrap and rework quantities+- Issue material by scan (untracked and tracked entities), and undo an issue+- Work instructions, and step records with photos+- Operation notes+- Raise a quality issue+- Print labels to the printers web MES already uses+- Picking lists: pick quantities, tracked picks, list status+- Clock in, clock out, end shift+- Shared-tablet mode with console PIN switching++**Stays on web MES for now:** inspections and inspection lots, batches,+maintenance dispatch, the 3D assembly view, drawings with markup, work-center+TV displays. **Never in this app:** ERP screens.++## Proposed Solution++### Architecture++```+ MES Mobile (Expo, iOS/Android) apps/mes server (React Router)+ ┌────────────────────────────┐ ┌──────────────────────────────────┐+ │ Expo Router screens │ commands + │ api+/v1+/* (NEW, Bearer JWT) │+ │ TanStack Query cache │ screen reads │ requireApiUser → idempotency → │+ │ Outbox (expo-sqlite) │──────────────▶│ zod (mes-core) → command/screen │+ │ supabase-js (user session) │ │ x+/* route actions (web, cookie) │+ └──────┬──────┬──────┬───────┘ │ parse form → same command │+ │ │ │ │ services/commands.server.ts (NEW) │+ sign-in lookups live changes, photos │ services/screens.server.ts (NEW) │+ │ │ │ └───────────────┬──────────────────┘+ ▼ ▼ ▼ │ invoke / write+ ┌──────────────────────────────────────────────────────────────▼──────────────┐+ │ Supabase: Auth · PostgREST (RLS) · Realtime · Storage · Edge functions │+ │ (issue, post-production-event, post-picking) · Postgres triggers │+ └─────────────────────────────────────────────────────────────────────────────┘+```++| Path | Goes to | Signed in as | Used for |+|---|---|---|---|+| Sign-in | MES API `POST /auth/code`, then Supabase Auth `verifyOtp` | — | Requesting and entering the emailed code |+| Commands | MES API | Operator (Bearer JWT, plus operator token on shared tablets) | Every change of state |+| Screen reads | MES API `GET` endpoints | Same | Operations list, operation detail, picking, timecard |+| Lookups | Supabase PostgREST | Signed-in user | `location`, `workCenter`, `item`, `trackedEntity`, `jobOperationNote` (read) |+| Live changes | Supabase Realtime | Signed-in user | Refetch triggers |+| Photos | Supabase Storage | Signed-in user | Step-record photos |++**Why writes go through the API.** RLS would let an employee insert a+`productionEvent` row directly, but each web action does more around the write:+material backflush (`issue`), cost posting (`post-production-event`),+tracked-entity genealogy, returning picked leftovers (`post-picking`), workflow+moments (`raiseMoment`), the floor gate in `start` (checked before the timer+reopens, per `.claude/rules/mes-job-operation-ui.md`), and the picking-list+policies (`incompletePickingListPolicy`, enforced server-side per+`2026-07-24-mes-material-picking-behavior.md` D7). A client writing tables+would skip all of it. Calling edge functions from the device doesn't work+either: multi-step commands are orchestrated in route actions, and+`functions/lib/supabase.ts` `requirePermissions` rejects a token whose subject+is not the payload `userId`, which rules out shared tablets.++**Why the main screens read through the API.** The web loaders read with the+service-role key after a sign-in check (`x+/operations.tsx:132`,+`x+/operation.$operationId.tsx:41`). Direct reads would hit RLS rules that+require `production_view` (`productionEvent`,+`20260228000000_rls-refactor-3.sql:1005`) and `inventory_view` (`pickingList`,+`20260601143527_picking-lists.sql:470`), so operators without them would see+less than on web. Lookups keep going direct because their tables only require+an employee of the company.++### Shared-tablet mode++Web MES already has this as console mode: a terminal signed in as one user,+operators pinning in with a PIN, every action attributed to the pinned operator.+Since PR #1734 and `20260926141957_employee-pin.sql`, the pin-in is a signed+cookie bound to the company and the terminal's session user, re-validated on+every request (`@carbon/auth/console-pin.server`), and PINs are bcrypt hashes in+`employeePin`, checked with `verifyEmployeePin` (`@carbon/ee/console.server`).+Console mode is a commercial feature: it is on only when+`isConsoleModeEnabledForCompany` says so (the `consoleEnabled` flag plus the+`PERMISSIONS` entitlement).++The app mirrors this with two signed tokens instead of cookies:++1. **Terminal token.** "Use this tablet as a shared terminal" (More screen) calls+ `POST /console/terminal`. It requires `settings_update` for the signed-in+ user and `isConsoleModeEnabledForCompany`, like `x+/console.toggle.tsx`.+ The server returns a terminal token signed with `SESSION_SECRET`, bound to+ `(companyId, sessionUserId)`. Leaving shared-terminal mode needs no+ permission; the app discards both tokens.+2. **Operator token.** An operator picks their name and enters their PIN:+ `POST /console/pin-in` with the terminal token. The server applies the same+ PIN lockout and terminal rate limit as `x+/console.pin-in.tsx` (moved into a+ shared helper), calls `verifyEmployeePin(getDatabaseClient(), …)`, and returns+ an operator token signed with `SESSION_SECRET`, holding the+ `StoredConsolePinIn` shape (`userId`, `companyId`, `sessionUserId`,+ `pinnedAt`). It expires after 1 hour idle, or the idle-lock window in a+ controlled environment, the same rule as `consolePinMaxAgeMs`.+3. Every API response to a console call returns a refreshed operator token in+ `X-Carbon-Operator` (the web refreshes `pinnedAt` on each shell navigation).+ `requireApiUser` re-validates each call like `resolveConsolePinIn`: the+ signature, the binding, the idle window, console mode still enabled, and the+ operator still an active employee of the company.+4. Commands run as the operator (`createdBy`, labor attribution). Reads and+ subscriptions keep running as the terminal user, as on web today.++Tokens live in memory only (the operator token) or SecureStore (the terminal+token), never in the query cache.++### Sign-in and session++1. **Server address.** First launch asks for the Carbon server, defaulting to+ Carbon Cloud's MES address. A QR code (`carbon-mes://configure?server=…`)+ fills it in. `GET /api/v1/config` (public) returns that server's+ `supabaseUrl`, `supabaseAnonKey`, `apiVersion` and `minAppVersion`. The anon+ key is public by design (it already ships in the web apps' HTML).+2. **Request a code.** `POST /api/v1/auth/code { email }` runs the same gates as+ the MES login action (`_public+/login.tsx`): the IP rate limit, the per-account+ lockout (`AccountLockout`), the user-exists check, and the SSO-required+ refusal (`isSsoRequiredForEmail`, returned as `sso_required`). It then sends+ the email the web sends (`signInWithOtp` server-side, as `sendMagicLink`+ does). Web bot protection (BotID/Turnstile) is browser-only, so the app+ relies on the rate limit and lockout, which are the NIST controls.+ Requesting the code straight from Supabase Auth would skip all four gates.+ The response is `{ method: "code" }`, except for store-review accounts (next+ step).+ **Store-review accounts (Q11).** Apple and Google reviewers can't receive an+ emailed code. For an email in `APP_REVIEW_EMAILS` (read through+ `@carbon/env`, set only on Carbon Cloud, empty everywhere else so the path+ is off), `/auth/code` sends nothing and returns `{ method: "password" }`.+ The app then shows a password field and calls `POST /api/v1/auth/password`,+ which refuses any email outside the allow-list, applies the same rate limit+ and lockout, signs in with the account's password server-side and returns+ the session. The review account is an ordinary employee of a demo company on+ Carbon Cloud with no other access. Normal users never see a password field.+3. **Enter the code.** The magic-link email template gains the 6-digit code+ (`{{ .Token }}`) next to the existing link, so web users see the same email+ with a code added. The app calls `supabase.auth.verifyOtp({ email, token,+ type: "email" })` and gets a session.+4. **2FA.** If `userHasVerifiedTotpFactor(userId)`, the app runs Supabase's+ TOTP challenge and verify, raising the session to `aal2`. `requireApiUser`+ rejects an `aal1` token from such a user with `mfa_required`, mirroring the+ web's `mfaVerified` bounce. Enrolment stays in ERP ("MES defers first login+ to ERP").+5. **Session storage.** The supabase-js client stores its session in+ `expo-secure-store` behind an encryption wrapper (SecureStore caps values at+ 2 KB), per Supabase's Expo guide. Token refresh pauses in the background.+6. **Context.** `GET /api/v1/me` returns companies, locations, the default+ location (`employeeJob.locationId`), work centers, whether console mode is+ available, and the permission flags the UI uses to disable controls. The+ chosen company, location and work centers are stored per device.++SSO sign-in is v1.1. Until then, users of SSO-required domains get a clear+refusal, and those companies use shared-tablet mode with a non-SSO terminal+account or wait for v1.1.++### Offline outbox++Online-first. The outbox covers brief Wi-Fi drops; no vendor surveyed offers+offline production writes (research, Pattern 2).++- Each command is a row in `expo-sqlite`: id, companyId, sessionUserId,+ operator userId, operationId, method, path, body, idempotency key, createdAt,+ attempts, state, last error. Rows are keyed by company; switching company+ pauses the other company's rows.+- Rows for the same operation send in order (SAP's sequential queue for+ quantity confirmations is the precedent). Rows with no operation (clock-in)+ share one lane.+- States: `queued → sending → done`. A network failure, a timeout, `503+ retry_later` or `409 request_in_progress` means **waiting to retry** with the+ same key (backoff 2 s → 60 s), which is safe because the server either never+ ran the command or de-duplicates it. Any other 4xx, or a 5xx the server+ stored, means **needs attention**: the operation's lane stops, the operator+ sees what failed and chooses Retry (new key, after the screen refetches) or+ Discard.+- Rows older than 8 hours (one shift) are never sent automatically. The operator+ confirms or discards each one, so a forgotten "start labor" can't post hours+ later.+- An expired operator token returns `401 operator_expired`. The row moves to+ needs attention until the operator pins in again.+- Signing out is blocked while rows are queued, with a screen listing them.+- A banner shows "Offline · 3 actions waiting". Cached screens show when they+ were last updated.++### Duplicate protection (server)++Every `POST` carries `Idempotency-Key`. The API keeps it in Redis (`@carbon/kv`,+already an ioredis client MES depends on) under+`(companyId, sessionUserId, key)`, together with a fingerprint of method, path+and body:++- Unseen key: `SET NX` an in-progress marker (5-minute expiry), run the command,+ then store the status and body for 24 hours.+- Key in progress: `409 request_in_progress`.+- Completed key: replay the stored response, **including a stored 5xx**. An+ automatic retry therefore never re-runs a command whose first run may have+ partly applied (lesson: "Retrying a 5xx from a non-idempotent Edge Function+ multiplies its side effects"). A retry after a 5xx needs a new key, which only+ the operator's Retry creates.+- Same key, different fingerprint: `422 idempotency_key_reused`.+- Redis unavailable: `503 retry_later`, returned before the command runs.++### Device features++| Need | v1 | Later |+|---|---|---|+| Handheld scanners (Zebra, Honeywell) | Keyboard mode: a focused hidden input catches the scan plus Enter, as web MES does | Own Expo module for DataWedge intents (Zebra's React Native library is archived) |+| Camera scanning | `expo-camera` barcode scanning | VisionCamera + ML Kit if speed matters |+| Photos | `expo-image-picker`, saved as JPEG on the device, uploaded to `{companyId}/job/{operationId}/{stepId}/{nanoid}/{filename}` (the `parseJobFilePath` contract), with a sanitised filename | — |+| Labels | `POST /print` → `trigger("print-job")` → Inngest → ProxyBox, as `x+/print.tsx` does | Bluetooth Zebra printers |+| Screen stays on | `expo-keep-awake` on operation screens | Android kiosk lock (needs the customer's MDM) |++### Distribution and versioning++- One public App Store listing and one Google Play listing under Carbon's+ developer accounts, named "Carbon MES". Bundle and package id+ `ms.carbon.mes` (reverse DNS of Carbon's domain; changeable until the first+ store submission). URL scheme `carbon-mes`.+- EAS Build profiles `development`, `preview` (TestFlight, Play internal+ testing) and `production`. EAS Update channels `preview` and `production`,+ runtime version from a fingerprint of the native code.+- `/api/v1` changes are additive. A breaking change needs `/api/v2`, and v1+ stays until the oldest supported app release stops using it. The two most+ recent store releases are supported. `minAppVersion` in `/config` lets the+ server show "Update required" to anything older.+- Self-hosted installs use the same store build: the server address screen, or+ the QR code, points it at their install.++### Design Decisions++| Decision | Choice | Rationale |+|---|---|---|+| App type | Native (Expo), tablet-first, phones supported | Hardware access and device registration (Tulip, Plex precedent); CTO recommendation |+| Where it lives | `apps/mes-mobile` in this monorepo | The API and the app change in one PR; types, validators, translations and tokens are shared without publishing (Q7) |+| React versions | Web stays on 18.3.1; the app uses React 19.2 | Expo forbids two React Native versions per monorepo and two React versions per app, not different React per app. The global pin becomes scoped (see Tooling) |+| Styling | Uniwind (Tailwind v4) | NativeWind stable supports Tailwind v3 only; Carbon web is Tailwind 4.3 |+| Components | React Native Reusables, copied in; Gluestack UI v5 as fallback | shadcn model like `@carbon/react`; we own the code, so the one-maintainer risk is contained |+| Write path | MES API in `apps/mes` running extracted commands | One code path for web and native, per-operator attribution (Q5) |+| Read path | API for operations, operation detail, picking, timecard; direct for lookups | Parity with the web loaders' service-role reads |+| Permissions | Same as each web route today: signed-in employee of the company; quality issue keeps `create: "quality"`; shared-terminal mode keeps `update: "settings"` | Parity (Q4); tightening changes who can use web MES too |+| Sign-in | Emailed code through the MES server, then 2FA; SSO in v1.1; password only for allow-listed store-review accounts | Keeps the rate limit, lockout and SSO-required gates (Q3); store reviewers can't receive codes (Q11) |+| Shared tablets | In v1, via signed terminal and operator tokens | The dominant device model at every surveyed vendor (Q2) |+| Offline | Online-first, ordered outbox, 8-hour stale limit, Redis de-duplication | Nobody offers offline production writes (Q6) |+| Licensing | Community edition; shared-tablet mode only where console mode is entitled | Same as web MES (Q8) |+| Distribution | Public store listings, server address at first launch | Tulip and Epicor partner-app pattern; one build for Cloud and self-hosted (Q9) |+| Translations | Reuse the `mes` Lingui catalog | One set of strings for translators (Q10) |+| Analytics and errors | PostHog (`posthog-react-native`), as web MES uses PostHog | No new vendor |+| 1 · Multi-tenancy | No new tables. Every API call takes `X-Carbon-Company`, checked against the user's claims; every query scopes `companyId`; every persisted client cache and outbox row is keyed by company, and hydration is guarded against a mid-flight company switch | Lesson "Client-side entity caches must be company-keyed" |+| 2 · Service shape | `@carbon/mes-core` queries take `client` first and return `{ data, error }`; `commands.server.ts` and `screens.server.ts` take `client` / `db` arguments and never build a DB client in a `*.service.ts` | `conventions-services.md`, `no-db-client-in-service` |+| 3 · RLS coverage | No new tables; direct lookups rely on existing employee-of-company policies | — |+| 4 · Permission scoping | Each endpoint mirrors its web route's `requirePermissions` argument | Parity (Q4) |+| 5 · Form pattern | Web routes keep `ValidatedForm` + `zfd` schemas; the API validates JSON with the plain zod schemas in `@carbon/mes-core`, which the web schemas wrap | One set of rules for both |+| 6 · Module layout | MES stays flat; two new `.server` modules; `packages/mes-core` gets its own `AGENTS.md` | `module-conventions.md`, `keep-sources-in-sync` |+| 7 · Backward compatibility | Web route paths unchanged; validators re-exported from `~/services/models` with `@deprecated`; edge function names and payloads unchanged; `/api/v1` is new and additive-only | `BACKWARD_COMPATIBILITY.md` (route paths and validators are STABLE) |++## Data Model Changes++N/A: no tables, columns or migrations. Idempotency lives in Redis, tokens are+signed rather than stored, and the realtime publication is unchanged.++Non-schema configuration changes:++- `packages/database/supabase/templates/magic-link.html` adds `{{ .Token }}`.+ The same change is applied to each hosted Supabase project's email template+ and the self-hosted Docker setups that ship the template+ (`packages/dev/docker/docker-compose.dev.yml`,+ `contrib/deploying/simple-docker-caddy/docker-compose.prod.yml`).+- Supabase Auth's redirect allow-list is unchanged: code sign-in has no+ redirect.++## API / Service Changes++### `packages/mes-core` (new, plain TypeScript)++Imports only `zod`, `@carbon/database` types and `@supabase/supabase-js` types.+No React, DOM or Node APIs.++- `src/models.ts` — JSON zod schemas for every command body, moved from+ `apps/mes/app/services/models.ts` (467 lines, `zfd`-based). The web file keeps+ its exports, wrapping these schemas with `zfd` where it needs form parsing.+- `src/queries.ts` — lookup reads used by the app: `(client, args) => { data,+ error }`, each scoped by `companyId`.+- `src/contract.ts` — request and response types for every endpoint, the error+ shape, and header names. Both the server routes and the app import them.++### `apps/mes/app/services/commands.server.ts` and `screens.server.ts` (new)++The body of each route action in the table below moves into a command function,+and each listed loader body into a screen function. The route becomes: parse the+form, call the command, redirect or return data as today. The API endpoint+becomes: `requireApiUser`, idempotency, parse JSON, call the same command,+return JSON. Behaviour that must survive the move, per+`mes-job-operation-ui.md`: the floor gate runs before the timer reopens in+`start`; `end` stays ungated; ending a batch-tagged event skips+`post-production-event`; auto-print after `complete` never blocks the+operation; scrap stays one `issue` `jobOperationScrap` invoke.++### `@carbon/auth` (new server functions)++- `requireApiUser(request, permissions?)` → `{ companyId, userId, sessionUserId,+ consoleMode, claims }`, or throws a JSON error `Response` (never a redirect):+ 1. Read `Authorization: Bearer <token>`. Reject `crbn_…` API keys (those+ belong to the ERP API).+ 2. Verify the token with Supabase Auth (`auth.getUser(token)`).+ 3. Read `X-Carbon-Company`; load claims with `getUserClaims(userId,+ companyId)` (Redis-cached, as on web). Require the employee role. Apply+ `permissions` exactly like `requirePermissions`.+ 4. If the user has a verified TOTP factor and the token is not `aal2`: `401+ mfa_required`.+ 5. If `X-Carbon-Operator` is present: verify the operator token and terminal+ binding and re-validate as in [Shared-tablet mode](#shared-tablet-mode).+ `userId` becomes the operator.+ 6. Apply a per-user rate limit (`Ratelimit` from `@carbon/kv`).+- `signTerminalToken` / `verifyTerminalToken`, `signOperatorToken` /+ `verifyOperatorToken`, next to `console-pin.server.ts` and sharing its+ `StoredConsolePinIn` shape and re-validation.+- The PIN lockout and terminal rate limit move from `x+/console.pin-in.tsx`+ into a shared helper that the web route and the API both call.++Commands use the service-role client after `requireApiUser`, exactly as the web+routes do after `requirePermissions`.++### MES API — `apps/mes/app/routes/api+/v1+/`++Every request sends `Authorization`, `X-Carbon-Company`, `X-Carbon-App-Version`,+and, when relevant, `X-Carbon-Location`, `X-Carbon-Operator` and+`Idempotency-Key` (every `POST`). No CORS headers: the API is for the native+app, not browsers. Errors are `{ error: { code, message, fields? } }`.++**Meta and auth**++| Endpoint | Auth | Does |+|---|---|---|+| `GET /config` | Public | Supabase URL, anon key, API version, minimum app version |+| `POST /auth/code` | Public, rate-limited | The MES login gates, then sends the code email; returns `{ method: "code" \| "password" }` |+| `POST /auth/password` | Public, rate-limited | Store-review accounts only (`APP_REVIEW_EMAILS`); returns a session |+| `GET /me` | User | Companies, locations, default location, work centers, console availability, permission flags |+| `POST /console/terminal` | User with `update: "settings"` | Terminal token (console mode must be enabled) |+| `POST /console/pin-in` | Terminal token | PIN check with lockout, operator token |+| `POST /console/pin-out` | Operator | Ends the pin-in (the app also drops the token) |++**Screen reads**++| Endpoint | Web loader today |+|---|---|+| `GET /operations?workCenterIds=…` | `x+/operations.tsx` |+| `GET /operations/:id` | `x+/operation.$operationId.tsx` |+| `GET /operations/:id/rework-targets` | `x+/rework-targets.$operationId.tsx` |+| `GET /picking` | `x+/picking._index.tsx` |+| `GET /picking/:listId` | `x+/picking.$pickingListId.tsx` |+| `GET /timecard` | `x+/timecard.tsx` |++**Commands**++| Operator action | Endpoint | Web route today |+|---|---|---|+| Start setup, labor or machine time | `POST /operations/:id/events` | `x+/start.$operationId.tsx` |+| Pause or stop an event | `POST /events/:id/end` | `x+/event.tsx` |+| End the operation | `POST /operations/:id/end` | `x+/end.$operationId.tsx` |+| Report good parts | `POST /operations/:id/quantities` | `x+/complete.tsx` |+| Report scrap | `POST /operations/:id/scrap` | `x+/scrap.tsx` |+| Report rework | `POST /operations/:id/rework` | `x+/rework.tsx` |+| Finish the operation | `POST /operations/:id/finish` | `x+/finish.tsx` |+| Issue material | `POST /operations/:id/materials/issue` | `x+/issue.tsx` |+| Issue a tracked entity | `POST /operations/:id/materials/issue-tracked` | `x+/issue-tracked-entity.tsx` |+| Undo an issue | `POST /operations/:id/materials/unconsume` | `x+/unconsume.tsx` |+| Record a step | `POST /operations/:id/step-records` | `x+/record.tsx` |+| Delete a step record | `POST /step-records/:id/delete` | `x+/record.$id.delete.tsx` |+| Add a note | `POST /operations/:id/notes` | Web inserts from the browser today; the API makes shared-tablet attribution correct |+| Raise a quality issue | `POST /quality-issues` | `x+/quality-issue.new.tsx` (`create: "quality"`) |+| Print a label | `POST /print` | `x+/print.tsx` |+| Pick a quantity | `POST /picking/:listId/lines/:lineId/quantity` | `x+/picking.$pickingListId.line.quantity.tsx` |+| Pick a tracked entity | `POST /picking/:listId/lines/:lineId/tracked` | `x+/picking.$pickingListId.tracked.$lineId.tsx` |+| Change picking-list status | `POST /picking/:listId/status` | `x+/picking.$pickingListId.status.tsx` |+| Clock in / clock out | `POST /timecard/clock-in`, `POST /timecard/clock-out` | `x+/timecard.tsx` |+| End shift | `POST /timecard/end-shift` | `x+/end-shift.tsx` |++| Status | Meaning | App behaviour |+|---|---|---|+| 400 | Validation failed (`fields`) | Show field errors |+| 401 `token_expired` | Session expired | Refresh once, retry |+| 401 `mfa_required` | 2FA needed | Open the 2FA screen |+| 401 `operator_expired` | Operator token expired | Ask the operator to pin in again |+| 403 | Not an employee, or missing permission | "Ask your supervisor for access"; controls disabled |+| 403 `sso_required` | SSO-required domain | Explain SSO sign-in is coming in an update |+| 409 `request_in_progress` | Duplicate while the first is running | Retry with the same key |+| 409 (other) | State changed, e.g. operation already Done | Refetch and say what changed |+| 422 `idempotency_key_reused` | Client bug | Needs attention |+| 426 `update_required` | App older than `minAppVersion` | Update screen |+| 503 `retry_later` | Redis unavailable; nothing ran | Retry with the same key |++### Tooling++- **React pin.** Replace the workspace-wide `react`, `react-dom`,+ `@types/react` and `@types/react-dom` overrides in `pnpm-workspace.yaml` with+ scoped ones. Only two installed packages hard-depend on React+ (`@react-email/preview-server` → react-dom 19.0.0, `linguito` → React+ ^18.3.1); the first gets a scoped override to keep today's behaviour. Add a+ named catalog (`catalogs.mobile`) for React 19.2, React Native and Expo.+ Prove web is unchanged: `pnpm why react` for `erp` and `mes` shows only+ 18.3.1.+- **Lingui.** Add `apps/mes-mobile` sources to the `mes` catalog's extract+ globs (an Ask First change, approved in Q10). Load catalogs through Lingui's+ Metro transformer; add Intl polyfills only where Hermes lacks them.+- **Checks.** Add `apps/mes-mobile` and `packages/mes-core` to the source roots+ in `packages/checks/src/sources/typescript.ts`, so `no-raw-rounding`,+ `no-inline-fraction-digits` and `no-db-client-in-service` scan them. The new+ API routes and `.server` modules are already covered.+- **Biome.** `apps/biome.jsonc` only includes `./**/app/**/*.ts*`; add+ `apps/mes-mobile/src/**`.+- **Turbo.** The app defines `typecheck`, `lint` and `test`, and no `build`+ script (EAS builds it), so `pnpm run build` is unaffected.+- **Dates and numbers.** No JavaScript `Date` for parsing, formatting or+ arithmetic (`@internationalized/date`); quantities use the quantity kind+ (up to 5 decimals) through `@carbon/utils`.++## UI Changes++Design language: `.claude/skills/carbon-design` (`shop-floor-mes.md`). Carbon's+tokens, status colours and copy rules, with MES ergonomics: large touch targets+(44–48 pt, hero Start/Pause larger), no hover-reveal, no context menus, one+colour-coded primary action, a bottom action dock on phones and a right-hand+dock on tablets, bottom sheets for secondary actions, toasts that never move the+operator off the operation screen.++### Screens (Expo Router)++```+app/+ _layout.tsx providers: Query, Auth, Theme, i18n+ (setup)/server.tsx Carbon server address, QR scan+ (auth)/sign-in.tsx email → "Send code"+ (auth)/verify.tsx 6-digit code+ (auth)/two-factor.tsx TOTP code+ (app)/_layout.tsx guard: session + company + location+ (app)/context.tsx company, location, work centers+ (app)/(tabs)/_layout.tsx Operations · Picking · Scan · Timecard · More+ (app)/(tabs)/operations/index.tsx+ (app)/(tabs)/operations/[id].tsx+ (app)/(tabs)/picking/index.tsx+ (app)/(tabs)/picking/[listId].tsx+ (app)/(tabs)/timecard.tsx+ (app)/(tabs)/more.tsx shared terminal, language, theme, outbox, sign out+ (app)/scan.tsx camera scanner (modal)+ (app)/pin.tsx operator picker + PIN pad (shared terminal)+```++- **Phone (portrait):** bottom tabs; the operation detail is a pushed screen+ with its action dock at the bottom (safe-area padding).+- **Tablet (landscape, usually mounted):** the operations list stays on the+ left (about 360 pt), the detail fills the rest, the dock sits on the right.+- **Operation detail tabs:** Details, Instructions, Materials, Notes. The same+ sections and order as `JobOperation.tsx`.+- **Cards** (operations, picking) show what operators scan for: item ID and+ description, big quantity ("12 of 40"), job ID, status icon plus text, due.+- **Shared terminal:** the header shows the pinned operator with "Switch+ operator"; idle expiry returns to the PIN screen.++### Design brief++- **Users and context:** operators standing at machines and picking carts,+ often gloved, on shared tablets; supervisors setting up terminals.+- **Archetype:** MES operator screen; exemplars+ `apps/mes/app/components/JobOperation/JobOperation.tsx`,+ `components/Controls.tsx`, `OperationsList.tsx`, `ShortPickModal.tsx`,+ `EndShift.tsx`.+- **Actions:** one dominant action per state (Start emerald, Pause red);+ report, scrap, issue and print in the dock; everything else in the More+ actions sheet. Confirmation modals: Cancel left, action right, both large,+ listing what will be affected.+- **States:** loading skeletons; empty only when truly empty ("No operations+ at Assembly 2"); offline banner with the outbox count; needs-attention rows;+ locked and no-permission controls disabled in place, never hidden;+ update-required screen.+- **Copy:** operator words over data-model words ("Instructions", not+ "Procedure"); plain questions ("How many were actually picked?"); every+ string through Lingui, including accessibility labels.+- **Reuse / extend / create:** reuse Carbon's status maps and icon vocabulary+ (shared from `@carbon/utils`), React Native Reusables for primitives (button,+ input, dialog, tabs, select, sheet via community library), `sonner-native`+ for toasts. Create a native action dock and hero buttons following+ `Controls.tsx`, since no React Native equivalent exists.++## Acceptance Criteria++Each is checked on an iPad and an Android tablet (including one Zebra Android+11+ device) and on one phone per platform.++- [ ] A user enters a Carbon Cloud server, requests a code, enters it, and lands+ on their default location's operations list; the same user on web MES+ sees the same operations for the same work centers.+- [ ] An email in `APP_REVIEW_EMAILS` gets a password field and signs in with+ it; any other email gets `{ method: "code" }`, and `POST /auth/password`+ refuses it. With the variable unset, no email gets the password path.+- [ ] A user with a verified TOTP factor must enter a 2FA code before any API+ call succeeds; an `aal1` token gets `401 mfa_required`.+- [ ] Requesting a code for an SSO-required domain shows the SSO message and+ sends no email; going past the account lockout's 5 attempts+ (`DEFAULT_MAX_ATTEMPTS`) locks the account exactly as web login does.+- [ ] Start labor, pause, report 10 good and 2 scrap, then finish: the+ `productionEvent`, `productionQuantity` and item ledger rows are identical+ to doing the same on web MES, including backflushed materials and the cost+ posting.+- [ ] The floor gate that blocks a start on web blocks the same start in the+ app with the same message.+- [ ] Issue a tracked entity by scanning its barcode with a keyboard-wedge+ scanner and with the camera; both post the same `issue` call as web.+- [ ] Record a step with a photo: the file lands under+ `{companyId}/job/{operationId}/{stepId}/…` and opens on web MES.+- [ ] Print a label from the app: a `print-job` event fires with the same+ payload as web's Print button.+- [ ] Pick a quantity on a picking list with `incompletePickingListPolicy =+ error`: completing an incomplete list is refused with web's message.+- [ ] Clock in, clock out and end shift produce the same timecard rows as web.+- [ ] On a shared terminal (company entitled to console mode), two operators pin+ in one after the other; each one's events show that operator as+ `createdBy`. Five wrong PINs lock that operator, as `x+/console.pin-in.tsx`+ does (`maxAttempts: 5`). After 1+ hour idle the next command returns `operator_expired` and the app shows+ the PIN screen.+- [ ] A user without `settings_update` can't turn a device into a shared+ terminal; the control is disabled with an explanation.+- [ ] With Wi-Fi off, report 5 good parts twice, then reconnect: exactly two+ `productionQuantity` rows are created, in order. Killing the app while+ rows are queued and reopening it resends them.+- [ ] Replaying the same request with the same `Idempotency-Key` creates one+ row and returns the first response.+- [ ] A queued row older than 8 hours is not sent until the operator confirms it.+- [ ] Switching company pauses the other company's outbox rows and never shows+ the other company's cached data.+- [ ] All existing web MES routes keep their paths and behaviour+ (`pnpm test` and the MES route tests pass; a manual pass of start,+ complete, scrap, issue, finish, picking and print on web).+- [ ] `pnpm why react` for `erp` and `mes` shows only 18.3.1 after the pin+ change.+- [ ] `pnpm exec turbo run typecheck --filter=mes --filter=mes-mobile+ --filter=@carbon/mes-core`, `pnpm exec biome check`, `pnpm test` and+ `pnpm run lingui:check` pass.++## Delivery Phases++| Phase | Weeks | Output | Done when |+|---|---|---|---|+| 0 · Scaffold | 1 | React pin scoped, `apps/mes-mobile` and `packages/mes-core` created, tooling wired | CI green with an empty app; web unchanged |+| 1 · Spike | 1 | Server address, code sign-in, 2FA, operations list through `GET /operations` | The list matches web MES on an iPad and an Android tablet |+| 2 · MES API | 2–3 | `requireApiUser`, tokens, idempotency, `commands.server.ts`, `screens.server.ts`, every endpoint | Web routes call the extracted code; API tests pass |+| 3 · Screens | 4–6 | Every v1 screen, outbox, scanning, photos, print, shared terminal | A pilot operator runs a full job on a tablet |+| 4 · Pilot and ship | 1–2 | TestFlight and Play internal testing, one pilot customer, store listings | One full pilot shift without falling back to web |++## Risks++| Risk | Severity | Mitigation |+|---|---|---|+| The extraction changes web MES behaviour | High | Move bodies without edits first, one route per commit; manual pass of every moved route on web before the API uses it |+| Scoping the React pin pulls React 19 into a web app | Med | Scoped override for `@react-email/preview-server`; `pnpm why react` check in the phase 0 PR |+| An automatic retry duplicates a command | High | Stored responses (including 5xx) replayed; retries only on "never ran" outcomes; Retry after a 5xx needs the operator |+| Shared-terminal tokens become a weaker path than the web cookie | High | Same secret, binding, idle window and per-request re-validation as `console-pin.server`; security review before merge |+| Operators lacking `production_view` get no live timer updates | Low | Same limit as web today; the operation screen also refetches on focus, after commands and every 30 s |+| React Native Reusables stalls (one maintainer) | Med | Components are copied in and owned; Gluestack UI v5 fallback |+| Uniwind breaking changes | Low | Pin versions; upgrade on purpose |+| Store review rejects the app | Med | Review-only password sign-in (Q11); reviewer notes explain the server address and the demo company |+| The review password path is abused | Med | Allow-list only, empty on every install but Carbon Cloud; same rate limit and lockout as code sign-in; the account belongs to a demo company only |++## Out of Scope / Later++- SSO sign-in (v1.1), passkeys+- Inspections, batches, maintenance dispatch, 3D assembly view, drawings+- Zebra DataWedge intents, Bluetooth printers, Android kiosk lock+- Push notifications+- Full offline mode or a sync engine+- Tightening MES permissions beyond today's parity++## Open Questions++> HARD STOP: Do not proceed with implementation until these are answered.++Q1–Q10 were answered by Sid on 2026-09-30 by accepting the recommended answer+for each.++- [x] **Q1. Which operator workflows ship in v1?** — **Answer:** core execution:+ time, good/scrap/rework, material by scan, step records with photos,+ notes, quality issues, labels, picking, clock in/out. Inspections,+ batches, maintenance, 3D and drawings stay on web.+- [x] **Q2. Personal devices or shared tablets?** — **Answer:** tablet-first+ with phone support; both personal sign-in and shared-tablet PIN mode in+ v1.+- [x] **Q3. How do users sign in?** — **Answer:** emailed 6-digit code+ requested through the MES server (rate limit, lockout, SSO-required+ gate), then 2FA where the user has a factor. SSO in v1.1.+- [x] **Q4. What permissions do app actions require?** — **Answer:** the same+ as web MES today (signed-in employee of the company); tighten later.+- [x] **Q5. What does the app call for writes?** — **Answer:** a new MES API in+ `apps/mes` at `/api/v1` with Bearer tokens, internal but versioned; the+ two most recent app releases stay supported.+- [x] **Q6. Offline behaviour?** — **Answer:** online-first with an ordered+ outbox for short drops, an 8-hour stale limit and duplicate protection in+ Redis.+- [x] **Q7. Stack and repository?** — **Answer:** `apps/mes-mobile` in this+ monorepo; Expo SDK 57, Expo Router, Uniwind, React Native Reusables,+ TanStack Query, supabase-js, PostHog; web stays on React 18.+- [x] **Q8. Licensing?** — **Answer:** Community edition, like web MES.+- [x] **Q9. Distribution?** — **Answer:** public App Store and Google Play+ listings; server address at first launch (default Carbon Cloud), with a+ QR code to configure.+- [x] **Q10. Translations?** — **Answer:** reuse the existing `mes` catalog.++Surfaced while writing the spec:++- [x] **Q11. How does App Store and Google Play review sign in?** Both stores+ require working reviewer access, and a reviewer can't receive an emailed+ code. — **Answer (Sid, 2026-09-30):** a review-only password. Emails in+ the `APP_REVIEW_EMAILS` allow-list (Carbon Cloud only) get a password+ field instead of a code; everyone else is unchanged.++## Changelog++- 2026-09-30: Created. Q1–Q10 resolved (recommended answers accepted); Q11,+ surfaced while writing, resolved as a review-only password. Built on+ `main` at `ea9f4be1e5`, after PR #1734 and `20260926141957_employee-pin.sql`+ closed the four security gaps found while researching (permission checks in+ `post-picking` and five `issue` cases, the unsigned console cookie, readable+ plain-text PINs).