Skip to content

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.

feat: assembly instructions (#1075)

Brad Barbin718c9c493afa
diff --git a/.agents/skills/rust-best-practices/SKILL.md b/.agents/skills/rust-best-practices/SKILL.md
new file mode 100644
index 0000000000..f527c7f4c4
--- /dev/null
+++ b/.agents/skills/rust-best-practices/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: rust-best-practices
+description: >
+ Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when:
+ (1) writing new Rust code or functions,
+ (2) reviewing or refactoring existing Rust code,
+ (3) deciding between borrowing vs cloning or ownership patterns,
+ (4) implementing error handling with Result types,
+ (5) optimizing Rust code for performance,
+ (6) writing tests or documentation for Rust projects.
+license: MIT
+compatibility: Rust 1.70+, Cargo
+metadata:
+ author: apollographql
+ version: "1.1.0"
+allowed-tools: Bash(cargo:*) Bash(rustc:*) Bash(rustfmt:*) Bash(clippy:*) Read Write Edit Glob Grep
+---
+
+# Rust Best Practices
+
+Apply these guidelines when writing or reviewing Rust code. Based on Apollo GraphQL's [Rust Best Practices Handbook](https://github.com/apollographql/rust-best-practices).
+
+## Best Practices Reference
+
+Before reviewing, familiarize yourself with Apollo's Rust best practices. Read ALL relevant chapters in the same turn in parallel. Reference these files when providing feedback:
+
+- [Chapter 1 - Coding Styles and Idioms](references/chapter_01.md): Borrowing vs cloning, Copy trait, Option/Result handling, iterators, comments
+- [Chapter 2 - Clippy and Linting](references/chapter_02.md): Clippy configuration, important lints, workspace lint setup
+- [Chapter 3 - Performance Mindset](references/chapter_03.md): Profiling, avoiding redundant clones, stack vs heap, zero-cost abstractions
+- [Chapter 4 - Error Handling](references/chapter_04.md): Result vs panic, thiserror vs anyhow, error hierarchies
+- [Chapter 5 - Automated Testing](references/chapter_05.md): Test naming, one assertion per test, snapshot testing
+- [Chapter 6 - Generics and Dispatch](references/chapter_06.md): Static vs dynamic dispatch, trait objects
+- [Chapter 7 - Type State Pattern](references/chapter_07.md): Compile-time state safety, when to use it
+- [Chapter 8 - Comments vs Documentation](references/chapter_08.md): When to comment, doc comments, rustdoc
+- [Chapter 9 - Understanding Pointers](references/chapter_09.md): Thread safety, Send/Sync, pointer types
+
+## Quick Reference
+
+### Borrowing & Ownership
+- Prefer `&T` over `.clone()` unless ownership transfer is required
+- Use `&str` over `String`, `&[T]` over `Vec<T>` in function parameters
+- Small `Copy` types (≤24 bytes) can be passed by value
+- Use `Cow<'_, T>` when ownership is ambiguous
+
+### Error Handling
+- Return `Result<T, E>` for fallible operations; avoid `panic!` in production
+- Never use `unwrap()`/`expect()` outside tests
+- Use `thiserror` for library errors, `anyhow` for binaries only
+- Prefer `?` operator over match chains for error propagation
+
+### Performance
+- Always benchmark with `--release` flag
+- Run `cargo clippy -- -D clippy::perf` for performance hints
+- Avoid cloning in loops; use `.iter()` instead of `.into_iter()` for Copy types
+- Prefer iterators over manual loops; avoid intermediate `.collect()` calls
+
+### Linting
+Run regularly: `cargo clippy --all-targets --all-features --locked -- -D warnings`
+
+Key lints to watch:
+- `redundant_clone` - unnecessary cloning
+- `large_enum_variant` - oversized variants (consider boxing)
+- `needless_collect` - premature collection
+
+Use `#[expect(clippy::lint)]` over `#[allow(...)]` with justification comment.
+
+### Testing
+- Name tests descriptively: `process_should_return_error_when_input_empty()`
+- One assertion per test when possible
+- Use doc tests (`///`) for public API examples
+- Consider `cargo insta` for snapshot testing generated output
+
+### Generics & Dispatch
+- Prefer generics (static dispatch) for performance-critical code
+- Use `dyn Trait` only when heterogeneous collections are needed
+- Box at API boundaries, not internally
+
+### Type State Pattern
+Encode valid states in the type system to catch invalid operations at compile time:
+```rust
+struct Connection<State> { /* ... */ _state: PhantomData<State> }
+struct Disconnected;
+struct Connected;
+
+impl Connection<Connected> {
+ fn send(&self, data: &[u8]) { /* only connected can send */ }
+}
+```
+
+### Documentation
+- `//` comments explain *why* (safety, workarounds, design rationale)
+- `///` doc comments explain *what* and *how* for public APIs
+- Every `TODO` needs a linked issue: `// TODO(#42): ...`
+- Enable `#![deny(missing_docs)]` for libraries
diff --git a/.agents/skills/rust-best-practices/references/chapter_01.md b/.agents/skills/rust-best-practices/references/chapter_01.md
new file mode 100644
index 0000000000..d41bfd09b9
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_01.md
@@ -0,0 +1,552 @@
+# Chapter 1 - Coding Styles and Idioms
+
+## 1.1 Borrowing Over Cloning
+
+Rust's ownership system encourages **borrow** (`&T`) instead of **cloning** (`T.clone()`).
+> ❗ Performance recommendation
+
+### ✅ When to `Clone`:
+
+* You need to change the object AND preserve the original object (immutable snapshots).
+* When you have `Arc` or `Rc` pointers.
+* When data is shared across threads, usually `Arc`.
+* Avoid massive refactoring of non performance critical code.
+* When caching results (dummy example below):
+```rust
+fn get_config(&self) -> Config {
+ self.cached_config.clone()
+}
+```
+* When the underlying API expects Owned Data.
+
+### 🚨 `Clone` traps to avoid:
+
+* Auto-cloning inside loops `.map(|x| x.clone)`, prefer to call `.cloned()` or `.copied()` at the end of the iterator.
+* Cloning large data structures like `Vec<T>` or `HashMap<K, V>`.
+* Clone because of bad API design instead of adjusting lifetimes.
+* Prefer `&[T]` instead of `Vec<T>` or `&Vec<T>`.
+* Prefer `&str` or `&String` instead of `String`.
+* Prefer `&T` instead of `T`.
+* Clone a reference argument, if you need ownership, make it explicit in the arguments for the caller. Example:
+```rust
+fn take_a_borrow(thing: &Thing) {
+ let thing_cloned = thing.clone(); // the caller should have passed ownership instead
+}
+```
+
+### ✅ Prefer borrowing:
+```rust
+fn process(name: &str) {
+ println!("Hello {name}");
+}
+
+let user = String::from("foo");
+process(&user);
+```
+
+### ❌ Avoid redundant cloning:
+```rust
+fn process_string(name: String) {
+ println!("Hello {name}");
+}
+
+let user = String::from("foo");
+process(user.clone()); // Unnecessary clone
+```
+
+## 1.2 When to pass by value? (Copy trait)
+
+Not all types should be passed by reference (`&T`). If a type is **small** and it is **cheap to copy**, it is often better to **pass it by value**. Rust makes it explicit via the `Copy` trait.
+
+### ✅ When to pass by value, `Copy`:
+* The type **implements** `Copy` (`u32`, `bool`, `f32`, small structs).
+* The cost of moving the value is negligible.
+
+```rust
+fn increment(x: u32) -> u32 {
+ x + 1
+}
+
+let num = 1;
+let new_num = increment(num); // `num` still usable after this point
+```
+
+### ❓ Which structs should be `Copy`?
+* When to consider declaring `Copy` on your own types:
+* All fields are `Copy` themselves.
+* The struct is `small`, up to 2 (maybe 3) words of memory or 24 bytes (each word is 64 bits/8bytes).
+* The struct **represents a "plain data object"**, without resourcing to ownership (no heap allocations. Example: `Vec` and `Strings`).
+
+❗**Rust Arrays are stack allocated.** Which means they can be copied if their underlying type is `Copy`, but this will be allocated in the program stack which can easily become a stack overflow. More on [Chapter 3 - Stack vs Heap](./chapter_03.md#33-stack-vs-heap-be-size-smart)
+
+For reference, each primitive type size in bytes:
+
+#### Integers:
+
+| Type | Size |
+|------------- |---------- |
+| i8 u8 | 1 byte |
+| i16 u16 | 2 bytes |
+| i32 u32 | 4 bytes |
+| i64 u64 | 8 bytes |
+| isize usize | Arch |
+| i128 u128 | 16 bytes |
+
+#### Floating Point:
+
+| Type | Size |
+|---------- |---------- |
+| f32 | 4 bytes |
+| f64 | 8 bytes |
+
+
+#### Other:
+
+| Type | Size |
+|---------- |---------- |
+| bool | 1 byte |
+| char | 4 bytes |
+
+
+### ✅ Good struct to derive `Copy`:
+```rust
+#[derive(Debug, Copy, Clone)]
+struct Point {
+ x: f32,
+ y: f32,
+ z: f32
+}
+```
+
+### ❌ Bad struct to derive `Copy`:
+```rust
+#[derive(Debug, Clone)]
+struct BadIdea {
+ age: i32,
+ name: String, // String is not `Copy`
+}
+```
+
+### ❓Which Enums should be `Copy`?
+* If your enum acts like tags and atoms.
+* The enum payloads are all `Copy`.
+* **❗Enums size are based on their largest element.**
+
+### ✅ Good Enum to derive
+```rust
+#[derive(Debug, Copy, Clone)]
+enum Direction {
+ North,
+ South,
+ East,
+ West,
+}
+```
+
+## 1.3 Handling `Option<T>` and `Result<T, E>`
+Rust 1.65 introduced a better way to safely unpack Option and Result types with the `let Some(x) = … else { … }` or `let Ok(x) = … else { … }` when you have a default `return` value, `continue` or `break` default else case. It allows early returns when the missing case is **expected and normal**, not exceptional.
+
+### ✅ Cases to use each pattern matching for Option and Return
+* Use `match` when you want to pattern match against the inner types `T` and `E`
+```rust
+match self {
+ Ok(Direction::South) => { … },
+ Ok(Direction::North) => { … },
+ Ok(Direction::East) => { … },
+ Ok(Direction::West) => { … },
+ Err(E::One) => { … },
+ Err(E::Two) => { … },
+}
+
+match self {
+ Some(3|5) => { … }
+ Some(x) if x > 10 => { … }
+ Some(x) => { … }
+ None => { … }
+}
+```
+
+* Use `match` when your type is transformed into something more complex Like `Result<T, E>` becoming `Result<Option<T>, E>`.
+```rust
+match self {
+ Ok(t) => Ok(Some(t)),
+ Err(E::Empty) => Ok(None),
+ Err(err) => Err(err),
+}
+```
+
+* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when the divergent code doesn't need to know about the failed pattern matches or doesn't need extra computation:
+```rust
+let Some(&Direction::North) = self.direction.as_ref() else {
+ return Err(DirectionNotAvailable(self.direction));
+}
+```
+
+* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when you want to break or continue a pattern match
+```rust
+for x in self {
+ let Some(x) = x else {
+ continue;
+ }
+}
+```
+
+* Use `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when `DIVERGING_CODE` needs extra computation:
+```rust
+if let Some(x) = self.next() {
+ // computation
+} else {
+ // computation when `None/Err` or not matched
+}
+```
+
+❗**If you don't care about the value of the `Err` case, please use `?` to propagate the `Err` to the caller.**
+
+### ❌ Bad Option/Return pattern matching:
+
+* Conversion between Result and Option (prefer `.ok()`,`.ok_or()`, and `ok_or_else()`)
+```rust
+match self {
+ Ok(t) => Some(t),
+ Err(_) => None
+}
+```
+
+* `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when divergent code is a default or pre-computed value (prefer `let PATTERN = EXPRESSION else { DIVERGING_CODE; }`):
+```rust
+if let Some(values) = self.next() {
+ // computation
+ (Some(..), values)
+} else {
+ (None, Vec::new())
+}
+```
+
+* Using `unwrap` or `expect` outside tests:
+```rust
+let port = config.port.unwrap();
+```
+
+## 1.4 Prevent Early Allocation
+
+When dealing with functions like `or`, `map_or`, `unwrap_or`, `ok_or`, consider that they have special cases for when memory allocation is required, like creating a new string, creating a collection or even calling functions that manage some state, so they can be replaced with their `_else` counter-part:
+
+### ✅ Good cases
+
+```rust
+let x = None;
+assert_eq!(x.ok_or(ParseError::ValueAbsent), Err(ParseError::ValueAbsent));
+
+let x = None;
+assert_eq!(x.ok_or_else(|| ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));
+
+
+let x: Result<_, &str> = Ok("foo");
+assert_eq!(x.map_or(42, |v| v.len()), 3);
+
+
+let x : Result<_, String> = Ok("foo");
+assert_eq!(x.map_or_else(|e|format!("Error: {e}"), |v| v.len()), 3);
+
+let x = "1,2,3,4";
+assert_eq!(x.parse_to_option_vec.unwrap_or_else(Vec::new), Ok(vec![1, 2, 3, 4]));
+```
+
+### ❌ Bad cases
+
+```rust
+let x : Result<_, String> = Ok("foo");
+assert_eq!(x.map_or(format!("Error with uninformed content"), |v| v.len()), 3);
+
+let x = "1,2,3,4";
+assert_eq!(x.parse_to_option_vec.unwrap_or(Vec::new()), Ok(vec![1, 2, 3, 4])); // could be replaced with `.unwrap_or_default`
+
+let x = None;
+assert_eq!(x.ok_or(ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));
+```
+
+### Mapping Err
+
+When dealing with Result::Err, sometimes is necessary to log and transform the Err into a more abstract or more detailed error, this can be done with `inspect_err` and `map_err`:
+
+```rust
+let x = Err(ParseError::InvalidContent(...));
+
+x
+ .inspect_err(|err| tracing::error!("function_name: {err}"))
+ .map_err(|err| GeneralError::from(("function_name", err)))?;
+```
+
+## 1.5 Iterator, `.iter` vs `for`
+
+First we need to understand a basic loop with each one of them. Let's consider the following problem, we need to sum all even numbers between 0 and 10 incremented by 1:
+
+* `for`:
+```rust
+let mut sum = 0;
+for x in 0..=10 {
+ if x % 2 == 0 {
+ sum += x + 1;
+ }
+}
+```
+
+* `iter`:
+```rust
+let sum: i32 = (0..=10)
+ .filter(|x| x % 2 == 0)
+ .map(|x| x + 1)
+ .sum();
+```
+
+> Both versions do the same thing and are correct and idiomatic, but each shines in different contexts.
+
+### When to prefer `for` loops
+* When you need **early exits** (`break`, `continue`, `return`).
+* **Simple iteration** with side-effects (e.g., logging, IO)
+ * logging can be done correctly in `Iterators` using `inspect` and `inspect_err` functions.
+* When readability matters more than simplicity or chaining.
+
+#### Example:
+```rust
+for value in &mut value {
+ if *value == 0 {
+ break;
+ }
+ *value += fancy_equation();
+}
+```
+
+### When to prefer `iterators` loops (`.iter()` and `.into_iter()`)
+* When you are `transforming collections` or `Option/Results`.
+* You can **compose multiple steps** elegantly.
+* No need for early exits.
+* You need support for indexed values with `.enumerate`.
+```rust
+let values: Vec<_> = vec.into_iter()
+ .enumerate()
+ .filter(|(_index, value)| value % 2 == 0)
+ .map(|(index, value)| value % index)
+ .collect()
+```
+* You need to use collections functions like `.windows` or `chunks`.
+* You need to combine data from multiple sources and don't want to allocate multiple collections.
+* Iterators can be combined with `for` loops:
+```rust
+for value in vec.iter().enumerate()
+ .filter(|(index, value)| value % index == 0) {
+ // ...
+}
+```
+
+> #### ❗REMEMBER: Iterators are Lazy
+>
+> * `.iter`, `.map`, `.filter` don't do anything until you call its consumer, e.g. `.collect`, `.sum`, `.for_each`.
+> * **Lazy Evaluation** means that iterator chains are fused into one loop at compile time.
+
+### 🚨 Anti-patterns to AVOID
+
+* Don't chain without formatting. Prefer each chained function on its own line with the correct indentation (`rustfmt` should take care of this).
+* Don't chain if it makes the code unreadable.
+* Avoid needlessly collect/allocate of a collection (e.g. vector) just to throw it away later by some larger operation or by another iteration.
+* Prefer `iter` over `into_iter` unless you don't need the ownership of the collection.
+* Prefer `iter` over `into_iter` for collections that inner type implements `Copy`, e.g. `Vec<i32>`.
+* For summing numbers prefer `.sum` over `.fold`. `.sum` is specialized for summing values, so the compiler knows it can make optimizations on that front, while fold has a blackbox closure that needs to be applied at every step. If you need to sum by an initial value, just added in the expression `let my_sum = [1, 2, 3].sum() + 3`.
+
+## 1.6 Comments: Context, not Clutter
+
+> "Context are for why, not what or how"
+
+Well-written Rust code, with expressive types and good naming, often speaks for itself. Many high-quality codebases thrive on **few or no comments**. And that's a good thing.
+
+Still, there are **moments where code alone isn't enough** - when there are performance quirks, external constraints, or non-obvious tradeoffs that require a nudge to the reader. In those cases, a concise comment can prevent hours of head-scratching or searching git history.
+
+### ✅ Good comments
+
+* Safety concerns:
+```rust
+// SAFETY: We have checked that the pointer is valid and non-null. @Function xyz.
+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }
+```
+
+* Performance quirks:
+```rust
+// This algorithm is a fast square root approximation
+const THREE_HALVES: f32 = 1.5;
+fn q_rsqrt(number: f32 ) -> f32 {
+ let mut i: i32 = number.to_bits() as i32;
+ i = 0x5F375A86_i32.wrapping_sub(i >> 1);
+ let y = f32::from_bits(i as u32);
+ y * (THREE_HALVES - (number * 0.5 * y * y))
+}
+```
+
+* Clear code beats comments. However, when the why isn't obvious, say it plainly - or link to where:
+```rust
+// PERF: Generating the root store per subgraph caused high TLS startup latency on MacOS
+// This works as a caching alternative. See: [ADR-123](link/to/adr-123)
+let subgraph_tls_root_store: RootCertStore = configuration
+ .tls
+ .subgraph
+ .all
+ .create_certificate_store()
+ .transpose()?
+ .unwrap_or_else(crate::services::http::HttpClientService::native_roots_store);
+```
+
+### ❌ Bad comments
+
+* Wall-of-text explanations: long comments and multiline comments
+```rust
+// Lorem Ipsum is simply dummy text of the printing and typesetting industry.
+// Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
+// when an unknown printer took a galley
+fn do_something_odd() {
+ …
+}
+```
+> Prefer `/// doc` comment if it's describing the function.
+
+* Comments that could be better represented as functions or are plain obvious
+```rust
+fn computation() {
+ // increment i by 1
+ i += 1;
+}
+```
+
+### ✅ Breaking up long functions over commenting them
+
+If you find yourself writing a long comment explaining "what", "how" or "each step" in a function, it might be time to split it. So the suggestion is to refactor. This can be beneficial not only for readability, but testability:
+
+#### ❌ Instead of:
+```rust
+fn process_request(request: T) {
+ // We first need to validate request, because of corner case x, y, z
+ // As the payload can only be decoded when they are valid
+ // Then we can perform authorization on the payload
+ // lastly with the authorized payload we can dispatch to handler
+}
+```
+
+#### ✅ Prefer
+```rust
+fn process_request(request: T) -> Result<(), Error> {
+ validate_request_headers(&request)?;
+ let payload = decode_payload(&request);
+ authorize(&payload)?;
+ dispatch_to_handler(payload)
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn validate_request_happy_path() { ... }
+
+ #[test]
+ fn validate_request_fails_on_x() { ... }
+
+ #[test]
+ fn validate_request_fails_on_y() { ... }
+
+ #[test]
+ fn decode_validated_request() { ... }
+
+ #[test]
+ fn authorize_payload_xyz() { ... }
+}
+```
+
+Let **structure** and **naming** replace commentary, and enhance its documentation with **tests as living documentation**.
+
+### 📝 TODOs are not comments - track them properly
+
+Avoid leaving lingering `// TODO: Lorem Ipsum` comments in the code. Instead:
+* Turn them into Jira or Github Issues.
+* If needed, to avoid future confusion, reference the issue in the code and the code in the issue.
+
+```rust
+// See issue #123: support hyper 2.0
+```
+
+This helps keeping the code clean and making sure tasks are not forgotten.
+
+### Comments as Living Documentation
+
+There are a few gotchas when calling comments "living documentation":
+* Code evolves.
+* Context changes.
+* Comments get stale.
+* Many large comments make people avoid reading them.
+* Team becomes fearful of delete irrelevant comments.
+
+If you find a comment, **don't trust it blindly**. Read it in context. If it's wrong or outdated, fix or remove it. A misleading comment is worse than no comments at all.
+
+> Comments should bother you - they demand re-verification, just like stale tests.
+
+When deeper justification is needed, prefer to:
+* **Link to a Design Doc or an ADR**, business logic lives well in design docs while performance tradeoffs live well in ADRs.
+* Move runtime example and usage docs into Rust Docs, `/// doc comment`, where they can be tested and kept up-to-date by tools like `cargo doc`.
+
+> Doc-comments and Doc-testing, `///` and `//!` in [Chapter 8 - Comments vs Documentation](./chapter_08.md)
+
+## 1.7 Use Declarations - "imports"
+
+Different languages have different ways of sorting their imports, in the Rust ecosystem the [standard way](https://github.com/rust-lang/rustfmt/issues/4107) is:
+
+- `std` (`core`, `alloc` would also fit here).
+- External crates (what is in your Cargo.toml `[dependencies]`).
+- Workspace crates (workspace member crates).
+- This module `super::`.
+- This module `crate::`.
+
+```rust
+// std
+use std::sync::Arc;
+
+// external crates
+use chrono::Utc;
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+
+// crate code lives in workspace
+use broker::database::PooledConnection;
+
+// super:: / crate::
+use super::schema::{Context, Payload};
+use super::update::convert_publish_payload;
+use crate::models::Event;
+```
+
+Some enterprise solutions opt to include their core packages after `std`, so all external packages that start with enterprise name are located before the others:
+
+```rust
+// std
+use std::sync::Arc;
+
+// enterprise external crates
+use enterprise_crate_name::some_module::SomeThing;
+
+// external crates
+use chrono::Utc;
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+
+// crate code lives in workspace
+use broker::database::PooledConnection;
+
+// super:: / crate::
+use super::schema::{Context, Payload};
+use super::update::convert_publish_payload;
+use crate::models::Event;
+```
+
+One way of not having to manually control this is using the following arguments in your `rustfmt.toml`:
+
+```toml
+reorder_imports = true
+imports_granularity = "Crate"
+group_imports = "StdExternalCrate"
+```
+
+> As of Rust version 1.88, it is necessary to execute rustfmt in nightly to correctly reorder code `cargo +nightly fmt`.
diff --git a/.agents/skills/rust-best-practices/references/chapter_02.md b/.agents/skills/rust-best-practices/references/chapter_02.md
new file mode 100644
index 0000000000..306b583525
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_02.md
@@ -0,0 +1,117 @@
+# Chapter 2 - Clippy and Linting Discipline
+
+Be sure to have `cargo clippy` installed with your rust compiler, run `cargo clippy -V` in your terminal for a rust project and you should get something like this `clippy 0.1.86 (05f9846f89 2025-03-31)`. If terminal fails to show a clippy version, please run the following code `rustup update && rustup component add clippy`.
+
+Clippy documentation can be found [here](https://doc.rust-lang.org/clippy/usage.html).
+
+## 2.1 Why care about linting?
+
+Rust compiler is a powerful tool that catches many mistakes. However, some more in-depth analysis require extra tools, that is where `cargo clippy` clippy comes into to play. Clippy checks for:
+* Performance pitfalls.
+* Style issues.
+* Redundant code.
+* Potential bugs.
+* Non-idiomatic Rust.
+
+## 2.2 Always run `cargo clippy`
+
+Add the following to your daily workflow:
+
+```shell
+$ cargo clippy --all-targets --all-features --locked -- -D warnings
+```
+
+* `--all-targets`: checks library, tests, benches and examples.
+* `--all-features`: checks code for all features enabled, auto solves conflicting features.
+* `--locked`: Requires `Cargo.lock` to be up-to-date, can be solved with `$ cargo update`.
+* `-D warnings`: treats warnings as errors
+
+Potential additions elements to add:
+
+* `-- -W clippy::pedantic`: lints which are rather strict or have occasional false positives.
+* `-- -W clippy::nursery`: Optionally can be added to check for new lints that are still under development.
+* ❗ Add this to your Makefile, Justfile, xtask or CI Pipeline.
+
+> Example at ApolloGraphQL
+>
+> In the `Router` project there is a `xtask` configured for linting that can be executed with `cargo xtask lint`.
+
+## 2.3 Important Clippy Lints to Respect
+
+| Lint Name | Why | Link |
+| --------- | ----| -----|
+| `redundant_clone` | Detects unnecessary `clones`, has performance impact | [link (nursery + perf)](https://rust-lang.github.io/rust-clippy/master/#redundant_clone) |
+| `needless_borrow` group | Removes redundant `&` borrowing | [link (style)](https://rust-lang.github.io/rust-clippy/master/#needless_borrow) |
+| `map_unwrap_or` / `map_or` | Simplifies nested `Option/Result` handling | [`map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/#map_unwrap_or) [`unnecessary_map_or`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_map_or) [`unnecessary_result_map_or_else`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_result_map_or_else) |
+| `manual_ok_or` | Suggest using `.ok_or_else` instead of `match` | [link (style)](https://rust-lang.github.io/rust-clippy/master/#manual_ok_or) |
+| `large_enum_variant` | Warns if an enum has very large variant which is bad for memory. Suggests `Boxing` it | [link (perf)](https://rust-lang.github.io/rust-clippy/master/#large_enum_variant) |
+| `unnecessary_wraps` | If your function always returns `Some` or `Ok`, you don't need `Option`/`Result` | [link (pedantic)](https://rust-lang.github.io/rust-clippy/master/#unnecessary_wraps) |
+| `clone_on_copy` | Catches accidental `.clone()` on `Copy` types like `u32` and `bool` | [link (complexity)](https://rust-lang.github.io/rust-clippy/master/#clone_on_copy) |
+| `needless_collect` | Prevents collecting and allocating an iterator, when allocation is not needed | [link (nursery)](https://rust-lang.github.io/rust-clippy/master/#needless_collect) |
+
+## 2.4 Fix warnings, don't silence them!
+
+**NEVER** just `#[allow(clippy::lint_something)]` unless:
+
+* You **truly understand** why the warning happens and you have a reason why it is better that way.
+* You **document** why it is being ignored.
+* ❗ Don't use `allow`, but `expect`, it will give a warning in case the lint is not true anymore, `#[expect(clippy::lint_something)]`.
+
+### Example:
+
+```rust
+// Faster matching is preferred over size efficiency
+#[expect(clippy::large_enum_variant)]
+enum Message {
+ Code(u8),
+ Content([u8; 1024]),
+}
+```
+
+> The fix would be:
+>
+> ```rust
+> // Faster matching is preferred over size efficiency
+> #[expect(clippy::large_enum_variant)]
+> enum Message {
+> Code(u8),
+> Content(Box<[u8; 1024]>),
+> }
+> ```
+
+### Handling false positives
+
+Sometimes Clippy complains even when your code is correct, in those cases there are two solutions:
+1. Try to refactor the code, so it improves the warning.
+2. **Locally** override the lint with `#[expect(clippy::lint_name)]` and a comment with the reason.
+3. Avoid global overrides, unless it is core crate issue, a good example of this is the Bevy Engine that has a set of lints that should be allowed by default.
+
+## 2.5 Configure workspace/package lints
+
+In your `Cargo.toml` file it is possible to determine which lints and their priorities over each other. In case of 2 or more conflicting lints, the higher priority one will be chosen. Example configuration for a package:
+
+```toml
+[lints.rust]
+future-incompatible = "warn"
+nonstandard_style = "deny"
+
+[lints.clippy]
+all = { level = "deny", priority = 10 }
+redundant_clone = { level = "deny", priority = 9 }
+manual_while_let_some = { level = "deny", priority = 4 }
+pedantic = { level = "warn", priority = 3 }
+```
+
+And for a workspace:
+
+```toml
+[workspace.lints.rust]
+future-incompatible = "warn"
+nonstandard_style = "deny"
+
+[workspace.lints.clippy]
+all = { level = "deny", priority = 10 }
+redundant_clone = { level = "deny", priority = 9 }
+manual_while_let_some = { level = "deny", priority = 4 }
+pedantic = { level = "warn", priority = 3 }
+```
diff --git a/.agents/skills/rust-best-practices/references/chapter_03.md b/.agents/skills/rust-best-practices/references/chapter_03.md
new file mode 100644
index 0000000000..074295e242
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_03.md
@@ -0,0 +1,209 @@
+# Chapter 3 - Performance Mindset
+
+The **golden rule** of performance work:
+
+> Don't guess, measure.
+
+Rust code is often already pretty fast - don't "optimize" without evidence. Optimize only after finding bottlenecks.
+
+### A good first steps
+* Use `--release` flag on you builds (might sound dummy, but it is quite common to hear people complaining that their Rust code is slower than their X language code, and 99% of the time is because they didn't use the `--release` flag).
+* `$ cargo clippy -- -D clippy::perf` gives you important tips on best practices for performance.
+* [`cargo bench`](https://doc.rust-lang.org/cargo/commands/cargo-bench.html) is a cargo tool to create micro-benchmarks and test different code solutions. Write a test scenario and bench you solution against the original code, if your improvement is larger than 5%, might be a good performance improvement.
+* [`cargo flamegraph`](https://github.com/flamegraph-rs/flamegraph) a powerful profiler for Rust code. For MacOS, [samply](https://github.com/mstange/samply) might be a better DX option.
+
+> #### Further reading on Benchmarking:
+> - [How to build a Custom Benchmarking Harness in Rust](https://bencher.dev/learn/benchmarking/rust/custom-harness/)
+
+
+## 3.1 Flamegraph
+
+Flamegraph helps you visualize how much time CPU spent on each task.
+
+```shell
+# Installing flamegraph
+cargo install flamegraph
+
+# cargo support provided through the cargo-flamegraph binary!
+# defaults to profiling cargo run --release
+cargo flamegraph
+
+# by default, `--release` profile is used,
+# but you can override this:
+cargo flamegraph --dev
+
+# if you'd like to profile a specific binary:
+cargo flamegraph --bin=stress2
+
+# Profile unit tests.
+# Note that a separating `--` is necessary if `--unit-test` is the last flag.
+cargo flamegraph --unit-test -- test::in::package::with::single::crate
+cargo flamegraph --unit-test crate_name -- test::in::package::with::multiple:crate
+
+# Profile integration tests.
+cargo flamegraph --test test_name
+
+# Run criterion benchmark
+# Note that the last --bench is required for `criterion 0.3` to run in benchmark mode, instead of test mode.
+cargo flamegraph --bench some_benchmark --features some_features -- --bench
+
+# Run workspace example
+cargo flamegraph --example some_example --features some_features
+```
+
+> ❗ Always run your profiles with `--release` enabled, the `--dev` flag isn't realistic as it doesn't have optimizations enabled.
+
+The result will look like a flame graph where:
+
+* The `y-axis` shows the **stack depth number**. When looking at a flamegraph, the main function of your program will be closer to the bottom, and the called functions will be stacked on top, with the functions that they call stacked on top of them.
+
+* The `width of each box` shows the **total time that that function** is on the CPU or is part of the call stack. If a function's box is wider than others, that means that it consumes more CPU per execution than other functions, or that it is called more than other functions.
+
+> ❗ The **color of each box** isn't significant, and **is chosen at random**.
+
+### 🚨 Remember
+* Thick stacks: heavy CPU usage
+* Thin stacks: low intensity (cheap)
+
+## 3.2 Avoid Redundant Cloning
+
+> Cloning is cheap... **until it isn't**
+
+In sections [Borrowing over Cloning](./chapter_01.md#11-borrowing-over-cloning) and [Important Clippy lints to respect](./chapter_02.md#23-important-clippy-lints-to-respect) we mentioned the impacts of cloning and the relevant clippy lint [`redundant_clone`](https://rust-lang.github.io/rust-clippy/master/#redundant_clone), so in this section we will explore a bit "when to pass ownership".
+
+* 🚨 If you really need to clone, leave it to the last moment.
+
+### When to pass ownership?
+
+* Only `.clone()` if you truly need a new owned copy. A few examples:
+ * Crate API Design requires owned data.
+ * Have overloaded `std::ops` but still need ownership to the old data:
+ ```rust
+ use std::ops::Add;
+
+ #[derive(Debug, Copy, Clone, PartialEq)]
+ struct Point {
+ x: i32,
+ y: i32,
+ }
+
+ impl Add for Point {
+ type Output = Self;
+
+ fn add(self, other: Self) -> Self {
+ Self {
+ x: self.x + other.x,
+ y: self.y + other.y,
+ }
+ }
+ }
+
+ assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
+ Point { x: 3, y: 3 });
+ ```
+ * Need to do comparison snapshots or due to API you need multiple owned instances of the data.
+ ```rust
+ fn snapshot(a: &MyValue, b:&MyValue) -> MyValueDiff {
+ a - b
+ }
+
+ impl Sub for MyValue {
+ type Output = MyValueDiff;
+
+ fn sub(self, other: Self) -> MyValue {
+ ...
+ }
+ }
+
+ fn main() {
+ let mut a = MyValue::default();
+ let b = a.clone();
+
+ a.magical_update();
+ println!("{:?}", snapshot(&a, &b));
+ }
+ ```
+* You have reference counted pointers (`Arc, Rc`).
+* You have small structs that are to big to `Copy` but as costly as `std::collections`. An example is HTTP client like `hyper_util::client::legacy::Client` that cloning allows you to share the connection pool.
+* You have a chained struct modifier that needs owned mutation, some **builders** require owned mutation, but most custom builders can be done with `pub fn with_xyz(&mut self, value: Xyz) -> &mut Self`.
+```rust
+// Inline `HashMap` insertion extension
+
+fn insert_owned(mut self, key: K, value: V) -> Self {
+ self.insert(key, value);
+ self
+}
+```
+* Ownership can also be a good way to model business logic / state. For example:
+```rust
+let not_validated: String = ...;// some user source
+let validated = Validate::try_from(not_validated)?;
+// Technically that `try_from` maybe didn't need ownership, but taking it lets us model intent
+```
+
+### When **NOT** to pass ownership?
+
+* Prefer API designs that take reference (`fn process(values: &[T])`), instead of ownership (`fn process(values: Vec<T>)`).
+* If you only need read access to elements, prefer `.iter` or slices:
+```rust
+for item in &some_vec {
+ ...
+}
+```
+* You need to mutate data that is owned by another thread, use `&mut MyStruct`.
+
+### Use `Cow` for `Maybe Owned` data
+
+Sometimes you don't actually need owned data, but that is not clear from the API perspective, so using [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html) is a way to efficiently address this case:
+
+```rust
+use std::borrow::Cow;
+
+fn hello_greet(name: Cow<'_, str>) {
+ println!("Hello {name}");
+}
+
+hello_greet(Cow::Borrowed("Julia"));
+hello_greet(Cow::Owned("Naomi".to_string()));
+```
+
+## 3.3 Stack vs Heap: Be size-smart!
+
+### ✅ Good Practices
+
+* Keep small types (`impl Copy`, `usize`, `bool`, etc) **on the stack**.
+* Avoid passing huge types (`> 512 bytes`) by value or transferring ownership. Prefer pass by reference (e.g. `&T` and `&mut T`).
+* Heap allocate recursive data structures:
+```rust
+enum OctreeNode<T> {
+ Node(T),
+ Children(Box<[Node<T>; 8]>),
+}
+```
+* Return small types by value, types that implement `Copy` or a cheaply Cloned are efficient to return by value (e.g. `struct Vector2 {x: f32, y: f32}`).
+
+### ❗ Be Mindful
+
+* Only use `#[inline]` when benchmark proves beneficial, Rust is already pretty good at inlining **without** hints.
+* Avoid massive stack allocations, box them. Example `let buffer: Box<[u8; 65536]> = Box::new(..)` would first allocate `[u8; 65536]` on the stack then box it, a non-const solution to this would be `let buffer: Box<[u8]> = vec![0; 65536].into_boxed_slice()`.
+* For large `const` arrays, considering using [crate smallvec](https://docs.rs/smallvec/latest/smallvec/) as it behaves like an array, but is smart enough to allocate large arrays on the heap.
+
+## 3.4 Iterators and Zero-Cost Abstractions
+
+Rust iterators are lazy, but eventually compiled away into very efficient tight loops that are only called when consumed. Chaining `.filter()`, `.map()`, `.rev()`, `.skip()`, `.take()`, `.collect()` usually doesn't cost extra and the compiler can reason well enough how to optimize them.
+* Prefer `iterators` over manual `for` loops when working with collections, the compiler can optimize them better than manually doing it.
+* Calling `.iter()` only creates a **reference** to the original collection, this allows you to hold multiple iterators of the same collection.
+
+#### ❗ Avoid creating intermediate collections unless it is really needed:
+
+* Consider that `process` accepts an `iterator`.
+* ❌ BAD - useless intermediate collection:
+```rust
+let doubled: Vec<_> = items.iter().map(|x| x * 2).collect();
+process(doubled);
+```
+* ✅ GOOD - pass the iterator (`fn process(arg: impl Iterator<Item = T>)`):
+```rust
+let doubled_iter = items.iter().map(|x| x * 2);
+process(doubled_iter);
+```
diff --git a/.agents/skills/rust-best-practices/references/chapter_04.md b/.agents/skills/rust-best-practices/references/chapter_04.md
new file mode 100644
index 0000000000..ebca71199c
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_04.md
@@ -0,0 +1,180 @@
+# Chapter 4 - Errors Handling
+
+Rust enforces a strict error handling approach, but *how* you handle them defines where your code feels ergonomic, consistent and safe - as opposing cryptic and painful. This chapter dives into best practices for modeling and managing fallible operations across libraries and binaries.
+
+> Even if you decide to crash you application with `unwrap` or `expect`, Rust forces you to declare that intentionally.
+
+## 4.1 Prefer `Result`, avoid panic 🫨
+
+Rust has a powerful type that wraps fallible data, [`Result<T, E>`](https://doc.rust-lang.org/std/result/), this allows us to handle Error cases according to our needs and manage the state of the application based on that.
+
+* If your function can fail, prefer to return a `Result`:
+```rust
+fn divide(x: f64, y: f64) -> Result<f64, DivisionError> {
+ if y == 0.0 {
+ Err(DivisionError::DividedByZero)
+ } else {
+ Ok(x / y)
+ }
+}
+```
+
+* Use `panic!` only in unrecoverable conditions - typically tests, assertions, bugs or a need to crash the application for some explicit reason.
+* There are 3 relevant macros that can replace `panic!` in appropriate conditions:
+ * `todo!`, similar to panic, but alerts the compiler that you are aware that there is code missing.
+ * `unreachable!`, you have reasoned about the code block and are sure that condition `xyz` is not possible and if ever becomes possible you want to be alerted.
+ * `unimplemented!`, specially useful for alerting that a block is not yet implement with a reason.
+
+## 4.2 Avoid `unwrap`/`expect` in Production
+
+Although `expect` is preferred to `unwrap`, as it can have context, they should be avoided in production code as there are smarter alternatives to them. Considering that, they should be used in the following scenarios:
+- In tests, assertions or test helper functions.
+- When failure is impossible.
+- When the smarter options can't handle the specific case.
+
+### 🚨 Alternative ways of handling `unwrap`/`expect`:
+
+* If your `Result` (or `Option`) can have a predefined early return value in case of `Result::Err`, that doesn't need to know the `Err` value, use `let Ok(..) = else { return ... }` pattern, as it helps with flatten functions:
+```rust
+let Ok(json) = serde_json::from_str(&input) else {
+ return Err(MyError::InvalidJson);
+}
+```
+* If your `Result` (or `Option`) needs error recovery in case of `Result::Err`, that doesn't need to know the `Err` value, use `if let Ok(..) else { ... }` pattern:
+```rust
+if let Ok(json) = serde_json::from_str(&input) else {
+ ...
+} else {
+ Err(do_something_with_input(&input))
+}
+```
+* Functions that can have to handle `Option::None` values are recommended to return `Result<T, E>`, where `E` is a crate or module level error, like the examples above.
+* Lastly `unwrap_or`, `unwrap_or_else` or `unwrap_or_default`, these functions help you create alternative exits to unwrap that manage the uninitialized values.
+
+## 4.3 `thiserror` for Crate level errors
+
+Deriving Error manually is verbose and error prone, the rust ecosystem has a really good crate to help with this, `thiserror`. It allows you to create error types that easily implement `From` trait as well as easy error message (`Display`), improving developer experience while working seamlessly with `?` and integrating with `std::error::Error`:
+
+```rust
+#[derive(Debug, thiserror::Error)]
+pub enum MyError {
+ #[error("Network Timeout")]
+ Timeout,
+ #[error("Invalid data: {0}")]
+ InvalidData(String),
+ #[error(transparent)]
+ Serialization(#[from] serde_json::Error),
+ #[error("Invalid request information. Header: {headers}, Metadata: {metadata}")]
+ InvalidRequest {
+ headers: Headers,
+ metadata: Metadata
+ }
+}
+```
+
+### Error Hierarchies and Wrapping
+
+For layered systems the best practice is to use nested `enum/struct` errors with `#[from]`:
+
+```rust
+use crate::database::DbError;
+use crate::external_services::ExternalHttpError;
+
+#[derive(Debug, thiserror::Error)]
+pub enum ServiceError {
+ #[error("Database handler error: {0}")]
+ Db(#[from] DbError),
+ #[error("External services error: {0}")]
+ ExternalServices(#[from] ExternalHttpError)
+}
+```
+
+## 4.4 Reserve `anyhow` for Binaries
+
+`anyhow` is an amazing crate, and quite useful for projects that are beginning and need accelerated speed. However, there is a turning point where it just painfully propagates through your code, considering this, `anyhow` is recommended only for **binaries**, where ergonomic error handling is needed and there is no need for precise error types:
+
+```rust
+use anyhow::{Context, Result, anyhow};
+
+fn main() -> Result<()> {
+ let content = std::fs::read_to_string("config.json")
+ .context("Failed to read config file")?;
+ Config::from_str(&content)
+ .map_err(|err| anyhow!("Config parsing error: {err}"))
+}
+```
+
+### 🚨 `Anyhow` Gotchas
+
+* Keeping the `context` and `anyhow` strings up-to-date in all code base is harder than keeping `thiserror` messages as you don't have a single point of entry.
+* `anyhow::Result` erases context that a caller might need, so avoid using it in a library.
+* test helper functions can use `anyhow` with little to no issues.
+
+## 4.5 Use `?` to Bubble Errors
+
+Prefer using `?` over verbose alternatives like `match` chains:
+```rust
+fn handle_request(req: &Request) -> Result<ValidatedRequest, MyError> {
+ validate_headers(req)?;
+ validate_body_format(req)?;
+ validate_credentials(req)?;
+ let body = Body::try_from(req)?;
+
+ Ok(ValidatedRequest::try_from((req, body))?)
+}
+```
+
+> In case error recovery is needed, use `or_else`, `map_err`, `if let Ok(..) else`. To **inspect or log your error**, use `inspect_err`.
+
+## 4.6 Unit Test should exercise errors
+
+While many errors don't implement PartialEq and Eq, making it hard to do direct assertions between them, it is possible to check the error messages with `format!` or `to_string()`, making the errors meaningful and test validated:
+
+```rust
+#[test]
+fn error_does_not_implement_partial_eq() {
+ let err = divide(10., 0.0).unwrap_err();
+ assert_eq!(err.to_string(), "division by zero");
+}
+
+#[test]
+fn error_implements_partial_eq() {
+ let err = process(my_value).unwrap_err();
+
+ assert_eq!(
+ err,
+ MyError {
+ ..
+ }
+ )
+}
+```
+
+## 4.7 Important Topics
+
+### Custom Error Structs
+
+Sometimes you don't need an enum to handle your errors, as there is only one type of error that your module can have. This can be solved with `struct Errors`:
+
+```rust
+#[derive(Debug, thiserror::Error, PartialEq)]
+#[error("Request failed with code `{code}`: {message}")]
+struct HttpError {
+ code: u16,
+ message: String
+}
+```
+
+### Async Errors
+
+When using async runtimes, like Tokio, make sure that your errors implement `Send + Sync + 'static` where needed, specially in tasks or across `.await` boundaries:
+
+```rust
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ ...
+ Ok(())
+}
+```
+
+> Avoid `Box<dyn std::error::Error>` in libraries unless it is really needed
diff --git a/.agents/skills/rust-best-practices/references/chapter_05.md b/.agents/skills/rust-best-practices/references/chapter_05.md
new file mode 100644
index 0000000000..397fef5d77
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_05.md
@@ -0,0 +1,381 @@
+# Chapter 5 - Automated Testing
+
+> Tests are not just for correctness. They are the first place people look to understand how your code works.
+
+* Tests in rust are declared with the attribute macro `#[test]`. Most code editors can compile and run the functions declared under the macro individually or blocks of them.
+* Test can have special compilation flags with `#[cfg(test)]`. Also executable in code editors if it contained `#[test]`, it is a good way to mock complicated functions or override traits.
+
+## 5.1 Tests as Living Documentation
+
+In Rust, as in many other languages, tests often show how the functions are meant to be used. If a test is clear and targeted, it's often more helpful than reading the function body, when combined with other tests, they serve as living documentation.
+
+### Use descriptive names
+
+> In the unit test name we should see the following:
+> * `unit_of_work`: which *function* we are calling. The **action** that will be executed. This is often be the name of the the test `mod` where the function is being tested.
+```rust
+#[cfg(test)]
+mod test {
+ mod function_name {
+ #[test]
+ fn returns_y_when_x() { ... }
+ }
+}
+```
+> * `expected_behavior`: the set of **assertions** that we need to verify that the test works.
+> * `state_that_the_test_will_check`: the general **arrangement**, or setup, of the specific test case.
+
+#### ❌ Don't use a generic name for a test
+```rust
+#[test]
+fn test_add_happy_path() {
+ assert_eq!(add(2, 2), 4);
+}
+```
+#### ✅ Use a name which reads like a sentence, describing the desired behavior
+> Alternatively, if you function has too many tests, you can blob them together in a `mod`, it makes it easier to read and navigate.
+
+```rust
+// OPTION 1
+#[test]
+fn process_should_return_blob_when_larger_than_b() {
+ let a = setup_a_to_be_xyz();
+ let b = Some(2);
+ let expected = MyExpectedStruct { ... };
+
+ let result = process(a, b).unwrap();
+
+ assert_eq!(result, expected);
+}
+
+// OPTION 2
+mod process {
+ #[test]
+ fn should_return_blob_when_larger_than_b() {
+ let a = setup_a_to_be_xyz();
+ let b = Some(2);
+ let expected = MyExpectedStruct { ... };
+
+ let result = process(a, b).unwrap();
+
+ assert_eq!(result, expected);
+ }
+}
+```
+
+> When executing `cargo test` the test output for each option will look like:
+> Option 1: `process_should_return_blob_when_larger_than_b`.
+> Option 2: `process::should_return_blob_when_larger_than_b`.
+
+### Use modules for organization
+
+Most IDEs can run a single module of tests all together.
+The test name in the output will also contain the name of the module.
+Together, that means you can use the module name to group related tests together:
+
+```rust
+#[cfg(test)]
+mod test { // IDEs will provide a ▶️ button here
+
+ mod process {
+ #[test] // IDEs will provide a ▶️ button here
+ fn returns_error_xyz_when_b_is_negative() {
+ let a = setup_a_to_be_xyz();
+ let b = Some(-5);
+ let expected = MyError::Xyz;
+
+ let result = process(a, b).unwrap_err();
+
+ assert_eq!(result, expected);
+ }
+
+ #[test] // IDEs will provide a ▶️ button here
+ fn returns_invalid_input_error_when_a_and_b_not_present() {
+ let a = None;
+ let b = None;
+ let expected = MyError::InvalidInput;
+
+ let result = process(a, b).unwrap_err();
+
+ assert_eq!(result, expected);
+ }
+ }
+}
+```
+
+### Only test one behavior per function
+
+To keep tests clear, they should describe _one_ thing that the unit does.
+This makes it easier to understand why a test is failing.
+
+#### ❌ Don't test multiple things in the same test
+```rust
+fn test_thing_parser(...) {
+ assert!(Thing::parse("abcd").is_ok());
+ assert!(Thing::parse("ABCD").is_err());
+}
+```
+
+#### ✅ Test one thing per test
+```rust
+#[cfg(test)]
+mod test_thing_parser {
+ #[test]
+ fn lowercase_letters_are_valid() {
+ assert!(
+ Thing::parse("abcd").is_ok(),
+ // Works like `eprintln`, `format` and `println` macros
+ "Thing parse error: {:?}",
+ Thing::parse("abcd").unwrap_err()
+ );
+ }
+
+ #[test]
+ fn capital_letters_are_invalid() {
+ assert!(Thing::parse("ABCD").is_err());
+ }
+}
+```
+
+> `Ok` scenarios should have an `eprintln` of the `Err` case.
+
+### Use very few, ideally one, assertion per test
+
+When there are multiple assertions per test, it's both harder to understand the intended behavior and
+often requires many iterations to fix a broken test, as you work through assertions one by one.
+
+❌ Don't include many assertions in one test:
+
+```rust
+#[test]
+fn test_valid_inputs() {
+ assert!(the_function("a").is_ok());
+ assert!(the_function("ab").is_ok());
+ assert!(the_function("ba").is_ok());
+ assert!(the_function("bab").is_ok());
+}
+```
+
+If you are testing separate behaviors, make multiple tests each with descriptive names.
+To avoid boilerplate, either use a shared setup function or [rstest](https://crates.io/crates/rstest) cases *with descriptive test names*:
+```rust
+#[rstest]
+#[case::single("a")]
+#[case::first_letter("ab")]
+#[case::last_letter("ba")]
+#[case::in_the_middle("bab")]
+fn the_function_accepts_all_strings_with_a(#[case] input: &str) {
+ assert!(the_function(input).is_ok());
+}
+```
+
+> Considerations when using `rstest`
+>
+> * It's harder for both IDEs and humans to run/locate specific tests.
+> * Expectation vs condition naming is now visually inverted (expectation first).
+
+## 5.2 Add Test Examples to your Docs
+
+We will deep dive into docs at a later stage, so in this section we will just briefly go over how to add tests to you docs. Rustdoc can turn examples into executable tests using `///` with a few advantages:
+
+* These tests run with `cargo test` **BUT NOT** `cargo nextest run`. If using `nextest`, make sure to run `cargo t --doc` separately.
+* They serve both as documentation and correctness checks, and are kept up to date by changes, due to the fact that the compiler checks them.
+* No extra testing boilerplate. You can easily hide test sections by prefixing the line with `#`.
+* ❗ There is no issue if you have test duplication between doc-tests and other non-public facing tests.
+
+```rust
+/// Helper function that adds any two numeric values together.
+/// This function reasons about which would be the correct type to parse based on the type
+/// and the size of the numeric value.
+///
+/// # Examples
+///
+/// ```rust
+/// # use crate_name::generic_add;
+/// use num::numeric;
+///
+/// # assert_eq!(
+/// generic_add(5.2, 4) // => 9.2
+/// # , 9.2)
+///
+/// # assert_eq!(
+/// generic_add(2, 2.0) // => 4
+/// # , 4)
+/// ```
+```
+
+This documentation code would look like:
+```rust
+use num::numeric;
+
+generic_add(5.2, 4) // => 9.2
+generic_add(2, 2.0) // => 4
+```
+
+## 5.3 Unit Test vs Integration Tests vs Doc tests
+
+As a general rule, without delving into *test pyramid naming*, rust has 3 sets of tests:
+
+### Unit Test
+
+Tests that go in the **same module** as the **tested unit** was declared, this allows the test runner to have visibility over private functions and parent `use` declarations. They can also consume `pub(crate)` functions from other modules if needed. Unit tests can be more focused on **implementation and edge-cases checks**.
+
+* They should be as simple as possible, testing one state and one behavior of the unit. KISS.
+* They should test for errors and edge cases.
+* Different tests of the same unit can be combined under a single `#[cfg(test)] mod test_unit_of_work {...}`, allowing multiple submodules for different `units_of_work`.
+* Try to keep external states/side effects to your API to minimum and focus those tests on the `mod.rs` files.
+* Tests that are not yet fully implemented can be ignored with the `#[ignore = "optional message"]` attribute.
+* Tests that intentionally panic should be annotated with the attribute `#[should_panic]`.
+
+```rust
+#[cfg(test)]
+mod unit_of_work_tests {
+ use super::*;
+
+ #[test]
+ fn unit_state_behavior() {
+ let expected = ...;
+ let result = ...;
+ assert_eq!(result, expected, "Failed because {}", result - expected);
+ }
+}
+```
+
+### Integration Tests
+
+Tests that go under the `tests/` directory, they are entirely external to your library and use the same code as any other code would use, not have access to private and crate level functions, which means they can **only test** functions on your **public API**.
+
+> Their purpose is to test whether many parts of the code work together correctly, units of code that work correctly on their own could have problems when integrated.
+
+* Test for happy paths and common use cases.
+* Allow external states and side effects, [testcontainers](https://rust.testcontainers.org/) might help.
+* if testing binaries, try to break **executable** and **functions** into `src/main.rs` and `src/lib.rs`, respectively.
+
+```
+├── Cargo.lock
+├── Cargo.toml
+├── src
+│ └── lib.rs
+└── tests
+ ├── mod.rs
+ ├── common
+ │ └── mod.rs
+ └── integration_test.rs
+```
+
+### Doc Testing
+
+As mentioned in section [5.2](#52-add-test-examples-to-your-docs), doc tests should have happy paths, general public API usage and more powerful attributes that improve documentation, like custom CSS for the code blocks.
+
+### Attributes:
+
+* `ignore`: tells rust to ignore the code, usually not recommended, if you want just a code formatted text, use `text`.
+* `should_panic`: tells the rust compiler that this example block will panic.
+* `no_run`: compiles but doesn't execute the code, similar to `cargo check`. Very useful when dealing with side-effects for documentation.
+* `compile_fail`: Test rustdoc that this block should cause a compilation fail, important when you want to demonstrate wrong use cases.
+
+## 5.4 How to `assert!`
+
+Rust comes with 2 macros to make assertions:
+* `assert!` for asserting boolean values like `assert!(value.is_ok(), "'value' is not Ok: {value:?}")`
+* `assert_eq!` for checking equality between two different values, `assert_eq!(result, expected, "'result' differs from 'expected': {}", result.diff(expected))`.
+
+### 🚨 `assert!` reminders
+* Rust asserts support formatted strings, like the previous examples, those strings will be printed in case of failure, so it is a good practice to add what the actual state was and how it differs from the expected.
+* If you don't care about the exact pattern matching value, using `matches!` combined with `assert!` might be a good alternative.
+```rust
+assert!(matches!(error, MyError::BadInput(_), "Expected `BadInput`, found {error}"));
+```
+* Use `#[should_panic]` wisely. It should only be used when panic is the desired behavior, prefer result instead of panic.
+* There are some other that can enhance your testing experience like:
+ * [`rstest`](https://crates.io/crates/rstest): fixture based test framework with procedural macros.
+ * [`pretty_assertions`](https://crates.io/crates/pretty_assertions): overrides `assert_eq` and `assert_ne`, and creates colorful diffs between them.
+
+## 5.5 Snapshot Testing with `cargo insta`
+
+> When correctness is visual or structural, snapshots tell the story better than asserts.
+
+1. Add to your dependencies:
+```toml
+insta = { version = "1.42.2", features = ["yaml"] }
+```
+> For most real world applications the recommendation is to use YAML snapshots of serializable values. This is because they look best under version control and the diff viewer and support redaction. To use this enable the yaml feature of insta.
+
+2. For a better review experience, add the CLI `cargo install cargo-insta`.
+
+3. Writing a simple test:
+```rust
+fn split_words(s: &str) -> Vec<&str> {
+ s.split_whitespace().collect()
+}
+
+#[test]
+fn test_split_words() {
+ let words = split_words("hello from the other side");
+ insta::assert_yaml_snapshot!(words);
+}
+```
+
+4. Run `cargo insta test` to execute, and `cargo insta review` to review conflicts.
+
+To learn more about `cargo insta` check out its [documentation](https://insta.rs/docs/quickstart/) as it is a very complete and well documented tool.
+
+### What is snapshot testing?
+
+Snapshot testing compares your output (text, Json, HTML, YAML, etc) against a saved "golden" version. On future runs, the test fails if the output changes, unless humanly approved. It is perfect for:
+* Generate code.
+* Serializing complex data.
+* Rendered HTML.
+* CLI output.
+
+#### ❌ What not to test with snapshot
+* Very stable, numeric-only or small structured data associated logic (prefer `assert_eq!`).
+* Critical path logic (prefer precise unit tests).
+* Flaky tests, randomly generated output, unless redacted.
+* Snapshots of external resources, use mocks and stubs.
+
+## 5.6 ✅ Snapshot Best Practices
+
+* Named snapshots, it gives meaningful snapshot files names, e.g. `snapshots/this_is_a_named_snapshot.snap`
+```rust
+assert_snapshot!("this_is_a_named_snapshot", output);
+```
+
+* Keep snapshots small and clear.
+```rust
+// ✅ Best case:
+assert_snapshot!("app_config/http", whole_app_config.http);
+
+// ❌ Worst case:
+assert_snapshot!("app_config", whole_app_config); // Huge object
+```
+
+> #### 🚨 Avoid snapshotting huge objects
+> Huge objects become hard to review and reason about.
+
+* Avoid snapshotting simple types (primitives, flat enums, small structs):
+```rust
+// ✅ Better:
+assert_eq!(meaning_of_life, 42);
+
+// ❌ OVERKILL:
+assert_snapshot!("the_meaning_of_life", meaning_of_life); // meaning_of_life == 42
+```
+
+* Use [redactions](https://insta.rs/docs/redactions/) for unstable fields (randomly generated, timestamps, uuid, etc):
+```rust
+use insta::assert_json_snapshot;
+
+#[test]
+fn endpoint_get_user_data() {
+ let data = http::client.get_user_data();
+ assert_json_snapshot!(
+ "endpoints/subroute/get_user_data",
+ data,
+ ".created_at" => "[timestamp]",
+ ".id" => "[uuid]"
+ );
+}
+```
+* Commit your snapshots into git. They will be stored in `snapshots/` alongside your tests.
+* Review changes carefully before accepting.
diff --git a/.agents/skills/rust-best-practices/references/chapter_06.md b/.agents/skills/rust-best-practices/references/chapter_06.md
new file mode 100644
index 0000000000..2467e51c2b
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_06.md
@@ -0,0 +1,161 @@
+# Chapter 6 - Generics, Dynamic Dispatch and Static Dispatch
+
+> Static where you can, dynamic where you must
+
+Rust allows you to handle polymorphic code in two ways:
+* **Generics / Static Dispatch**: compile-time, monomorphized per use.
+* **Trait Objects / Dynamic Dispatch**: runtime vtable, single implementation.
+
+Understanding the trade-offs lets you write faster, smaller and more flexible code.
+
+## 6.1 [Generics](https://doc.rust-lang.org/book/ch10-00-generics.html)
+
+Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is generics: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.
+
+We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let's first look at how to define functions, structs, enums, and methods using generics. Generics can also be used to implement Type State Pattern and constrain a struct functionality to certain expected types, more on type state on [Chapter 7](./chapter_07.md).
+
+[Generics by Examples](https://doc.rust-lang.org/rust-by-example/generics.html).
+
+### Generics Performance
+
+You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types. Rust accomplishes this by performing monomorphization of the code using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. The compiler checks for all occurrences of the generic parameter and generates code for the concrete types the generic code is called with.
+
+## 6.2 Static Dispatch: `impl Trait` or `<T: Trait>`
+
+A static dispatch is basically a constrained version of a generics, a trait bounded generic, at compile-time it is able to check if your generic satisfies the declared traits.
+
+### ✅ Best when:
+* You want **zero runtime cost**, by paying the compile time cost.
+* You need **tight loops or performance**.
+* Your types are **known at compile time**.
+* Your are working with **single-use implementations** (monomorphized).
+
+### 🏎️ Example: High-performance function with generic
+```rust
+fn specialized_sum<T: MyTrait, U: Iterator<Item = T>>(iter: U) -> T {
+ iter.map(|x| x.random_mapping()).sum()
+}
+
+// or, equivalent, more modern
+fn specialized_sum<T: MyTrait>(iter: impl Iterator<Item = T>) -> T {
+ iter.map(|x| x.random_mapping()).sum()
+}
+```
+
+This is compiled into **specialized machine code** for each usage, fast and inlined.
+
+## 6.3 Dynamic Dispatch: `dyn Trait`
+
+Usually dynamic dispatch is used with some kind of pointer or a reference, like `Box<dyn Trait>`, `Arc<dyn Trait>` or `&dyn trait`.
+
+### ✅ Best when:
+* You absolutely need runtime polymorphism.
+* You need to **store different implementations** in one collection.
+* You want to **abstract internals behind a stable interface**.
+* You are writing a **plugin-style architecture**.
+
+> ❗ Closer to what you would get in an object oriented language and can have some heavy costs associated to it. Can avoid generic entirely and let you mix types that implement the same traits.
+
+### 🚚 Example: Heterogeneous collection
+
+```rust
+trait Animal {
+ fn greet(&self) -> String;
+}
+
+struct Dog;
+impl Animal for Dog {
+ fn greet(&self) -> String {
+ "woof".to_string()
+ }
+}
+
+struct Cat;
+impl Animal for Cat {
+ fn greet(&self) -> String {
+ "meow".to_string()
+ }
+}
+
+fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {
+ for animal in animals {
+ println!("{}", animal.greet())
+ }
+}
+```
+
+## 6.4 Trade-off summary
+
+| | Static Dispatch (impl Trait) | Dynamic Dispatch (dyn Trait) |
+|------------------- |------------------------------ |---------------------------------- |
+| Performance | ✅ Faster, inlined | ❌ Slower: vtable indirection |
+| Compile time | ❌ Slower: monomorphization | ✅ Faster: shared code |
+| Binary size | ❌ Larger: per-type codegen | ✅ Smaller |
+| Flexibility | ❌ Rigid, one type at a time | ✅ Can mix types in collections |
+| Use in trait fn() | ❌ Traits must be object-safe | ✅ Works with trait objects |
+| Errors | ✅ Clearer | ❌ Erased types can confuse errors |
+
+* Prefer generics/static dispatch when you control the call site and want performance.
+* Use dynamic dispatch when you need abstraction, plugins or mixed types. 🚨 Runtime cost.
+* If you are not sure, start with generics, trait bound them - then use `Box<dyn Trait>` when flexibility outweighs speed.
+
+> Favor static dispatch until your trait needs to live behind a pointer.
+
+## 6.5 Best Practices for Dynamic Dispatch
+
+Dynamic dispatch `Ptr<dyn Trait>` is a powerful tool, but it also has significant performance trade-offs. You should only reach for it when **type erasure or runtime polymorphism** are essential. It is important to know when you need Trait Objects:
+
+### ✅ Use Dynamic Dispatch When:
+
+* You need heterogeneous types in a collection:
+```rust
+fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {
+ for animal in animals {
+ println!("{}", animal.greet())
+ }
+}
+```
+
+* You want runtime plugins or hot-swappable components.
+* You want to abstract internals from the caller (library design).
+
+
+### ❌ Avoid Dynamic Dispatch When:
+
+* You control the concrete types.
+* You are writing code in performance critical paths.
+* You can express the same logic in other ways while keeping simplicity, e.g. generics.
+
+## 6.6 🚨 Trait Objects Ergonomics
+
+* Prefer `&dyn Trait` over `Box<dyn Trait>` when you don't need ownership.
+* Use `Arc<dyn Trait>` for shared access across threads.
+* Don't use `dyn Trait` if the trait has methods that return `Self`.
+* **Avoid boxing too early**. Don't box inside structs unless you are sure it'll be beneficial or is required (recursive).
+```rust
+// ✅ Use generics when possible
+struct Renderer<B: Backend> {
+ backend: B
+}
+
+// ❌ Premature Boxing
+struct Renderer {
+ backend: Box<dyn Backend> // Boxing too early
+}
+```
+* If you must expose a `dyn trait` in a public API, `Box` at the boundary, not internally.
+* **Object Safety**: You can only create `dyn Traits` from object-safe traits:
+ * It has **no generic methods**.
+ * It doesn't require `Self: Sized`.
+ * All method signatures use `&self`, `&mut self` or `self`.
+ ```rust
+ // ✅ Object Safe
+ trait Runnable {
+ fn run(&self);
+ }
+
+ // ❌ Not Object Safe
+ trait Factory {
+ fn create<T>() -> T; // generic methods are not allowed
+ }
+ ```
diff --git a/.agents/skills/rust-best-practices/references/chapter_07.md b/.agents/skills/rust-best-practices/references/chapter_07.md
new file mode 100644
index 0000000000..f7eab2c4f5
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_07.md
@@ -0,0 +1,226 @@
+# Chapter 7 - Type State Pattern
+
+Models state at compile time, preventing bugs by making illegal states unrepresentable. It takes advantage of the Rust generics and type system to create sub-types that can only be reached if a certain condition is achieved, making some operations illegal at compile time.
+
+> Recently it became the standard design pattern of Rust programming. However, it is not exclusive to Rust, as it is achievable and has inspired other languages to do the same [swift](https://swiftology.io/articles/typestate/) and [typescript](https://catchts.com/type-state).
+
+## 7.1 What is Type State Pattern?
+
+**Type State Pattern** is a design pattern where you encode different **states** of the system as **types**, not as runtime flags or enums. This allows the compiler to enforce state transitions and prevent illegal actions at compile time. It also improves the developer experience, as developers only have access to certain functions based on the state of the type.
+
+> Invalid states become compile errors instead of runtime bugs.
+
+## 7.2 Why use it?
+
+* Avoids runtime checks for state validity. If you reach certain states, you can make certain assumptions of the data you have.
+* Models state transitions as type transitions. This is similar to a state machine, but in compile time.
+* Prevents data misuse, e.g. using uninitialized objects.
+* Improves API safety and correctness.
+* The phantom data field is removed after compilation so no extra memory is allocated.
+
+## 7.3 Simple Example: File State
+
+[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/simple-type-state)
+```rust
+use std::{io, path::{Path, PathBuf}};
+
+struct FileNotOpened;
+struct FileOpened;
+
+#[derive(Debug)]
+struct File<State> {
+ /// Path to the opened file
+ path: PathBuf,
+ /// Open `File` handler
+ handle: Option<std::fs::File>,
+ /// Type state manager
+ _state: std::marker::PhantomData<State>
+}
+
+impl File<FileNotOpened> {
+ /// `open` is the only entry point for this struct.
+ /// * When called with a valid path, it will return a `File<FileOpened>` with a valid `handler` and `path`
+ /// * `open` serves as an alternative to `new` and `defaults` methods (usable when your struct needs valid data to exist).
+ fn open(path: &Path) -> io::Result<File<FileOpened>> {
+ // If file is invalid, it will return `std::io::Error`
+ let file = std::fs::File::open(path)?;
+ Ok(
+ File {
+ path: path.to_path_buf(),
+ // Always valid
+ handle: Some(file),
+ _state: std::marker::PhantomData::<FileOpened>
+ }
+ )
+ }
+}
+
+impl File<FileOpened> {
+ /// Reads the content of the `File` as a `String`.
+ /// `read` can only be called by state `File<FileOpened>`
+ fn read(&mut self) -> io::Result<String> {
+ use io::Read;
+
+ let mut content = String::new();
+ let Some(handle)= self.handle.as_mut() else {
+ unreachable!("Safe to unwrap as state can only be reached when file is open");
+ };
+ handle.read_to_string(&mut content)?;
+ Ok(content)
+ }
+
+ /// Returns the valid path buffer.
+ fn path(&self) -> &PathBuf {
+ &self.path
+ }
+}
+```
+
+## 7.4 Real-World Examples
+
+### Builder Pattern with Compile-Time Guarantees
+
+> Forces the user to **set required fields** before calling `.build()`.
+
+[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/type-state-builder)
+
+A type-state pattern can have more than one associated states:
+
+```rust
+use std::marker::PhantomData;
+
+struct MissingName;
+struct NameSet;
+struct MissingAge;
+struct AgeSet;
+
+#[derive(Debug)]
+struct Person {
+ name: String,
+ age: u8,
+ email: Option<String>,
+}
+
+struct Builder<NameState, AgeState> {
+ name: Option<String>,
+ age: u8,
+ email: Option<String>,
+ _name_marker: PhantomData<NameState>,
+ _age_marker: PhantomData<AgeState>,
+}
+
+impl Builder<MissingName, MissingAge> {
+ fn new() -> Self {
+ Builder { name: None, age: 0, _name_marker: PhantomData, _age_marker: PhantomData, email: None }
+ }
+
+ fn name(self, name: String) -> Builder<NameSet, MissingAge> {
+ Builder { name: Some(name), _name_marker: PhantomData::<NameSet>, age: self.age, _age_marker: PhantomData, email: None }
+ }
+
+ fn age(self, age: u8) -> Builder<MissingName, AgeSet> {
+ Builder { age, _age_marker: PhantomData::<AgeSet>, name: None, _name_marker: PhantomData, email: None }
+ }
+}
+
+impl Builder<NameSet, MissingAge> {
+ fn age(self, age: u8) -> Builder<NameSet, AgeSet> {
+ Builder { age, _age_marker: PhantomData::<AgeSet>, name: self.name, _name_marker: PhantomData::<NameSet>, email: None }
+ }
+}
+
+impl Builder<MissingName, AgeSet> {
+ fn email(self, email: String) -> Self {
+ Self { name: self.name , age: self.age , email: Some(email) , _name_marker: self._name_marker , _age_marker: self._age_marker }
+ }
+
+ fn name(self, name: String) -> Builder<NameSet, AgeSet> {
+ Builder { name: Some(name), _name_marker: PhantomData::<NameSet>, age: self.age, _age_marker: PhantomData::<AgeSet>, email: self.email }
+ }
+}
+
+impl Builder<NameSet, AgeSet> {
+ fn build(self) -> Person {
+ Person {
+ name: self.name.unwrap_or_else(|| unreachable!("Name is guarantee to be set")),
+ age: self.age,
+ email: self.email,
+ }
+ }
+}
+```
+
+Although a bit more verbose than a usual builder, this guarantees that all necessary fields are present (note that e-mail is optional field only present in the final builder).
+
+#### Usage:
+```rust
+// ✅ Valid cases
+let person: Person = Builder::new().name("name".to_string()).age(30).build();
+let person: Person = Builder::new().age(30).name("name".to_string()).build();
+let person: Person = Builder::new().age(30).name("name".to_string()).email("[email protected]".to_string()).build();
+
+// ❌ Invalid cases
+let person: Person = Builder::new().name("name".to_string()).build(); // ❌ Compile error: Age required to `build`
+let person: Person = Builder::new().age(30).build(); // ❌ Compile error: Name required to `build`
+let person: Person = Builder::new().age(30).email("[email protected]".to_string()).build(); // ❌ Compile error: Name required to `build`
+let person: Person = Builder::new().build();// ❌ Compile error: Name and Age required to `build`
+```
+
+### Network Protocol State Machine
+
+Illegal transitions like sending a message before connecting **simply don't compile**:
+
+```rust
+// Mock example
+struct Disconnected;
+struct Connected;
+
+struct Client<State> {
+ stream: Option<std::net::TcpStream>,
+ _state: std::marker::PhantomData<State>
+}
+
+impl Client<Disconnected> {
+ fn connect(addr: &str) -> std::io::Result<Client<Connected>> {
+ let stream = std::net::TcpStream::connect(addr)?;
+ Ok(Client {
+ stream: Some(stream),
+ _state: std::marker::PhantomData::<Connected>
+ })
+ }
+}
+
+impl Client<Connected> {
+ fn send(&mut self, msg: &str) {
+ use std::io::Write;
+ let Some(stream) = self.stream.as_mut() else {
+ unreachable!("Stream is guarantee to be set");
+ };
+ stream.write_all(msg.as_bytes())
+ }
+}
+```
+
+## 7.5 Pros and Cons
+
+### ✅ Use Type-State Pattern When:
+* Your want **compile-time state safety**.
+* You need to enforce **API constraints**.
+* You are writing a library/crate that is heavy dependent on variants.
+* Your want to replace runtime booleans or enums with **type-safe code paths**.
+* You need compile time correctness.
+
+### ❌ Avoid it when:
+* Writing trivial states like enums.
+* Don't need type-safety.
+* When it leads to overcomplicated generics.
+* When runtime flexibility is required.
+
+### 🚨 Downsides and Cautions
+* Can lead to more **verbose solutions**.
+* Can lead to **complex type signatures**.
+* May require **unsafe** to return **variant outputs** based on different states.
+* May required a bunch of duplication (e.g. same struct field reused).
+* PhantomData is not intuitive for beginners and can feel a bit hacky.
+
+> Use this pattern when it **saves bugs, increases safety or simplifies logic**, not just for cleverness.
diff --git a/.agents/skills/rust-best-practices/references/chapter_08.md b/.agents/skills/rust-best-practices/references/chapter_08.md
new file mode 100644
index 0000000000..19153401f9
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_08.md
@@ -0,0 +1,254 @@
+# Chapter 8 - Comments vs Documentation
+
+> Clear code beats clear comments. However, when the why isn't obvious, comment it plainly - or link to where you can read more context.
+
+## 8.1 Comments vs Documentation: Know the Difference
+
+| Purpose | Use `// comment` | Use `/// doc` or `//! crate doc` |
+|-------------- |------------------------------------------- |---------------------------------------------------------------- |
+| Describe Why | ✅ Yes - explains tricky reasoning | ❌ Not for documentation |
+| Describe API | ❌ Not useful | ✅ Yes - public interfaces, usage, details, errors, panics |
+| Maintainable | 🚨 Often becomes obsolete and hard to reason | ✅ Tied to code, appears in generated docs and can run test cases |
+| Visibility | Local development only | Exported to users and tools like `cargo doc` |
+
+## 8.2 When to use comments
+
+Use `//` comments (double slashed) when something can't be expressed clearly in code, like:
+* **Safety Guarantees**, some of which can be better expressed with code conditionals.
+* Workarounds or **Optimizations**.
+* Legacy or **platform-specific** behaviors. Some of them can be expressed with `#[cfg(..)]`.
+* Links to **Design Docs** or **ADRs**.
+* Assumptions or **gotchas** that aren't obvious.
+
+> Name your comments! For example, a comment regarding a safety guarantee should start with `// SAFETY: ...`.
+
+### ✅ Good comment:
+```rust
+// SAFETY: `ptr` is guaranteed to be non-null and aligned by caller
+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }
+```
+
+### ✅ Design context comment:
+```rust
+// CONTEXT: Reuse root cert store across subgraphs to avoid duplicate OS calls:
+// [ADR-12](link/to/adr-12): TLS Performance on MacOS
+```
+
+## 8.3 When comments get in the way
+
+Avoid comments that:
+* Restate obvious things (`// increment i by 1 for the next loop`).
+* Can grow stale over time.
+* `TODO`s without actions (links to some versioned issue).
+* Could be replaced by better naming or smaller functions.
+
+### ❌ Bad comment:
+```rust
+fn compute(counter: &mut usize) {
+ // increment by 1
+ *counter += 1;
+}
+```
+
+### ❌ Too long or outdated
+```rust
+// Originally written in 2028 for some now-defunct platform
+```
+
+## 8.4 Don't Write Living Documentation (living comments)
+
+Comments as a "living documentation" is a **dangerous myth**, as comments are **not free**:
+* They **rot** - nobody compiles comments.
+* They **mislead** - readers usually assume they are true with no critique, e.g. "the other developer knows this code better than I do".
+* They **go stale** - unless maintained with the code, they become irrelevant.
+* They are **noisy** - comments can clutter your code with multiple unnecessary lines.
+
+If something deserves to live beyond a PR, put it in:
+* An **ADR** (Architectural Design Record).
+* A Design Document.
+* Document it **in code** by using types, doc comments, examples, renaming code blocks into cleaner functions.
+* Add tests to cover and explain the change.
+
+> ### 🚨 If you find a comment, **read it in context**. Does it still make sense? If not, remove or update it, or ask for help. Comments should bother you.
+
+## 8.5 Replace Comments with Code
+
+Instead of long commented blocks, break logic into named helper functions:
+
+#### ❌ Commented code block:
+```rust
+fn save_user(&self) -> Result<(), MyError> {
+ // check if the user is authenticated
+ if self.is_authenticated() {
+ // serialize user data
+ let data = serde_json::to_string(self)?;
+ // write to file
+ std::fs::write(self.path(), data)?;
+ }
+}
+```
+**✅ Extract for clarity**:
+
+```rust
+fn save_auth_user(&self) -> Result<PathBuf, MyError> {
+ if self.is_authenticated() {
+ let path = self.path();
+ let serialized_user = serde_json::to_string(self)?;
+ std::fs::write(path, serialized_user)?;
+ Ok(path)
+ } else {
+ Err(MyError::UserNotAuthenticated)
+ }
+}
+```
+
+## 8.6 `TODO` should become issues
+
+Don't leave `// TODO:` scattered around the codebase with no owner. Instead:
+1. File Github Issue or Jira Ticket. (Prefer github issues on public repositories).
+2. Reference the issue in the code:
+
+```rust
+// TODO(issue #42): Remove workaround after bugfix
+```
+
+This makes `TODO`s trackable, actionable and visible to everyone.
+
+## 8.7 When to use doc comments
+
+Use `///` doc comments to document:
+* All **public functions, structs, traits, enums**.
+* Their purpose, their usage and their behaviors.
+* Anything developers need to understand how to use it correctly.
+* Add context that related to `Errors` and `Panics`.
+* Plenty of examples.
+
+### ✅ Good doc comment:
+
+```rust
+/// Loads [`User`] profile from disk
+///
+/// # Error
+/// - Returns [`MyError`] if the file is missing [`MyError::FileNotFound`].
+/// - Returns [`MyError`] if the content is an invalid Json, [`MyError::InvalidJson`].
+fn load_user(path: &Path) -> Result<User, MyError> {...}
+```
+
+**Doc comments can also include examples, links and even tests:**
+
+```rust
+/// Returns the square of the integer part of any number.
+/// Square is limited to `u128`.
+///
+/// # Examples
+///
+/// ```rust
+/// assert_eq!(square(4.3), 16)
+/// ```
+fn square(x: impl ToInt) -> u128 { ... }
+```
+
+## 8.8 Documentation in Rust: How, When and Why
+
+Rust provides **first-class documentation tooling** via rustdoc, which makes documenting your code a key part of writing idiomatic and maintainable rust. There are doc specific lints to help with documentation, like:
+
+| Lint | Description |
+|-------------- |------------------------------------------- |
+| [missing_docs](https://doc.rust-lang.org/rustdoc/lints.html#missing_docs) | Warns that a public functions, struct, const, enum has missing documentation |
+| [broken_intra_doc_links](https://doc.rust-lang.org/rustdoc/lints.html#broken_intra_doc_links) | Detects if an internal documentation link is broken. Specially useful when things are renamed. |
+| [empty_docs](https://rust-lang.github.io/rust-clippy/master/#empty_docs) | Disallow empty docs - preventing bypass of `missing_docs` |
+| [missing_panics_doc](https://rust-lang.github.io/rust-clippy/master/#missing_panics_doc) | Warns that documentation should have a `# Panics` section if function can panic |
+| [missing_errors_doc](https://rust-lang.github.io/rust-clippy/master/#missing_errors_doc) | Warns that documentation should have a `# Errors` section if function returns a `Result` explaining `Err` conditions |
+| [missing_safety_doc](https://rust-lang.github.io/rust-clippy/master/#missing_safety_doc) | Warns that documentation should have a `# Safety` section if public facing functions have visible unsafe blocks |
+
+
+### Difference between `///` and `//!`
+
+| Style | Used for | Scope |Example |
+|---------- |------------------------------ |------------------------------------------- |---------------------------------------------------------------- |
+| `///` | Line doc comment | Public items like struct, fn, enum, consts | Documenting, giving context and usage to `fn`, `struct`, `enum`, etc |
+| `//!` | Module level doc comment | Modules or entire crates | Explaining crate/module purpose with common use cases and quickstart |
+
+### `///` Item level documentation
+
+Use `///` for functions, structs, traits, enums, const, etc:
+
+```rust
+/// Adds two numbers together.
+///
+/// # Examples
+///
+/// ```
+/// let result = my_crate::add(2, 3);
+/// assert_eq!(result, 5);
+/// ```
+pub fn add(a: i32, b: i32) -> i32 {
+ a + b
+}
+```
+* ✅ Write clear and descriptive **What it does** and **how to use it**.
+* ✅ Use `# Examples` section to better explain **how to use it**.
+* ✅ Prefer writing examples that can be tested via `cargo test`, even if you have to hide their output with starting `#`:
+```rust
+/// ```
+/// let result = my_crate::add(2, 3);
+/// # assert_eq!(result, 5);
+/// ```
+```
+* ✅ Use `# Panics`, `# Errors` and `# Safety` sections when relevant.
+* Add relevant context to the type.
+
+### `//!` Module/Crate level Documentation
+
+Use `//!` when you want to document the **purpose of a module or a crate**. It is places at the top of a `lib.rs` or `mod.rs` file, for example `engine/mod.rs`:
+```rust
+//! This module implements a custom chess engine.
+//!
+//! It handles board state, move generation and check detection.
+//!
+//! # Example
+//! ```
+//! let board = chess::engine::Board::default();
+//! assert!(board.is_valid());
+//! ```
+```
+
+## 8.9 Checklist for Documentation coverage
+
+📦 Crate-Level (lib.rs)
+- [ ] `//!` doc at top explains **what the crate does**, and **what problems it solves**.
+- [ ] Includes crate-level `# Examples` or pointers to modules.
+
+📁 Modules (mod.rs or inline)
+- [ ] `//!` doc explains **what this module is for**, its **exports**, and **invariants**.
+- [ ] Avoid repeating doc comments on re-exported items unless clarification is needed.
+
+🧱 Structs, Enums, Traits
+- `///` doc explains:
+ - [ ] The role this type plays.
+ - [ ] Invariants or expectations.
+ - [ ] Example construction or usage.
+- [ ] Consider using [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute) if external users may match on it.
+
+🔧 Functions and Methods
+- `///` doc covers:
+ - [ ] What it does.
+ - [ ] Parameters and their meaning.
+ - [ ] Return value behavior.
+ - [ ] Edge cases (`# Panics`, `# Errors`).
+ - [ ] Usage example, `# Examples`.
+
+📑 Traits
+- [ ] Explain the **purpose** of the trait (marker? dynamic dispatch?).
+- [ ] Doc for each method — include **when/why** to implement it.
+- [ ] Document clearly default implemented methods and when to override.
+
+📦 Public Constants
+- [ ] Document what they configure and when you'd want to use them.
+
+### 📌 Best Practices
+* ✅ Use examples generously — they double as test cases.
+* ✅ Prefer clarity over formality — it's for humans, not machines.
+* ✅ Prefer doc comments to explain usage, and leave implementation details to code comments if needed.
+* ✅ Use `cargo doc --open` to check your output often.
+* ✅ Add `#![deny(missing_docs)]` and other relevant doc lints in top-level modules if you want to enforce full doc coverage.
diff --git a/.agents/skills/rust-best-practices/references/chapter_09.md b/.agents/skills/rust-best-practices/references/chapter_09.md
new file mode 100644
index 0000000000..bbef404c79
--- /dev/null
+++ b/.agents/skills/rust-best-practices/references/chapter_09.md
@@ -0,0 +1,256 @@
+# Chapter 9 - Understanding Pointers
+
+Many higher level languages hide memory management, typically **passing by value** (copy data) or **passing by reference** (reference to shared data) without worrying about allocation, heap, stack, ownership and lifetimes, it is all delegated to the garbage collector or VM. Here is a comparison on this topic between a few languages:
+
+### 📌 Language Comparison
+
+| Language | Value Types | Reference/Pointer Types | Async Model & Types | Manual Memory |
+|------------ |------------------------------------- |----------------------------------------------------------- |---------------------------------------------------------------------------- |------------------------------ |
+| Python | None | Everything is a reference | async def, await, Task, coroutines and asyncio.Future | ❌ Not Allowed |
+| Javascript | Primitives | Objects | `async/await`, `Promise`, `setTimeout`. single threaded event loop | ❌ Not Allowed |
+| Java | Primitives | Objects | `Future<T>`, threads, Loom (green threads) | ❌ Almost none & not recommended |
+| Go | Values are copied unless using `&T` | Pointers (`*T`, `&T`), escape analysis | goroutines, `channels`, `sync.Mutex`, `context.Context` | ⚠️ Limited |
+| C | Primitives and structs supported | Raw pointers `T*` and `*void` | Threads, event loops (`libuv`, `libevent`) | ✅ Fully |
+| C++ | Primitives and references | Raw `T*` and smart pointers `shared_ptr` and `unique_ptr` | threads, `std::future`, `std::async`, (since c++ 20 `co_await/coroutines`) | ✅ Mostly |
+| Rust | Primitives, Arrays, `impl Copy` | `&T`, `&mut T`, `Box<T>`, `Arc<T>` | `async/await`, `tokio`, `Future`, `JoinHandle`, `Send + Sync` | ✅🔒 Safe and Explicit |
+
+## 9.1 Thread Safety
+
+Rust tracks pointers using `Send` and `Sync` traits:
+- `Send` means data can move across threads.
+- `Sync` means data can be referenced from multiple threads.
+
+> A pointer is thread-safe only if the data behind it is.
+
+| Pointer Type | Short Description | Send + Sync? | Main Use |
+|---------------- |--------------------------------------------------------------------------- |-------------------------------------- |------------ |
+| `&T` | Shared reference | Yes | Shared access |
+| `&mut T` | Exclusive mutable reference | No, not Send | Exclusive mutation |
+| `Box<T>` | Heap-allocated owning pointer | Yes, if T: Send + Sync | Heap allocation |
+| `Rc<T>` | Single-threaded ref counted pointer | No, neither | Multiple owners (single-thread) |
+| `Arc<T>` | Atomic ref counter pointer | Yes | Multiple owners (multi-thread) |
+| `Cell<T>` | Interior mutability for copy types | No, not Sync | Shared mutable, non-threaded |
+| `RefCell<T>` | Interior mutability (dynamic borrow checker) | No, not Sync | Shared mutable, non-threaded |
+| `Mutex<T>` | Thread-safe interior mutability with exclusive access | Yes | Shared mutable, threaded |
+| `RwLock<T>` | Thread-safe shared readonly access OR exclusive mutable access | Yes | Shared mutable, threaded |
+| `OnceCell<T>` | Single-thread one-time initialization container (interior mutability ONCE) | No, not Sync | Simple lazy value initialization |
+| `LazyCell<T>` | A lazy version of `OnceCell<T>` that calls function closure to initialize | No, not Sync | Complex lazy value initialization |
+| `OnceLock<T>` | Thread-safe version of `OnceCell<T>` | Yes | Multi-thread single init |
+| `LazyLock<T>` | Thread-safe version of `LazyCell<T>` | Yes | Multi-thread complex init |
+| `*const T/*mut T` | Raw Pointers | No, user must ensure safety manually | Raw memory / FFI |
+
+## 9.2 When to use pointers:
+
+### `&T` - Shared Borrow:
+
+Probably the most common type in a Rust code base, it is **Safe, with no mutation** and allows **multiple readers**.
+
+```rust
+let data: String = String::from_str("this a string").unwrap();
+
+print_len(&data);
+print_capacity(&data);
+print_bytes(&data);
+
+fn print_len(s: &str) {
+ println!("{}", s.len())
+}
+
+fn print_capacity(s: &String) {
+ println!("{}", s.capacity())
+}
+
+fn print_bytes(s: &String) {
+ println!("{:?}", s.as_bytes())
+}
+```
+### `&mut T` - Exclusive Borrow:
+
+Probably the most common *mutable* type in a Rust code base, it is **Safe, but only allows one mutable borrow at a time**.
+
+```rust
+let mut data: String = String::from_str("this a string").unwrap();
+mark_update(&mut data);
+
+fn mark_update(s: &mut String) {
+ s.push_str("_update");
+}
+```
+
+### [`Box<T>`](https://doc.rust-lang.org/std/boxed/struct.Box.html) - Heap Allocated
+
+Single-owner heap-allocated data, great for recursive types and large structs.
+
+```rust
+pub enum MySubBoxedEnum<T> {
+ Single(T),
+ Double(Box<MySubBoxedEnum<T>>, Box<MySubBoxedEnum<T>>),
+ Multi(Vec<T>), // Note that Vec is already a boxed value
+}
+```
+
+### [`Rc<T>`](https://doc.rust-lang.org/std/rc/struct.Rc.html) - Reference Counter (single-thread)
+
+You need multiple references to data in a single thread. Most common example is linked-list implementation.
+
+### [`Arc<T>`](https://doc.rust-lang.org/std/sync/struct.Arc.html) - Atomic Reference Counter (multi-thread)
+
+You need multiple references to data in multiple threads. Most common use cases is sharing readonly Vec across thread with `Arc<[T]>` and wrapping a `Mutex` so it can be easily shared across threads, `Arc<Mutex<T>>`.
+
+### [`RefCell<T>`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) - Runtime checked interior mutability
+
+Used when you need shared access and the ability to mutate date, borrow rules are enforced at runtime. **It may panic!**.
+
+```rust
+use std::cell::RefCell;
+let x = RefCell::new(42);
+*x.borrow_mut() += 1;
+
+assert_eq!(&*x.borrow(), 42, "Not meaning of life");
+```
+
+Panic example:
+```rust
+use std::cell::RefCell;
+let x = RefCell::new(42);
+
+let borrow = x.borrow();
+
+let mutable = x.borrow_mut();
+```
+
+### [`Cell<T>`](https://doc.rust-lang.org/std/cell/struct.Cell.html) - Copy-only interior mutability
+
+Somewhat the fast and safe version of `RefCell`, but it is limited to types that implement the `Copy` trait:
+
+```rust
+use std::cell::Cell;
+
+struct SomeStruct {
+ regular_field: u8,
+ special_field: Cell<u8>,
+}
+
+let my_struct = SomeStruct {
+ regular_field: 0,
+ special_field: Cell::new(1),
+};
+
+let new_value = 100;
+
+// ERROR: `my_struct` is immutable
+// my_struct.regular_field = new_value;
+
+// WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,
+// which can always be mutated with copy values
+my_struct.special_field.set(new_value);
+assert_eq!(my_struct.special_field.get(), new_value);
+```
+
+### [`Mutex<T>`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) - Thread-safe mutability
+
+An exclusive access pointer that allows a thread to read/write the data contained inside. It is usually wrapped in an `Arc` to allow shared access to the Mutex.
+
+### [`RwLock<T>`](https://doc.rust-lang.org/std/sync/struct.RwLock.html) - Thread-safe mutability
+
+Similar to a `Mutex`, but it allows multiple threads to read it OR a single thread to write. It is usually wrapped in an `Arc` to allow shared access to the RwLock.
+
+
+### [`*const T/*mut T`](https://doc.rust-lang.org/std/primitive.pointer.html) - Raw pointers
+
+Inherently **unsafe** and necessary for FFI. Rust makes their usage explicit to avoid accidental misuse and unwilling manual memory management.
+
+```rust
+let x = 5;
+let ptr = &x as *const i32;
+unsafe {
+ println!("PTR is {}", *ptr)
+}
+```
+
+### [`OnceCell`](https://doc.rust-lang.org/std/cell/struct.OnceCell.html) - Single-thread single initialization container
+
+Most useful when you need to share a configuration between multiple data structures.
+
+```rust
+use std::{cell::OnceCell, rc::Rc};
+
+#[derive(Debug, Default)]
+struct MyStruct {
+ distance: usize,
+ root: Option<Rc<OnceCell<MyStruct>>>,
+}
+
+fn main() {
+ let root = MyStruct::default();
+ let root_cell = Rc::new(OnceCell::new());
+ if let Err(previous) = root_cell.set(root) {
+ eprintln!("Previous Root {previous:?}");
+ }
+ let child_1 = MyStruct{
+ distance: 1,
+ root: Some(root_cell.clone())
+ };
+
+ let child_2 = MyStruct{
+ distance: 2,
+ root: Some(root_cell.clone())
+ };
+
+
+ println!("Child 1: {child_1:?}");
+ println!("Child 2: {child_2:?}");
+}
+```
+
+### [`LazyCell`](https://doc.rust-lang.org/std/cell/struct.LazyCell.html) - Lazy initialization of `OnceCell`
+
+Useful when the initialized data can be delayed to when it is actually being called.
+
+### [`OnceLock`](https://doc.rust-lang.org/std/sync/struct.OnceLock.html) - thread-safe `OnceCell`
+
+Useful when you need a `static` value.
+
+```rust
+use std::sync::OnceLock;
+
+static CELL: OnceLock<u32> = OnceLock::new();
+
+// `OnceLock` has not been written to yet.
+assert!(CELL.get().is_none());
+
+// Spawn a thread and write to `OnceLock`.
+std::thread::spawn(|| {
+ let value = CELL.get_or_init(|| 12345);
+ assert_eq!(value, &12345);
+})
+.join()
+.unwrap();
+
+// `OnceLock` now contains the value.
+assert_eq!(
+ CELL.get(),
+ Some(&12345),
+);
+```
+
+### [`LazyLock`](https://doc.rust-lang.org/std/sync/struct.LazyLock.html) - thread-safe `LazyCell`
+
+Similar to `OnceLock`, but the static value is a bit more complex to initialize.
+
+```rust
+use std::sync::LazyLock;
+
+static CONFIG: LazyLock<HashMap<&str, T>> = LazyLock::new(|| {
+ let data = read_config();
+ let mut config: HashMap<&str, T> = data.into();
+ config.insert("special_case", T::default());
+ config
+});
+
+let _ = &*CONFIG;
+```
+
+## References
+- [Mara Bos - Rust Atomics and Locks](https://marabos.nl/atomics/)
+- [Semicolon video on pointers](https://www.youtube.com/watch?v=Ag_6Q44PBNs)
diff --git a/.ai/ds-rules.md b/.ai/ds-rules.md
index 127a8ee2f1..63956ad729 100644
--- a/.ai/ds-rules.md
+++ b/.ai/ds-rules.md
@@ -49,6 +49,16 @@ Rules for UI code in Carbon. These are laws, not suggestions. Follow them when w
- ALWAYS use semantic status classes or component variants
- Prefer component props (`variant="destructive"`) over color classes
- Background colors: use card/surface components, not raw `bg-*` classes
+- NEVER use green/emerald **text** (`text-emerald-*`, `text-green-*`) OR
+ yellow/amber **text** (`text-yellow-*`, `text-amber-*`) as an inline status
+ indicator (e.g. a "Planned automatically" success note or a "low confidence"
+ caution note). Keep inline status understated (Vercel aesthetic): neutral
+ `text-muted-foreground`, with a `Lu*` icon (e.g. `LuCircleCheck`,
+ `LuTriangleAlert`) if affirmation/emphasis is needed, and let the wording
+ carry the meaning. This is about colored *prose*, not chips or icon glyphs —
+ `Status`/`Badge` status components (including `color="green"`/`"yellow"`),
+ status dots (`bg-green-500`), and severity **icon** colors are fine and
+ encouraged for status affordances.
## Typography Rules
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 3169318549..cc44d2a5c7 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -46,6 +46,31 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** All forms in `apps/erp/app/routes/`, `packages/form/`.
+## Features live inside existing permission modules
+
+**Context:** Building a new feature that belongs to an existing domain (e.g., assembly instructions within production).
+
+**Problem:** Creating a standalone module enum value / permission family (`Assembly` module with `assembly_*` permissions) for something that is really part of an existing domain. Assembly instructions belong to **production**, governed by `production_<view|create|update|delete>`.
+
+**Rule:** Don't invent a new module/permission family for a feature that fits an existing domain. Add a sub-link in the existing sidebar group (like Procedures) and a full-screen editor in its own route tree (`x+/assembly+/$id`, `handle.module: "production"`, mirroring `x+/procedure+/`). Pattern: list route under `x+/<module>+/<plural>.tsx`, full-screen editor in a sibling `x+/<singular>+/` tree whose `_layout.tsx` declares the parent module. Module folder = permission module = nav module.
+
+**Applies to:** New features under `apps/erp/app/routes/x+/`, `apps/erp/app/modules/`.
+
+## Assembly viewer camera + animation principles
+
+**Context:** Camera transitions and part-motion animation in the assembly instruction viewer (`packages/viewer`).
+
+**Problem:** Per-step re-zooming and pure-geometry view heuristics lose the "where are we on the model" context; small fasteners are invisible at assembly scale; sparse path sampling produced false "removable" results (washer/bolt ordering bugs).
+
+**Rule (user directives):**
+- **Constant zoom, rotate-only:** per-step camera transitions keep the standing whole-assembly distance and only rotate toward the action — never re-zoom per step or frame a single small part tightly.
+- **Occlusion-aware angles:** choose view direction by scoring how many parts block the line of sight to the animated part (seated pose + travel midpoint), not by pure geometry heuristics.
+- **Exaggerate small parts:** bolts/washers get display-only exaggerated travel (>=2.5x their size) so insertions read at assembly scale.
+- **Manual motion editing is a 0.001% escape hatch:** keep it collapsed behind "Edit manually"; motions come from the geometry planner.
+- **Planner correctness beats coverage:** cap sample spacing (2mm) rather than sample count. Threaded fasteners need a thread-depth penetration allowance along their own axis because CAD models them as interfering solid cylinders.
+
+**Applies to:** `packages/viewer/`, geometry planner (`services/geometry`).
+
## Posting-group-style matrices are a rejected pattern
**Context:** Designing multi-jurisdiction tax determination; the spec anchored on the customerType × itemPostingGroup posting-group matrix as "Carbon precedent."
@@ -86,6 +111,114 @@ Format: `Context → Problem → Rule → Applies to`
**Applies to:** `packages/database/supabase/migrations/` touching `account`; `packages/database/supabase/functions/lib/seed.data.ts`; anything walking the chart-of-accounts tree.
+## Never fabricate a "best-effort" motion through geometry
+
+**Context:** The assembly motion planner (`services/geometry/app/plan.py`) had a tier-4 "forced removal" that gave unsolvable parts a straight-line motion through whatever blocked them, so every part animated. On the seat-rail assembly 6/30 parts got 48–647mm fly-through motions early in the sequence — the whole animation read as wrecked.
+
+**Problem:** A fabricated path is worse than no path: it renders as a collision, erodes trust in every other step, and hides the real geometric finding (interlocked unit, embedded solid, missing mate exemption) behind a fake answer.
+
+**Rule:** When a solver can't prove a result, emit an explicit flagged state (`motion: "none"` + `blockedBy` + warning) and give the UI a degraded-but-honest rendering (fade-in at the seated pose). Never ship a fabricated approximation of a geometric/physical claim. Same for display fallbacks: an AABB "least-blocked direction" guess may only be used where it's labeled as a guess, never silently for planner output.
+
+**Applies to:** `services/geometry/app/plan.py`, `packages/viewer` (fallback.ts, AssemblyPlayer), `generateAssemblyStepsFromPlan`.
+
+## Penetration tolerances must stay far below sample spacing
+
+**Context:** The planner allowed 1.5mm "thread depth" penetration along a fastener's axis versus ALL parts, with collision samples every 2.0mm, to make solid-thread models removable through their nuts.
+
+**Problem:** Tolerance ≈ spacing means a thin blocker (1mm washer, flange, cover) can pass between samples entirely below the allowance — the part "removes" through solid metal, which scrambles the greedy disassembly order downstream. A blanket allowance also applies to parts that have nothing to do with the threads.
+
+**Rule:** Scope allowances to the specific mating pair that justifies them (fastener ↔ its detected threaded mate, capped at the seated interference + margin), keep the global tolerance an order of magnitude below sample spacing, and locally refine sampling near any contact that approaches the tolerance.
+
+**Applies to:** `services/geometry/app/plan.py` collision sampling; any sampled sweep/clearance check.
+
+## trimesh CollisionManager rebuilds BVHs on every single-object query
+
+**Context:** Re-planning the 31-part seat rail took ~2 hours; the old planner took ~59s. `manager.in_collision_single(mesh, transform)` builds a fresh FCL BVH for the queried mesh on EVERY call, and the greedy loop also removed/re-added parts per attempt (another BVH rebuild each).
+
+**Rule:** For sampled sweeps, cache the FCL BVH per mesh (`mesh_to_BVH` once, `fcl.CollisionObject` per query) and collide against `manager._manager` directly; never remove/re-add a manager object to "exclude" it — filter its contacts by name with an infinite allowance instead. Bound sampling by the AABB separation distance (beyond it, disjointness is provable).
+
+**Applies to:** `services/geometry/app/plan.py` (`_contacts_at`, `_self_exempt`), any trimesh/fcl sampling loop.
+
+## Don't pre-sign a short-lived upload URL before a long-running operation
+
+**Context:** `assembly-plan` pre-signed a `createSignedUploadUrl` for `plan.json`, then called the geometry `/plan` service which ran the motion planner (~3 min) and finally PUT the result to that URL. Uploads 400'd and the job stuck in `Processing` forever; the ERP UI polled "Solving motions…" indefinitely.
+
+**Problem:** Supabase `createSignedUploadUrl` mints a **60-second** token and the SDK gives no way to extend it (it only honors `{ upsert }`; the TTL is a storage-server setting). By the time a multi-minute planner finished, the token had expired → `400 InvalidJWT "exp claim timestamp check failed"` → the service returned 502. The fast `/convert` path (~16s) never tripped it, so the pattern looked fine. Re-runs/"already exists" are a red herring — an upsert PUT to an existing object returns 200.
+
+**Rule:** A pre-signed **upload** URL must be consumed within ~60s of minting. For any operation that can outlast that, don't hand the worker a pre-signed PUT URL — have the service **return the artifact inline** and let the worker persist it with the service-role client the moment it has the bytes (no token, no expiry). Also bound the outbound `fetch` with `AbortSignal.timeout(...)` so a hung service fails cleanly (→ `onFailure` marks the row Failed) instead of pinning it in `Processing`.
+
+**Applies to:** `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts`, `services/geometry/app/main.py` (`/plan`); any Inngest task that pre-signs storage upload URLs before a slow external call.
+
+## Direct psql DDL needs a PostgREST schema-cache reload
+
+**Context:** Applied an unshipped migration's delta (drop `assemblyGroup`, create `assemblyUnit`) to the local DB with `psql` instead of `crbn migrate`, to avoid a full rebuild. The ERP page then hung: the `$id` loader's `Promise.all` timed out (`fetchWithRetry` TimeoutError) even on queries against unrelated tables.
+
+**Problem:** PostgREST caches the DB schema. `crbn migrate` / `db:migrate` reload it after applying migrations; a raw `psql` DDL does not. With a stale cache, queries against the changed tables can't resolve and hang, which exhausts the connection pool and times out *other* queries too. (Confirmed after: `assemblyGroup` returned PGRST205 "Could not find the table in the schema cache".)
+
+**Rule:** After any direct-psql schema change to a local Supabase DB, reload PostgREST — `psql -c "NOTIFY pgrst, 'reload schema';"` (or `docker restart <...>-postgrest-1`). Prefer `crbn migrate` when possible; when patching by hand (e.g. editing an unshipped migration in place), the reload is a required follow-up.
+
+**Applies to:** any local schema change applied outside `crbn migrate`; symptom is loader/REST timeouts after a DDL patch.
+
+## Synthetic box meshes fake huge penetration under sustained sliding contact
+
+**Context:** Writing planner ordering tests (`test_part_with_blocked_insertion_is_not_demoted`) with raw `trimesh.creation.box` parts: a slider seated 0.05mm into a channel floor read as depth **29.8mm** against the rail at every sweep sample, so the planner declared it inseparable and rigid-merged it.
+
+**Problem:** FCL reports per-triangle-pair local penetration. A box face is two giant triangles; two near-coplanar giant triangles overlapping 0.05mm in the normal direction report a depth spanning their tangential overlap. Real STEP models never hit this — tessellation at `linearDeflection` keeps triangles small, so local depths stay bounded by element scale. The artifact only appears in synthetic tests whose parts sustain face-on-face sliding contact; brief seated contact that separates immediately (stacked boxes lifting off) is fine.
+
+**Rule:** In planner tests, any part that must SLIDE while touching another needs `mesh.subdivide_to_size(5.0)` on both meshes — and prefer seating the moving part against a face perpendicular to its travel (contact vanishes on the first sample) over a face parallel to it (contact persists the whole sweep). Also avoid geometry where a seated bite must scrape past an opening sill: that is a real interference, not an artifact.
+
+**Applies to:** `services/geometry/tests/test_plan.py` synthetic fixtures; debugging any "cannot separate / planned as one rigid unit" result on hand-built trimesh geometry.
+
+## Ordering heuristics must be gated on a large noisy model, not just the seat rail
+
+**Context:** The weakly-secured-last + sandwich-gasket refactor validated green on 47 unit tests and a byte-identical 31-part seat-rail baseline, then made real planning slower with worse results. A 20-line classification probe on the 118-part SA Mando & Battery Harness immediately showed why: 4 sandwich detections — ALL false positives, including a 33mm "thin" part (ratio-only thinness cap) and two 10.4mm isotropic pass-through allowances (uncapped observed depth granted as "compliant squish").
+
+**Problem:** The seat rail is a best-case model: named fasteners, clean contacts, no ambiguous plate stacks. Proxy signals calibrated there (name-only fastener detection, contact counts, thinness ratios) explode on models with unnamed hardware, clearance fits, and interpenetrating CAD. Two failure classes: (1) a *preference* wired into the greedy removal priority is not a preference — that ranking schedules expensive removal attempts and picks flag/merge victims, so fronting hard-to-remove parts multiplies failed sweeps (slower); (2) any heuristic that grants collision allowances fails open — one false positive corrupts collision truth for every sweep it touches (worse).
+
+**Rule:** Before shipping a planner ordering/allowance heuristic: (a) run the classification-only probe (`.ai/scratch/geometry-probe.py`) on a large noisy model (harness/BCU class) and eyeball every cohort member and every allowance value — a 10mm "squish" is a bug, not a gasket; (b) keep display preferences in the topo sort only, never in `removal_priority`; (c) cap and axis-gate anything that relaxes collision tolerance, and prefer fail-closed (reject classification) over fail-open (grant allowance) when evidence is out of range.
+
+**Applies to:** `services/geometry/app/plan.py` ordering preferences, `_sandwiched_parts`-style classifiers, any future exempt/allowance mechanism.
+
+## Profile the planner before optimizing — the flood was pass-through, not self-collision
+
+**Context:** Motion planning took ~3 min (seat rail) / >30 min (harness). A micro-benchmark showed a 2,000× per-sample cost for a part colliding with its own seated copy (it stays registered in the manager), so the "obvious" fix was to unregister the moving part during its own sweeps. Implemented, byte-identical output — and **zero real-model speedup** (191→211s). cProfile told the truth: 86% of total time was `_contacts_at` under `_path_blockers`, dominated by **pass-through enumeration** — sweeping a part THROUGH its blockers enumerates the blocker's full triangle-contact set (53M contact objects on a 31-part model) at every sample for the whole travel, when all `_path_blockers` needs is each blocker's identity, discovered once.
+
+**Problem:** Micro-benchmarks measure the mechanism you built them around, not the workload. Self-collision flooding is real but self-overlap ends early in most sweeps; deep pass-throughs persist for hundreds of samples and were the actual cost. The two look identical from the outside (both are "too many contacts").
+
+**Rule:** For planner performance work, cProfile the real model FIRST (`cProfile.run('plan_step(...)')` — 30s of setup) and read cumtime by caller before choosing a lever. The winning fix: in `_path_blockers`, once a partner is recorded as a blocker, unregister it from the broadphase for the remainder of the sweep and re-register before returning (`registerObject`/`unregisterObject` on the SAME CollisionObject rebuilds nothing — the BVH lives on the geometry). Seat rail 191–211s → 20–26s (8×), harness >30min → 9.5min, byte-identical sequences. Keep the self-unregister too (it's what makes the synthetic test suite 8× faster), but don't mistake it for the fix.
+
+**Applies to:** `services/geometry/app/plan.py` sweep functions (`_path_blockers`, `_contacts_at`, `_unregistered`); any future "collect all X along a path" collision query.
+
+## Verify what actually rendered before root-causing a "bad motion" report
+
+**Context:** A user reported step 4's screw+washer "colliding through the 3D MARKETING and seat rail clamp" and asked for a motion-planning refactor. A trimesh/FCL sweep of the STORED motion against the real GLB meshes showed it was collision-free against the entire model — and the only geometrically feasible insertion (the reverse sense jams the washer into the clamp bore by 3.4mm). The visible garbage came from elsewhere: a re-motion job was still running, so steps played stale/"none" motions through the collision-blind AABB display fallback, on top of 26 never-installed components being rendered solid.
+
+**Problem:** A "the animation collides" report conflates at least four layers: the stored plan motion, the display-time fallback synthesis (`displayMotionForStep` → `synthesizeFallbackMotion`), display adjustments (`exaggerateMotion`), and the visibility model (what else is on canvas). Root-causing the planner first is attacking the strongest layer — the geometry service's motion had `verified: true` and meant it.
+
+**Rule:** Before touching planner code for a visual-collision report: (1) check `assemblyPlanJob.status` — Queued/Processing means the user watched placeholder motions; (2) dump the step's stored `motion` from `assemblyInstructionStep` and sweep it against the GLB with trimesh (`services/geometry/.venv` has everything; storage files live in the storage container under `/var/lib/storage/stub/stub/<bucket>/...`); (3) only if the stored motion itself collides is it a planner problem — otherwise it's fallback/visibility/display-layer work in `packages/viewer`.
+
+**Applies to:** assembly-instruction motion bug reports; `packages/viewer/src/{motion,fallback,AssemblyPlayer}`; `services/geometry/app/plan.py`.
+
+## GLB node↔nodeId joins must be validated against graph.json bboxes
+
+**Context:** Building BCU acceptance fixtures from the viewer GLB: nodeIds live in glTF node `extras` which trimesh drops, so the join went through world-transform matching. The geometry service bakes vertices in world space with identity node transforms — every node "matched" position (0,0,0) and the assignment silently scrambled 431 parts. The resulting degree/volume table looked plausible ("Seal Electronics Box, degree 19, 742cm³") and drove two wrong fix iterations before the graph.json bboxes exposed it.
+
+**Problem:** A shuffled mesh↔name assignment still produces plausible-looking planner output — garbage in, plausible garbage out. Name-prefix or transform heuristics have no error signal of their own.
+
+**Rule:** When joining GLB scene nodes to graph.json nodeIds, match on world BBOX against graph.json's per-leaf bbox (authoritative, written by the same converter) and assert coverage (all nodes matched, max error < 1mm) before trusting any downstream analysis. `/tmp`-fixture recipe: parse the GLB JSON chunk for extras + walk scenes for world matrices, then bbox-match to trimesh geometry.
+
+**Applies to:** acceptance/repro scripts over viewer GLBs; any offline analysis pairing `graph.json` with `model.glb`.
+
+## Name-only fastener classification: "pin" and spec suffixes mark structure as hardware
+
+**Context:** The SA BCU's enclosure is named "Electronics Box - 36 Pin" (a connector pin COUNT). The fastener name regex matched `\bpin\b`, classifying the box as hardware: removal priority fronted it (fasteners first → expensive failed sweeps → flagged early), base candidacy excluded it, and the assembly sequence anchored on a gasket. One word in a part name inverted the entire build order.
+
+**Problem:** Fastener detection is name-only; real CAD names carry fastener-ish tokens in structural parts (pin counts, "M8 slot pattern" spec suffixes). A false positive is fail-open: it changes scheduling, exemptions, and base selection everywhere at once.
+
+**Rule:** Never classify on ambiguous single tokens — "pin" is out (dowel pins still match via "dowel"). Back the name test with physical sanity in `_classify_fasteners`: a name-matched part spanning more than `max(100mm, 0.35 × assembly diagonal)` keeps its structural role. When ordering goes absurd on a new model, print the `fasteners` cohort first — one misclassified structural part explains a scrambled sequence.
+
+**Applies to:** `services/geometry/app/plan.py` (`FASTENER_NAME_RE`, `_classify_fasteners`, `removal_priority`, `_reselect_base`); future classification heuristics.
+
## Client-side entity caches must be company-keyed in a multi-tenant app
**Context:** A prod company export failed its closure guard: a `salesOrder` (and its `opportunity`) in one company referenced another company's customer. Root cause chain: `RealtimeDataProvider` (ERP + MES) cached the customer/item/supplier/people lists in IndexedDB under **global** keys (`"customers"`), and company switching is a client-side navigation — so after a switch, the previous company's cached list could hydrate the pickers before the properly-scoped server fetch landed. Nothing downstream caught the bad pick: zod validated `customerId` as a bare string, services inserted it blindly, RLS only checks the row's own `companyId`, and the FK was single-column (`customerId → customer(id)`).
diff --git a/.ai/plans/2026-07-04-animated-work-instructions.md b/.ai/plans/2026-07-04-animated-work-instructions.md
new file mode 100644
index 0000000000..07d4d7dc0c
--- /dev/null
+++ b/.ai/plans/2026-07-04-animated-work-instructions.md
@@ -0,0 +1,225 @@
+# Animated Work Instructions — Implementation Plan
+
+Spec: `.ai/specs/2026-07-04-animated-work-instructions-design.md`
+Research: `.ai/research/animated-work-instructions.md`
+Conventions: `.ai/rules/conventions-database.md`, `conventions-services.md`,
+`conventions-forms.md`, `conventions-ui.md`
+
+Working name for the module: **assembly**.
+
+---
+
+## Phase 0 — Foundations (assembly-aware viewer + manual animated instructions)
+
+Goal: STEP upload → server-converted GLB with assembly hierarchy → new AssemblyPlayer
+component → manually authored animated steps, playable in ERP and MES. No planner yet.
+This phase is shippable on its own and de-risks the whole stack.
+
+### 0.1 Geometry service skeleton
+**Files:** create `services/geometry/` (Dockerfile, `pyproject.toml`, FastAPI app)
+1. FastAPI app with `/health`, `/convert` (accepts signed source URL + signed PUT URLs
+ for artifacts, plus options: deflection, units), API-key auth via shared secret env.
+2. Dependencies: `cadquery-ocp` (OCCT), `trimesh`, `pygltflib`; pin versions.
+3. Local dev: docker-compose entry; document `npm run dev` interplay in README.
+4. Commit.
+
+### 0.2 STEP → GLB + graph.json conversion
+**Files:** `services/geometry/app/convert.py`, tests with 2–3 sample STEP fixtures
+1. `STEPCAFControl_Reader` → XCAF doc → walk assembly tree: per-node name, local
+ transform, product vs instance, color.
+2. `BRepMesh_IncrementalMesh` (configurable deflection) → `RWGltf_CafWriter` GLB.
+3. Generate stable node IDs: `hash(geometryHash + parentPath + siblingOrdinal)`; write
+ into glTF node `extras` (post-pass with pygltflib) and into `graph.json` (tree,
+ transforms, bboxes, volume, unit).
+4. Unit-normalize to mm; record source unit.
+5. Pytest over fixtures: node count, ID stability across two runs, GLB loads in
+ three.js (validate with `gltf-validator` in CI).
+6. Commit.
+
+### 0.3 Meshopt compression pass
+**Files:** `services/geometry/app/optimize.py` (or Node sidecar step in the Inngest fn
+using `@gltf-transform/cli`)
+1. Apply quantize + `EXT_meshopt_compression`; preserve node extras.
+2. Verify size reduction and round-trip of extras in test.
+3. Commit.
+
+### 0.4 Database migration: processing columns + plan job table
+**Files:** `packages/database/supabase/migrations/<ts>_assembly-foundations.sql`
+1. Follow `.ai/rules/conventions-database.md`. Alter `modelUpload`: add `processingStatus`,
+ `processingError`, `glbPath`, `graphPath`, `partCount`, `processedAt`.
+2. Create `assemblyPlanJob` per spec (kind: 'convert' now, 'plan' later) with RLS.
+3. `npm run db:build`; commit.
+
+### 0.5 Inngest convert pipeline
+**Files:** `packages/jobs/src/inngest/tasks/assembly-convert.ts`, event in
+`packages/jobs/src/events.ts`
+1. Event `assembly/model.process` {modelUploadId, companyId, userId}.
+2. Function: mark queued → create signed URLs → POST geometry `/convert` → poll/await →
+ update `modelUpload` + `assemblyPlanJob` → emit `assembly/model.processed`.
+3. Failure path writes `processingError`; retries per existing Inngest patterns (mirror
+ `model-thumbnail.ts`).
+4. Trigger from the existing model upload path for `.step/.stp` files (find the upload
+ action that writes `modelUpload`).
+5. Commit.
+
+### 0.6 packages/viewer: AssemblyPlayer
+**Files:** create `packages/viewer/` (package.json, tsup config) with
+`AssemblyViewer.tsx`, `AssemblyPlayer.tsx`, `useAssembly.ts`, `motion.ts`
+1. Deps: `three` (catalog), `@react-three/fiber`, `@react-three/drei`,
+ `three-stdlib` meshopt decoder. No imports from apps.
+2. `useAssembly(glbUrl, graphUrl)`: loads GLB, indexes nodes by stable ID, exposes
+ tree + setters (highlight, ghost/wireframe, hide, transform offset).
+3. `motion.ts`: build three.js KeyframeTracks from step motion JSON
+ ({linear|L|helix|path}); reverse for insertion playback; per-step clip cache.
+4. `AssemblyPlayer`: props = {glbUrl, graphUrl, steps, activeStepIndex,
+ onStepChange, readOnly}; renders canvas, step scrubber, play/pause, part
+ highlight for active step, prior parts solid / future parts hidden or ghosted.
+5. Storybook-style demo route or vite playground inside the package for development.
+6. Commit.
+
+### 0.7 Instruction schema migration
+**Files:** `packages/database/supabase/migrations/<ts>_assembly-instructions.sql`
+1. `assemblyInstruction`, `assemblyInstructionStep` per spec (fractional `sortOrder`,
+ JSONB motion/camera/fastener/warnings, `partNodeIds TEXT[]`,
+ `planConfidence`), RLS, indexes on (companyId, modelUploadId) and
+ (assemblyInstructionId, sortOrder).
+2. Nullable `assemblyInstructionId` FK on `jobOperation` and `methodOperationStep`.
+3. New `assembly` module permissions wired like existing modules (check how `quality`
+ or similar module registers permissions).
+4. `npm run db:build`; commit.
+
+### 0.8 Assembly module: models + service
+**Files:** `apps/erp/app/modules/assembly/assembly.models.ts`, `assembly.service.ts`
+1. Zod validators (instruction, step upsert with motion JSON schema) per
+ `.ai/rules/conventions-forms.md`; service CRUD per `conventions-services.md` (Kysely transaction for
+ bulk step writes/reorder — see `database-transactions` skill notes).
+2. Commit.
+
+### 0.9 ERP routes: instruction editor (manual authoring MVP)
+**Files:** `apps/erp/app/routes/x+/assembly+/` (list, `$id.tsx` editor), path entries
+in `apps/erp/app/utils/path.ts`
+1. List route: instructions table (status, item, model, updated).
+2. Editor route: three-pane layout — step list (drag reorder via fractional sortOrder),
+ AssemblyPlayer center, step detail form right (title, text, partNodeIds via
+ click-to-select in viewer, motion editor: direction gizmo + distance, helix params).
+3. "New instruction from model" action on item Model tab when
+ `processingStatus = success`.
+4. `requirePermissions` with `assembly` module throughout.
+5. Commit.
+
+### 0.10 MES playback (read-only)
+**Files:** `apps/mes/app/routes/x+/operation.$operationId.tsx` (+ JobOperation
+component)
+1. If linked instruction exists, render AssemblyPlayer (readOnly) in/next to the Model
+ tab; step next/prev controls sized for gloved touch.
+2. Commit.
+
+### 0.11 Phase 0 verification
+1. `/login` + `/test`: upload a multi-part STEP fixture, watch convert succeed, author
+ 3 manual steps, play in editor, link to a job operation, view in MES.
+2. Record findings; fix; commit.
+
+---
+
+## Phase 1 — Auto-draft (the planner)
+
+Goal: "Generate instructions" produces a complete draft: fastener groups, sequence,
+motions, text.
+
+### 1.1 Contact/blocking graph
+`services/geometry/app/contacts.py`: trimesh-based proximity/contact pairs (distance <
+ε), per-pair contact normals + blocked direction cones; persisted into graph.json.
+Tests on fixtures (stacked plates, pin-in-hole).
+
+### 1.2 Fastener classification
+`services/geometry/app/fasteners.py`:
+1. Name regex table (ISO/DIN/ANSI/McMaster patterns) over node names.
+2. Geometry heuristic: small bbox, ≥80% lateral surface from coaxial cylinders (OCCT
+ face typing), hex/socket head detection; duplicate clustering by geometry hash.
+3. Axis + insertion direction from coaxial hole in contacting part; emit fastener
+ groups {spec?, count, axis, targetNodeIds}.
+4. Tests: fixture with named + unnamed screws; false-positive guard (dowel pins
+ classified as pins not screws is acceptable Phase 1).
+
+### 1.3 Greedy disassembly sequencer
+`services/geometry/app/sequence.py`:
+1. Candidate directions per part: ±XYZ, principal axes, hole/fastener axes.
+2. Removability: sample path (~100 poses × clearance ε) collision checks
+ (trimesh.CollisionManager); fasteners removed first per group (analytic helix +
+ retract).
+3. Greedy loop respecting XCAF subassembly boundaries; tie-break: top-down, outside-in,
+ small-parts-last reversed to small-parts-first on assembly.
+4. Tier-4 "L" motions (lift-then-slide two-segment search) for failures.
+5. Unresolved parts → manual steps with reason codes.
+6. Output plan.json: ordered steps {partNodeIds, motion, confidence, warnings}.
+7. Budget caps + structured timing stats. Tests on 3 fixtures incl. one designed
+ failure.
+
+### 1.4 `/plan` endpoint + Inngest wiring
+1. `/plan` on geometry service (inputs: graph.json + GLB or mesh cache; output:
+ plan.json to signed URL).
+2. Inngest `assembly-plan.ts`: chain after convert when user requests generation;
+ `assemblyPlanJob` kind 'plan'; on success, transactional draft creation:
+ `assemblyInstruction` + steps from plan.json (motion, partNodeIds, fastener,
+ warnings, confidence).
+
+### 1.5 Step text generation
+`packages/jobs/src/inngest/tasks/assembly-step-text.ts`: structured facts → existing AI
+infra (small prompt, batch) with deterministic template fallback ("Install 4× M5 SHCS
+into mounting plate (8 N·m)"). Editor regenerate button per step.
+
+### 1.6 Editor: draft triage UX
+Confidence filter (low-confidence/manual-needed queue), accept/fix flows, re-plan
+button (re-runs planner preserving user-edited steps by partNodeIds match).
+
+### 1.7 Phase 1 verification
+End-to-end on 3 real assemblies (find public STEP assemblies: gearbox, vise, enclosure)
+— measure: % steps auto-accepted, planner wall time. Target: >70% steps accepted
+unedited, <5 min for ≤200 parts.
+
+---
+
+## Phase 2 — Editor depth + MES execution
+
+- 2.1 Subassembly grouping UI (parentStepId tree; collapse groups into single steps).
+- 2.2 Exploded view generation (offsets along removal directions; explode slider in
+ player; per-step explode JSON).
+- 2.3 Auto-camera: offscreen ID-buffer scoring of ~26 candidate views per step in the
+ geometry service or client; temporal smoothness penalty; stored in step camera JSON.
+- 2.4 Stability gate: pybullet drop-test per reversed step → hold/fixture warnings
+ surfaced as step callouts.
+- 2.5 MES execution: step-complete events, per-step durations on jobOperation, parts/
+ fastener pick callouts; gloved-touch UI polish.
+- 2.6 `share+` public player route (signed, revocable) — the standalone wedge.
+- 2.7 Tool/torque libraries: link `methodOperationTool`/resources; torque field on
+ fastener JSON surfaced in player.
+
+## Phase 3 — Moats
+
+- 3.1 Revision propagation: graph diff (name + geometry hash + position matching),
+ step remap, "needs review" flags, instruction version bump flow.
+- 3.2 Physics escalation tier (Assemble-Them-All-style force-guided search, MIT code as
+ reference; budget-capped, behind a flag).
+- 3.3 Onshape: pull mates + native glTF for connected tenants; mate axes feed the
+ sequencer.
+- 3.4 APS Model Derivative fallback for native formats (SLDASM/NX/CATIA) using existing
+ AutodeskViewer/urn plumbing.
+- 3.5 Operator feedback loop: `assemblyInstructionFeedback` from MES → editor inbox.
+- 3.6 PDF/static export via `packages/documents` (per-step rendered frames).
+- 3.7 FTO review (US 11,813,756; US 9,053,258; US 7,295,201) before GA marketing.
+
+## Risks / open questions
+
+1. **OCCT learning curve + dirty CAD** — mitigate with per-part failure isolation and
+ a fixture corpus collected from real customer files early.
+2. **Planner quality on real assemblies** is the product risk; Phase 1.7 metrics gate
+ further investment in tiers vs. editor ergonomics.
+3. **ECS sizing/cost** for geometry workers (CPU/mem heavy, bursty) — start with one
+ modest service + queue depth alarm; Modal/Fly escape hatch documented.
+4. **Single new language in the monorepo** (Python service) — CI, lint, deploy
+ pipelines need an owner; keep the service API tiny.
+5. **Naming**: "assembly" module vs. product name (decide before routes ship).
+
+## Review
+
+(to be filled in during execution)
diff --git a/.ai/plans/2026-07-05-assembly-planner-v3.md b/.ai/plans/2026-07-05-assembly-planner-v3.md
new file mode 100644
index 0000000000..bdb88bbbb1
--- /dev/null
+++ b/.ai/plans/2026-07-05-assembly-planner-v3.md
@@ -0,0 +1,300 @@
+# Assembly Planner v3 — Reason From Contact Geometry, Not Axis Lists
+
+Status: in progress
+Supersedes the earlier assembly-through-disassembly refactor plan (deleted).
+Everything that plan shipped stands: flagged-fade-in viewer semantics,
+precedence DAG + forward verification, rigid merge, subassembly groups,
+joint edges, structural scoring, the BVH-cache perf pass, and step
+generation v2 with Regenerate. v3 fixes what the real model exposed.
+
+## Ground truth to reason against
+
+Expected seat-rail order (from Brad), abstracted to its causal skeleton:
+
+```
+rail → the skeleton
+slider, slider → corridor riders: must travel the rail while it's empty
+part 7 → mounted component, placed before it is fastened
+torx ×4 → its fasteners, entering THROUGH the holes (tilted bore axes)
+knob ×3 → adjusters: thread in, clamp nothing → after the structure
+marketing badge → cosmetic, shallow attachment
+washer, screw → the badge/clamp's fastener stack, washer first, screw last
+```
+
+Nothing here is seat-rail-specific. The generating principles:
+
+1. Skeleton first (big, central).
+2. A part whose insertion sweeps a long corridor goes while the corridor is
+ empty (hard: precedence edges; soft: do it early even when not forced).
+3. A mounted component precedes its fasteners; its securing fasteners follow
+ it immediately, entering along their bore axes through the holes.
+4. Mate-only fasteners (knobs, set screws) are accessories — ordinary small
+ structure, no priority jump.
+5. Cosmetics late; their own fastener stacks (washer → screw) come right
+ after them, last.
+
+P6 already encodes 1, 3(ordering), 4, 5. The seat-rail run exposes what's
+still wrong underneath.
+
+## Evidence from the latest run (52.7s local, all P6 changes active)
+
+```
+tiers={linear:19, group:2, flagged:6} verified=24/30
+flagged: Torx M6 ×4, Part 7, clamping knob #1
+sequence: rail, [badge+clamp group], knob, Part7(flagged), [screw+washer g],
+ knob(flagged), slider, torx(flagged)×2, slider, torx(flagged)×2,
+ HRKN ×16 …
+```
+
+Three distinct root causes, none of them "needs more heuristics":
+
+**RC1 — The Torx bolts have no discoverable axis, so they never get the
+hole path.** The assembly plane is tilted (sliders travel [0.34, 0, 0.94]).
+The Torx bore axes are tilted too. A stubby flange-head bolt defeats the SVD
+axis (near-cubic), defeats the bbox axis (a tilted bolt's AABB is a diagonal
+cube), and — if its tapped hole is modeled at clearance — has no deep thread
+contacts for the contact-ring fit. Result: candidate directions collapse to
+the six world axes, and a tilted bore can never be exited along a world
+axis. Flagged. Part 7 then deadlocks behind its own unresolvable bolts.
+The information that WAS available and unused: the bolt's seated surface
+contacts (the flange's under-head ring on Part 7) — a planar ring whose
+normal IS the bore axis, at any contact depth including zero.
+
+**RC2 — Travel semantics are "exit the assembly AABB", which is wrong for
+parts that point inward.** The cheese screw's bore points into the assembly;
+AABB-exit along its axis is 606mm (the 1.5×diagonal cap). Real removal is
+"back out of the hole into free space" (~20–30mm). Consequences compound:
+absurd travels read badly, they sweep across the whole model creating
+spurious precedence edges, they waste collision samples, and the 606mm
+"travel" made a fastener group look like a corridor-sweeper and jump to
+step 6.
+
+**RC3 — Greedy takes the FIRST clear direction, not the LEAST-ENTANGLING
+one.** The badge+clamp group went +Z at greedy time; if that sweep crosses
+where a slider seats, it manufactures `group ≺ slider` and drags the whole
+clamp stack to step 2. When several directions are collision-free at
+disassembly time, the choice among them decides the constraint graph — and
+we currently don't choose, we take the first hit.
+
+Plus the pipeline gap: **the app never runs the new planner.** Generate
+Steps consumes the STORED plan.json; the geometry service container still
+runs the old code. Every in-app impression so far is of the v1 planner.
+
+## Redesign
+
+### D1. Candidate directions come from contact geometry (fixes RC1)
+
+Collect, in the one seated broadphase pass we already do, per part: contact
+points AND contact normals with every neighbor (any depth — surface touches
+included; fcl contacts carry normals).
+
+Axis/direction discovery becomes a cascade over evidence, strongest first:
+
+1. Thread-mate contact band (exists) — cylinder fit.
+2. **All-contact ring/normal fit (new):** fit the cylinder/ring axis over
+ the part's full seated contact cloud; for a flange bolt in a clearance
+ hole this is the under-head ring → bore axis, tilted or not.
+3. **Contact-normal clusters (new, all parts, not just fasteners):** dedup
+ contact normals (dot > 0.95), take the top 2–3 clusters by support, add
+ ± as candidate directions after the symmetry axis and before world axes.
+ A box on a plate offers +Z; a dovetailed slider offers the rail
+ direction; a tilted bolt offers its bore axis. This is "ask the mating
+ surfaces how the part comes apart" — the general form of every special
+ case we've hand-coded.
+4. World axes last, as today.
+
+Named fasteners stay bore-axis-restricted (now with a real axis to
+restrict to), sense ordered away-from-mate (exists).
+
+### D2. Travel = reach free space, not exit the world (fixes RC2)
+
+Redefine removal travel: sample along the direction (bounded by AABB
+separation as today, so clearance of the tail is still proven), record the
+LAST touching sample; travel = last_contact + margin + one part-extent for
+readability. The remaining path to separation must still verify clear —
+semantics unchanged for soundness, only the recorded animation distance and
+the swept-edge footprint shrink. Fastener insertions become hole-length
+travels; precedence edges stop being manufactured by phantom cross-assembly
+sweeps; the corridor-exposure signal becomes honest (a 250mm slider ride is
+a corridor; a 25mm screw backing out is not).
+
+### D3. Direction choice minimizes entanglement (fixes RC3)
+
+When more than one direction is collision-free at greedy time, score each
+CLEAR candidate by its blocker count against the FULL seated assembly (the
+sweep we already run for the DAG, just earlier) and pick
+(fewest-full-set-blockers, shortest travel). The bolt "takes the path
+through the holes" because the hole path has zero full-set blockers; the
+clamp group stops choosing a direction that flies over the slider seat.
+Bounded cost: ≤ a handful of extra sweeps per part, only when several
+directions clear, and D2 just made sweeps short.
+
+### D4. Ordering polish (small, after D1–D3)
+
+- Corridor/exposure bucket applies to structure only — never fastener or
+ fastener-group units (their place comes from joint edges + securing
+ class).
+- Group units inherit fastener-ness when any member is a fastener (the
+ washer+screw pair is a fastener stack, not a corridor part).
+- Everything else in P6 stands: joint edges, securing-vs-accessory,
+ structural key, runs, base.
+
+### D5. Close the app loop (fixes "nothing changed")
+
+- Rebuild/restart the local geometry service with the new code and confirm
+ the running container's plan.py matches the working tree (how it mounts
+ is task 1 — verify, don't assume).
+- Add "Re-run motion planning" to the assembly editor (triggers the
+ assembly-plan job; the poll/refresh UX from the lazy-conversion work
+ already handles the wait), so a stale plan.json is a one-click refresh —
+ today the only path is deleting artifacts or the retry-on-failure button.
+- Then: re-plan → Regenerate from Plan → watch in the browser.
+
+## Experiment protocol (the scratch loop)
+
+Harness: extend `/tmp/replan.py` into `services/geometry/scratch/explain.py`
+(gitignored or scratch — throwaway):
+
+- `--explain "<name substr>"`: for each matching part, print classification
+ (which cascade stage produced the axis), mates, joint set, every candidate
+ direction tried with its first blocker and depth, and the chosen motion.
+- `--sequence`: the final order annotated with tier/travel/verified plus,
+ per unit, WHICH preference class placed it (base / run / securing /
+ corridor / structural) — makes ordering disputes decidable in one read.
+- Fast loop: tessellation is cached after the first run (~8s), planning
+ ~50s → sub-minute iterations.
+
+Experiments, in order (each is a falsifiable question):
+
+- E1: `--explain Torx` on the current code — confirm RC1 (no axis → world
+ axes only). This is the baseline record.
+- E2: D1 stage-2 (all-contact ring fit) alone — do the Torx bolts get a
+ tilted axis and a linear motion? Does knob #1 resolve? Does Part 7
+ unflag once its bolts do?
+- E3: D2 travels — cheese screw travel drops from 606mm to O(30mm); count
+ of derived precedence edges drops; no new verification failures.
+- E4: D3 choice — badge+clamp group stops preceding the sliders; sliders
+ land immediately after the rail.
+- E5: full acceptance (below) + fixture suite (18 tests) + determinism.
+
+## Acceptance (generalized from the expected order — constraints, not a
+literal transcript)
+
+On the seat rail, all of:
+1. `sequence[0]` = Seat Rail; flagged = 0 (or only parts we can defend
+ geometrically, by name, with blockers).
+2. Sliders precede every knob/stop/clamp that sits in their corridor, and
+ appear in the first quarter of the sequence.
+3. Part 7 precedes all four Torx bolts; the Torx bolts are LINEAR along a
+ tilted (non-world) axis, consecutive, verified.
+4. Every fastener follows every member of its joint; washer precedes its
+ screw; the washer+screw stack sits after the badge/clamp it secures.
+5. Knobs appear after the structure they thread into, never before a
+ mounted component they don't touch… and never via a priority jump.
+6. All non-flagged parts verified; planMs within 2× of today's 53s; two
+ consecutive runs byte-identical.
+
+And in the app (D5): fresh plan.json → Regenerate → the browser playback
+shows bolts entering through holes, no fly-through, fade-in only for
+defensible flags.
+
+## Tasks
+
+- [ ] T1 (D5a): find how the local geometry service runs (image vs mount),
+ rebuild/restart with current code; verify `/health` + a plan request
+ uses PLAN_VERSION 2. Document the loop in the plan doc.
+- [ ] T2 (harness): `--explain` / `--sequence` scratch runner; record E1
+ baseline for Torx/knob/Part 7.
+- [ ] T3 (D1): contact-cloud collection (points+normals per part) → ring
+ fit stage 2 → normal-cluster candidates stage 3; fixtures: tilted
+ stubby bolt in a tilted plate (must exit along the tilted bore),
+ box-on-plate normal candidate.
+- [ ] T4 (D2): last-contact travel semantics + margin; adjust
+ `_exit_travel` callers, DAG derive, verify; fixtures: inward-pointing
+ screw gets O(hole) travel; existing 18 tests stay green (travel
+ asserts may need updating — assert direction, not magnitude).
+- [ ] T5 (D3): least-entanglement direction choice; fixture: part with two
+ clear exits, one crossing another part's seat — must pick the empty
+ one (assert via derived-edge count).
+- [ ] T6 (D4): exposure = structure-only; groups inherit fastener-ness.
+- [ ] T7: E5 acceptance run; update contracts doc ordering paragraph;
+ lessons entry (contact geometry > axis lists; travel = free space).
+- [ ] T8 (D5b): "Re-run motion planning" action + button (assembly editor),
+ then in-app E2E: re-plan → regenerate → browser verify.
+
+## Risks / notes
+
+- Contact-normal candidates add directions; direction count stays bounded
+ (≤ symmetry 2 + clusters 6 + world 6) and D2 makes each test cheaper.
+- Ring fits on noisy tessellation: keep the cylinder-fit quality gate
+ (radial std) and fall through to the next stage rather than guessing.
+- The HRKN M8 rail bolts were absent from the expected list; treat their
+ position as unconstrained beyond "after the rail, grouped, verified" —
+ do not tune for them.
+- Fixture travels asserted by magnitude will need loosening after D2 —
+ assert direction and verified-ness instead.
+
+## Execution log (running)
+
+- E1 (baseline): Torx flagged NOT for tilted axes — bores are world-Y; blocked
+ at 0.17–0.35mm by their own joint through-part (Part 7's snug counterbore).
+ Root: tolerance below tessellation noise; fix: `_mesh_tolerance` =
+ max(0.15, 2.5 × linearDeflection), plus **joint-sliding allowances** — along
+ its bore axis a fastener may keep sliding contact with its joint members.
+ Result: all 4 Torx linear through the holes, verified. (rtree was missing
+ from the venv, silently disabling every containment test — added to deps.)
+- D2 (reach-free-space travels): cheese screw 606→49mm, HRKN 127→21mm,
+ sliders keep their honest 131mm ride. Spurious "corridor" classifications
+ and cross-assembly sweep edges gone.
+- D3 (least entanglement): tie-break by candidate order, not travel (travel
+ broke natural-axis preference for loose rods).
+- Ordering evidence (topo pick traces): XY-centrality buckets ranked mid-rail
+ hardware above off-center sliders — centrality is meaningless along a
+ linear assembly; bbox volume lied 5× for tilted bolts and worse for
+ wrap-around/text parts. Now: **mesh volume** (watertight, else sum of
+ watertight split bodies, else bbox) ranks structure big→small; centrality
+ demoted to tiebreak; corridor slot removed (redundant).
+- New hard edges that made the expected order emerge:
+ - **Support/stacking**: mostly-vertical seated contact between structure
+ parts ⇒ lower before upper.
+ - **Joint-stack**: a joint's members order by WHERE they engage the shank
+ (ring-test projection), tip → head, head end = the fastener's widest end
+ (immune to snug-counterbore mate misclassification). The bolt clamps the
+ head-side part onto the tip-side part — works across CAD air gaps.
+- Current seat rail: 40s, forced 0, flagged 3 (Part 7 + 2 clamping knobs —
+ explains in flight), sliders each immediately followed by their Torx pair.
+
+## Final state of this pass (seat rail, local)
+
+```
+ 1. Seat Rail (base) expected: 1 ✓
+ 2. Seat Rail Slider expected: 2 ✓
+ 3. Seat Rail Slider expected: 3 ✓
+ 4. Part 7 expected: 4 ✓
+ 5-8. Bolt M6 Torx ×4 (thru holes) expected: 5-8 ✓
+ 9-10. badge + clamp (group) expected: 12 (variance)
+11-12. cheese screw + washer (group) expected: 13-14 (variance)
+13. clamping knob (radial, planned) expected: 9-11 (variance)
+14-15. knob variant pieces (flagged) — stacked CAD duplicates, fade in
+16-31. HRKN M8 rail bolts ×16 (omitted from expected list)
+tiers: 24 linear, 2 group, 2 flagged, 0 forced · verified 29/31
+```
+
+What landed beyond the original D1–D5: mesh-scaled tolerance; joint-
+sliding allowances (the "through the holes" fix); geometric head-end
+detection; joint-stack (tip→head) and support (lower≺upper) hard edges;
+material-volume structural ranking (split-body volumes for text/logo
+soups); evidence-based rigid merging (single-real-blocker) replacing all
+depth/coincidence heuristics; classification cascade extended to the full
+contact cloud and dominant normals; real-sweep blockers for merge/flag
+decisions; group growth deprioritizes deep-bitten members.
+
+Known remainders:
+- Two knob variant pieces still flag (M12 + the rail-bitten -6-3): the
+ pair-group that would extract them cleanly loses its test budget to the
+ bitten sibling. Honest fade-in with named blockers; refine later.
+- planMs ~170s local (was 24s before the stuck-round merge-scan; the
+ scan's escape sweeps dominate). Optimize when it matters — the plan job
+ is async.
+- In-app loop not yet exercised: uvicorn --reload already runs this code;
+ next step is Re-run Motion Planning → Regenerate from Plan → browser.
diff --git a/.ai/plans/2026-07-06-assembly-visual-motion-camera-editor.md b/.ai/plans/2026-07-06-assembly-visual-motion-camera-editor.md
new file mode 100644
index 0000000000..0484090e48
--- /dev/null
+++ b/.ai/plans/2026-07-06-assembly-visual-motion-camera-editor.md
@@ -0,0 +1,203 @@
+# Plan: Visual motion-path editor + per-step camera capture (assembly instructions)
+
+Date: 2026-07-06
+Branch: `claude/confident-maxwell-dy4fvr`
+Status: **Phases 1–4 implemented** (viewer helpers + tests, red-path editor, camera
+capture, editor/route integration). Gates green: `@carbon/viewer` typecheck + 64 unit
+tests, `erp` + `mes` typecheck, biome clean. **Phase 5 (browser verification) pending.**
+
+## Goal
+
+Restore two authoring capabilities to the assembly instruction editor that the
+number-based motion editor replaced:
+
+1. **Draggable motion path.** When authoring a step's motion, the part's insertion
+ path renders as a **red line in the 3D viewer** with **drag-and-drop waypoints**.
+ Editing waypoints edits the motion. (Replaces typing Vec3 direction/distance.)
+2. **Set camera view per step.** A button that saves the *current* viewer camera
+ as the step's `camera` pose, so playback frames that step exactly as the author
+ set it. Plus a "Clear" that returns the step to auto-framing.
+
+> Note: neither feature exists in git history — this is a **rebuild**, not a revert.
+> The number-based editor has been the only motion editor since the first commit;
+> `step.camera` has only ever been set by the geometry planner, never by UI.
+
+## What already exists (grounding — verified in code)
+
+Persistence is **already done** — this is a UI-only feature:
+
+- `assemblyInstructionStepValidator` (`production.models.ts:1214`) already accepts
+ `motion: jsonField(motionSchema.optional())` and
+ `camera: jsonField(cameraSchema.nullable().optional())`. `motionSchema`
+ (`:1053`) already includes the `path` variant (`keyframes: {t, position, quaternion}[]`,
+ min 2). `cameraSchema` (`:1095`) = `{position: vec3, target: vec3, fov: number}`.
+- The step-save route `x+/assembly+/$id.steps.$stepId.tsx` validates that schema and
+ calls `upsertAssemblyInstructionStep` — **no route/DB/migration changes needed.**
+- Viewer already **consumes** both fields: `motionToKeyframes`/`buildStepClip`
+ (`packages/viewer/src/motion.ts`) animates `path` motions; `AssemblyScene` reads
+ `step.camera` (`AssemblyPlayer.tsx:931+`) to frame the shot, else auto-frames.
+- Viewer stack: react-three-fiber 8.18 + drei 9.122 + three 0.163. drei ships
+ `Line`, `TransformControls`, `DragControls`, `PivotControls`, `Html`, `Sphere`
+ (all present in installed `.d.ts`) — nothing new to add to deps.
+- `nodeId → Object3D` map (`useAssembly.ts:108`, `nodesById`) is already threaded
+ into `AssemblyScene` — the bridge for placing handles at part positions.
+- Live camera is reachable inside `AssemblyScene`: `camera = useThree(s=>s.camera)`
+ (`AssemblyPlayer.tsx:510`), `controls = useThree(s=>s.controls)` (`:511`,
+ OrbitControls via `makeDefault`). `{camera.position, controls.target, camera.fov}`
+ is exactly a `CameraPose`.
+
+The gaps to close:
+
+- Editor (`AssemblyInstructionProperties.tsx` → `StepForm`) supports only
+ `motionTypes = ["none","linear","L","helix"]` (`:165`) and maps `path → none`
+ (`makeMotionDraft`, `:236`). It emits no camera. No Hidden `camera` field exists.
+- `AssemblyPlayer` exposes no way to edit a path or read out the camera
+ (`AssemblyPlayerProps`, `:33`): callbacks are only `onStepChange`, `onSelectParts`,
+ `onGraphLoaded`. `readOnly` disables selection (MES uses it).
+
+## Design decisions (recommended defaults — flag any for veto)
+
+1. **Serialize to RELATIVE motion (`linear`/`L`), not absolute `path`.** Discovered
+ while grounding: a `path` motion's keyframes are absolute world positions, and
+ `motionToKeyframes` validates the last keyframe equals *each part's* seated pose —
+ so `path` only works for single-part steps and would throw on multi-part rigid
+ groups. `linear`/`L` are relative (direction+distance applied to each part's own
+ seated pose), exactly how the planner already animates grouped steps. So the editor
+ emits **`linear` for 2 waypoints, `L` for 3+ waypoints**. Waypoints are world-space
+ for display, anchored so the **last waypoint is the seated reference** (centroid of
+ the step's parts' seated positions); intermediate + first waypoints are draggable,
+ the last is locked to seated. `path` handling is left untouched (planner may still
+ produce it; we convert it to waypoints on open).
+2. **Orientation (v1): pure translation.** Parts translate without rotating — no
+ per-waypoint quaternion authoring (which is why `path` buys us nothing here). Full
+ 6-DOF is out of scope for v1.
+3. **The path editor is the only motion editor.** Selecting a step samples its current
+ motion (`linear`/`L`/`helix`/`path`/`none`) into editable world waypoints via a new
+ `motionToWaypoints` helper, so any step is draggable; drags serialize back via
+ `waypointsToMotion`. The numeric editor is **removed** (see Resolved decisions).
+4. **Waypoint ops:** drag existing (translate gizmo), **double-click a segment** to
+ insert a waypoint, **select + Delete/trash button** to remove. Minimum 2
+ waypoints (start + seated).
+5. **Autosave on drag-end**, debounced, via the existing step fetcher — consistent
+ with direct-manipulation UX. No explicit Save click for path edits.
+6. **Camera button lives in the properties panel** (with the rest of step editing);
+ the viewer exposes an **imperative `captureCameraPose()`** via `forwardRef` so the
+ button can read the live pose. "Set view" saves `camera`; "Clear" saves `null`.
+7. **Edit is Draft-only** (`isDisabled`/`readOnly` already gate this); MES playback
+ (`readOnly`) is untouched. Editing **pauses playback** and pins the part at a
+ preview pose so mixer rebuilds don't fight the handles.
+
+## Architecture
+
+Three panels coordinate through the route (`$id.tsx`), which already owns shared
+selection state (`selectedNodeIds`, `selectedStepId`, `draftPartNodeIds`):
+
+- **Lift a motion-edit session** into `$id.tsx`: `editingMotion: {stepId} | null`
+ plus a `draftMotion` for the step being edited. The viewer renders the red path
+ for `editingMotion.stepId`; `StepForm` toggles the session and mirrors
+ `draftMotion` into its existing `motion` state / Hidden field.
+- **Camera capture** uses a `playerRef` (imperative handle) held by `$id.tsx`,
+ passed to `StepForm` as an `onCaptureCamera`/`onClearCamera` callback pair.
+
+### New/changed files
+
+| File | Change |
+|---|---|
+| `packages/viewer/src/motion.ts` | Add `motionToWaypoints(motion, seatedPosition, opts)` and `waypointsToMotion(worldWaypoints, seatedPosition)` (pure): sample any motion to world waypoints, and convert dragged waypoints back to `linear`/`L`/`none`. Reuse existing `motionToKeyframes`. |
+| `packages/viewer/src/MotionPathEditor.tsx` (new) | In-scene overlay: drei `Line` (red) through waypoints + draggable `TransformControls` handles; last handle locked; double-click insert / Delete remove. Emits world-space waypoints on change. |
+| `packages/viewer/src/AssemblyPlayer.tsx` | Add props `editMotion?: {stepId, motion} \| null`, `onMotionChange?(stepId, motion)`. Render `<MotionPathEditor>` in `AssemblyScene` (sibling of `<primitive object={scene}>`) when editing the active step. `forwardRef` + `useImperativeHandle` exposing `captureCameraPose(): CameraPose` (bridged from an in-scene reporter that closes over `camera`/`controls`). Pause playback while editing. |
+| `packages/viewer/src/index.ts` | Export the new helpers/types if consumed by ERP. |
+| `apps/erp/app/routes/x+/assembly+/$id.tsx` | Hold `editingMotion` + `draftMotion` state and `playerRef`; thread `editMotion`/`onMotionChange` to `AssemblyPlayer`; pass camera + edit callbacks to `AssemblyInstructionProperties`. |
+| `apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx` | `StepForm`: add "Edit path in 3D" toggle (starts/stops the session; syncs `draftMotion` ↔ `motion`); support the `path` motion type in `makeMotionDraft`/`serializeMotion` (stop mapping `path → none`); add "Set camera to current view" + "Clear view" buttons and a `<Hidden name="camera" value=…>` field so camera persists on save. Keep numeric editor under an "Advanced" disclosure. |
+| `apps/erp/app/modules/production/AGENTS.md`, `docs/specs/animated-work-instructions-contracts.md` | Doc the visual editor + camera authoring (keep-docs-in-sync). |
+
+## Phases & tasks
+
+### Phase 1 — Viewer helpers (pure, testable)
+- [ ] `motionToWaypoints(motion, seatedPosition, {defaultDistance?})`: sample any
+ motion into ordered world-space waypoints (start … seated) via `motionToKeyframes`,
+ deduping coincident points. For `none` (or unsamplable), synthesize a short
+ straight default offset so a path always exists to drag.
+- [ ] `waypointsToMotion(worldWaypoints, seatedPosition)`: force last waypoint to
+ seated, drop degenerate segments; 1 segment → `linear`, 2+ → `L`, none → `none`.
+ Directions/distances match `motionToKeyframes`' reconstruction (verified: exact
+ round-trip for linear/L).
+- [ ] Verify: `pnpm --filter @carbon/viewer typecheck` + extend `motion.test.ts`
+ (round-trip linear/L, multi-part safety, none→default, degenerate→none).
+
+### Phase 2 — Editable red path in the viewer
+- [ ] `MotionPathEditor.tsx`: drei `Line` (red, `lineWidth≈3`) through waypoints;
+ `TransformControls` (translate) on each non-terminal handle; terminal handle a
+ static locked marker. Double-click a segment inserts a midpoint; selecting a
+ handle + Delete removes it (min 2). Convert handle positions → world waypoints,
+ call `onMotionChange(stepId, waypointsToPathMotion(...))` on drag-end (debounced).
+- [ ] Wire into `AssemblyScene`: render only when `editMotion?.stepId === activeStep.id`
+ and not `readOnly`. Disable `OrbitControls` while dragging a handle (TransformControls
+ `dragging-changed` → toggle `controls.enabled`). Pause the mixer; pin the edited
+ part at the current preview pose so clip rebuilds don't clobber handles.
+- [ ] Extend `AssemblyPlayerProps` with `editMotion`/`onMotionChange`; keep all existing
+ props/behavior. `readOnly` path unchanged (MES unaffected).
+
+### Phase 3 — Camera capture (imperative)
+- [ ] `forwardRef` on `AssemblyPlayer`; `useImperativeHandle` exposing
+ `captureCameraPose()`. In-scene `CameraPoseReporter` writes a getter
+ (`() => ({position: camera.position.toArray(), target: controls.target.toArray(),
+ fov: (camera as PerspectiveCamera).fov})`) into a ref the handle reads.
+- [ ] No behavior change to existing `step.camera` consumption.
+
+### Phase 4 — Editor + route integration
+- [ ] `$id.tsx`: add `editingMotion`/`draftMotion` state + `playerRef`; pass
+ `editMotion={editingMotion && {stepId, motion: draftMotion}}`,
+ `onMotionChange={(stepId, m) => setDraftMotion(m)}` to `AssemblyPlayer`; pass
+ `onCaptureCamera`/`onClearCamera` (read `playerRef.current.captureCameraPose()`,
+ submit to the step route) and edit-session toggles to `AssemblyInstructionProperties`.
+- [ ] `StepForm`: support `path` in `makeMotionDraft`/`serializeMotion`; add "Edit path
+ in 3D" toggle that opens the session and binds the viewer's `draftMotion` back into
+ `motion` (so the Hidden `motion` field + autosave use it); add "Set camera to current
+ view" / "Clear view" buttons and `<Hidden name="camera">`. Numeric editor moves under
+ an "Advanced" disclosure (kept, not removed).
+- [ ] Autosave path edits on drag-end via the step fetcher (debounced ~500ms).
+
+### Phase 5 — Verify
+- [ ] `pnpm --filter @carbon/viewer typecheck`, `pnpm exec turbo run typecheck --filter=erp`,
+ `pnpm run lint`, viewer unit tests.
+- [ ] Browser (agent-browser `/auth` + `/test`): create/open a Draft instruction on a
+ converted model → select a step → "Edit path" shows a red line with handles → drag a
+ waypoint, add one, delete one → play the step and confirm the part follows the new
+ path → "Set camera to current view", reload, confirm the step frames to the saved pose
+ → "Clear view" returns to auto-frame. Confirm MES playback (readOnly) is unchanged.
+- [ ] Screenshots in the PR (surface-designs rule).
+
+## Risks / watch-items
+
+- **Mixer vs handles.** The clip effect (`AssemblyPlayer.tsx:658`) rebuilds on step/seek
+ and restores seated poses on cleanup. The editor overlay must live outside that lifecycle
+ and edit must pause playback (decision #7), or drags will fight the animation.
+- **World vs local space.** Handles are world-space; `buildStepClip` localizes to parent.
+ Keep all editing in world space and only convert at `waypointsToPathMotion`; verify with a
+ part that has a non-identity parent transform.
+- **TransformControls + OrbitControls conflict.** Standard drei pattern: toggle
+ `controls.enabled` on `dragging-changed`. Must restore on unmount.
+- **`readOnly`/MES regression.** All new UI gates on `!readOnly` + Draft. Add an explicit
+ check that the MES `Assembly.tsx` consumer compiles and behaves unchanged.
+- **fov edge case.** Orthographic camera has no `fov`; guard with `PerspectiveCamera`
+ instanceof (already the pattern at `:820`), fall back to 45.
+
+## Out of scope (v1)
+
+- 6-DOF waypoint rotation (orientation authoring).
+- Editing `helix`/`L` *parameters* by 3D manipulation (numeric "Advanced" editor stays).
+- Timeline-keyframe scrubbing UI beyond the existing playback scrubber.
+
+## Resolved decisions (2026-07-06)
+
+- **Remove the numeric motion editor entirely.** The visual path editor is the only
+ motion editor. Any planner-produced motion (`linear`/`L`/`helix`/`none`) is converted
+ to an editable `path` on selection via `motionToWaypoints`; there is **no** numeric
+ Vec3/parameter fallback. `motionTypes` / `MotionDraft` / `serializeMotion` /
+ `VectorInput` / `ScalarInput` and the `showMotionEditor` disclosure in `StepForm` are
+ deleted. Consequence: helix/L can no longer be edited *parametrically* — only as a
+ dragged path. (Accepted.)
+- **Autosave path edits on drag-end** (debounced), via the step fetcher. No Save click.
+- **Camera button in the properties panel**, reading the live pose through the
+ `AssemblyPlayer` imperative ref.
diff --git a/.ai/plans/2026-07-06-bom-driven-subassembly-planning.md b/.ai/plans/2026-07-06-bom-driven-subassembly-planning.md
new file mode 100644
index 0000000000..03cf0d95f4
--- /dev/null
+++ b/.ai/plans/2026-07-06-bom-driven-subassembly-planning.md
@@ -0,0 +1,311 @@
+# BOM-Driven Subassembly Planning — Plan Nested Units, Not Leaf Soup
+
+## Problem
+
+A real customer model ("431 parts") planned for **11 minutes** and produced
+hundreds of junk steps. The assembly is really **7 BOM lines** — one of them a
+purchased PCB whose 3D model carries hundreds of tiny child solids (chips,
+caps, connectors). Today the planner flattens every leaf mesh into an
+independent rigid body (`_collect_world_parts` in `services/geometry/app/plan.py`
+discards the hierarchy), so it fights 400+ bodies that can never separate in
+real life, then step generation surfaces them all.
+
+Everything needed to fix this already exists in the system:
+
+| Signal | Where it lives | State |
+|---|---|---|
+| CAD hierarchy (PCB = one subassembly node) | `graph.json` (`convert.py` preserves `isAssembly` + `children`) | built, ignored by planner |
+| Engineering BOM (7 items) | `getFlattenedBomMaterials(client, itemId, companyId)` | built |
+| Geometry ↔ BOM item mapping | `assemblyPartMapping` (geometryHash → itemId), auto-matched by `autoMatchAssemblyParts` (nameSimilarity ≥ 0.45 greedy) | built |
+| Persisted "these nodes are one unit" | `assemblyGroup` table (becomes lean `assemblyUnit` per D0) | built, display-only |
+| One-step-per-unit playback | plan.json v2 `groups: { gN: { partNodeIds, motion } }` → `buildAssemblyStepGroups` makes a group ONE step; AssemblyPlayer animates it | built |
+
+The change is therefore mostly **wiring**: derive the planned units in TS from
+BOM + hierarchy + authored units, hand them to the planner, and let the
+planner treat each unit as a single rigid body. Collapsing 431 → ~7 bodies also
+collapses the O(N²) collision work — this should take the 11-minute run back
+to well under a minute.
+
+## Prerequisite (uncommitted work in tree)
+
+The async `/plan` refactor (submit → 202 + poll `GET /plan/{jobId}`, worker
+polls via `step.sleep`) is already implemented and typechecked in the working
+tree (`services/geometry/app/main.py`, `schemas.py`,
+`packages/jobs/src/inngest/functions/tasks/assembly-plan.ts`). It fixes the
+`UND_ERR_HEADERS_TIMEOUT` retry-storm on long plans. Commit it first (or with
+Task 3) — this plan builds on that flow.
+
+## Design
+
+### D0. One grouping concept: the Subassembly (drop the parity taxonomy)
+
+The `assemblyGroup` types `Cluster` / `Kit` / `Combination` are leftovers of
+the abandoned feature-parity direction: all three are display-only (nothing
+consumes them), kitting belongs on the materials side if it ever returns, and
+"Combination = parts treated as one unit" is superseded by BOM-driven unit
+derivation. `assemblyInstructionStep.groupIds` is a dead column (no reads or
+writes anywhere).
+
+`childInstructionId` goes too (user-confirmed): instructions attach to
+**items**, and each BOM level is its own item — a Make subassembly's item gets
+its own `assemblyInstruction` with its own model. The parent instruction never
+spawns or links child instructions; it just consumes the subassembly as one
+part. With that gone, nothing about the override is instruction-specific, so
+the row rescopes from `assemblyInstructionId` to **`modelUploadId`** — the same
+scoping (and survival semantics across instruction delete/recreate) as
+`assemblyPartMapping`. The worker also only has `modelUploadId`, so derivation
+reads it directly.
+
+Simplify while the branch is unshipped (user-confirmed):
+
+- **Schema** — edit migration `20260611134652_assembly-editor-parity.sql` in
+ place: replace `assemblyGroup` with a lean **`assemblyUnit`** table —
+ `id, modelUploadId (FK modelUpload, CASCADE), name, partNodeIds TEXT[],`
+ `itemId TEXT NULL (mapped BOM item), companyId, audit fields`. Drop the
+ `assemblyGroupType` enum, `childInstructionId`, `partNumber`, and
+ `assemblyInstructionStep.groupIds` (dead column). Local DB patch (no
+ rebuild): drop `assemblyGroup` + the enum + the `groupIds` column, create
+ `assemblyUnit` (exact SQL written at execution time from the edited
+ migration). Then regenerate DB types (`pnpm run generate:types`) BEFORE
+ typechecking.
+- **Models/service** — `assemblyUnitValidator`, `get/upsert/deleteAssemblyUnit`
+ replace the group equivalents (mechanical rename + simplification; routes
+ `$id.groups.*` → `$id.units.*`).
+- **UI** — BOM tree "Groups" section becomes **"Subassemblies"** (label stays
+ in manufacturing language even though the table is `assemblyUnit`); the
+ four-option Group dropdown becomes one "Create subassembly" action.
+
+### D1. Unit derivation is a pure TS function (BOM is the source of truth)
+
+New `deriveAssemblyUnits` in `packages/viewer/src/units.ts` (pure — no DB, no
+IO — so it unit-tests trivially and both the worker and the UI can call it):
+
+```ts
+type AssemblyUnit = {
+ id: string; // subtree root nodeId (or authored unit id)
+ name: string; // BOM item name > node name
+ nodeIds: string[]; // member LEAF nodeIds (what the planner merges)
+ itemId?: string; // BOM item this unit maps to, when known
+ source: "authored" | "bom" | "hierarchy";
+};
+
+function deriveAssemblyUnits(args: {
+ graph: AssemblyGraph;
+ bomMaterials: { itemId: string; name: string | null }[];
+ partMappings: { geometryHash: string; itemId: string }[];
+ authoredUnits: { id: string; partNodeIds: string[] }[]; // assemblyUnit rows
+}): AssemblyUnit[];
+```
+
+Rules, in precedence order:
+
+1. **Authored** `assemblyUnit` rows are explicit units (the user's
+ override — both "collapse this" and, by deleting the unit, "expand
+ this").
+2. **Unwrap wrappers**: descend through single-child assembly chains from the
+ root (STEP exports often nest `Product → Assembly → actual children`).
+3. **Top-level candidates**: the (unwrapped) root's direct children. A leaf
+ child is a unit of itself.
+4. **BOM refinement** for assembly-node candidates:
+ - If the node (or its subtree) corresponds to **≤ 1 BOM item** — via
+ `nameSimilarity(nodeName, bomName)` at the threshold `autoMatchAssemblyParts`
+ already uses, or because every mapped leaf inside it maps to the same
+ item — **collapse** it into one unit (the PCB case).
+ - If the node does NOT correspond to a BOM item but its children match
+ several BOM items, **descend one level** and re-apply (handles gratuitous
+ grouping layers).
+ - No BOM / no matches → keep the top-level-only fallback (collapse the
+ subassembly node as one unit). Flat models (all leaves at root) behave
+ exactly as today.
+
+`nameSimilarity` moves from `production.service.ts` to a shared pure module
+(`packages/viewer/src/similarity.ts` or `@carbon/utils`) and is re-imported by
+the service — one implementation, not two.
+
+### D2. Planner contract: `options.units`, plan version 3
+
+`POST /plan` request gains an optional field (geometry service stays dumb —
+it receives geometry decisions, it doesn't make BOM decisions):
+
+```jsonc
+"options": {
+ "units": [ { "id": "nodeId-of-subtree", "name": "PCB Assembly", "nodeIds": ["leaf1", "leaf2", ...] } ]
+}
+```
+
+In `plan_step` / `_collect_world_parts`: leaves listed in a unit concatenate
+into **one `_Part`** (single trimesh, `node_id = unit.id`). Contacts inside a
+unit are self-exempt by construction. Multi-member units emit into plan.json
+as the **existing v2 `groups` shape** (`partNodeIds` = member leaves, shared
+motion) plus an additive optional `name` — downstream step generation and the
+viewer already handle groups as one step.
+
+Bump `PLAN_VERSION` (plan.py) and `CURRENT_PLAN_VERSION`
+(`packages/viewer/src/plan.ts`) **2 → 3** so pre-grouping plans are treated as
+absent and auto-replan — same staleness mechanism that retired v1.
+
+### D3. Worker derives units before submitting
+
+`assembly-plan.ts` `start-plan` step, before the POST: download `graph.json`
+(small), load BOM (`modelUpload → assemblyInstruction.itemId →
+getFlattenedBomMaterials` equivalent via service role), `assemblyPartMapping`
+rows, and `assemblyUnit` rows (all `modelUploadId`-scoped); call `deriveAssemblyUnits`;
+pass `options.units`. No instruction/BOM found → pass only hierarchy-derived
+units (the function handles empty inputs).
+
+### D4. UI: units in the BOM tree + re-run
+
+`AssemblyBomTree.tsx` gains a subassembly-node view: an assembly node that was
+(or would be) collapsed renders as one row — name, member count, mapped BOM
+item — with a **"Plan as one part" toggle** that upserts/deletes the
+`assemblyUnit` (`partNodeIds` = subtree leaf ids). This
+also de-noises the current distinct-parts list (the PCB's 300 internals fold
+into one row). The existing **Re-run plan** action
+(`$id.plan.rerun.tsx`) already covers "apply my change".
+
+### D5. Step generation niceties
+
+`buildAssemblyStepGroups` passes the group `name` through so the draft step
+titles read "Install PCB Assembly" instead of a 300-part enumeration
+(`describeStep` prefers the group name when present). Auto-linking the step's
+`assemblyInstructionStepMaterial` to the unit's mapped `itemId` is a natural
+follow-up — noted, **not in this pass**.
+
+## Tasks
+
+- [x] **T0 — Commit the async /plan prerequisite** already in tree.
+ Verify: `pnpm exec turbo run typecheck --filter=@carbon/jobs` green;
+ `services/geometry/.venv/bin/python -m pytest -q` green.
+
+- [x] **T0.5 — Simplify the group model (D0)**
+ Files: `packages/database/supabase/migrations/20260611134652_assembly-editor-parity.sql`
+ (in-place edit), local psql patch (SQL in D0), `pnpm run generate:types`,
+ `production.models.ts`, `production.service.ts`,
+ `AssemblyBomTree.tsx` (Subassemblies section, single create action),
+ routes `$id.groups.*` → `$id.units.*` (no child-instruction creation).
+ Verify: `pnpm exec turbo run typecheck --filter=erp` green; BOM tree renders
+ and creates a subassembly locally.
+
+- [x] **T1 — `deriveAssemblyUnits` + shared `nameSimilarity`**
+ Files: `packages/viewer/src/units.ts` (new), `packages/viewer/src/units.test.ts`
+ (new), move `nameSimilarity` out of `production.service.ts`, export from
+ `packages/viewer/src/index.ts`.
+ Tests: wrapper unwrap; flat model → per-leaf units; PCB-like fixture
+ (7 children, one with 300 leaves + BOM of 7) → 7 units; authored unit
+ precedence; descend-when-no-BOM-match.
+ Verify: `pnpm --filter @carbon/viewer test` and typecheck green.
+
+- [x] **T2 — Geometry service: units + PLAN_VERSION 3**
+ Files: `services/geometry/app/schemas.py` (`PlanOptions.units`),
+ `services/geometry/app/plan.py` (`plan_step(units=...)`, merge in
+ `_collect_world_parts`, emit `groups` with `name`, `PLAN_VERSION = 3`),
+ `services/geometry/tests/test_plan.py` (nested fixture via
+ `tests/fixtures/make_fixtures.py`: enclosure + board-with-children →
+ collapsed unit plans as one body, group payload carries members + name).
+ Verify: `services/geometry/.venv/bin/python -m pytest -q` green.
+
+- [x] **T3 — Worker passes units**
+ File: `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts` —
+ fetch graph/BOM/mappings/groups, call `deriveAssemblyUnits`, send
+ `options.units`.
+ Verify: typecheck green; local run (see T6).
+
+- [x] **T4 — Viewer/step-gen: v3 + names**
+ Files: `packages/viewer/src/plan.ts` (`CURRENT_PLAN_VERSION = 3`, parse
+ optional group `name`, title passthrough in `buildAssemblyStepGroups`),
+ `packages/viewer/src/plan.test.ts`.
+ Verify: `pnpm --filter @carbon/viewer test` green.
+
+- [x] **T5 — BOM tree unit rows + toggle**
+ Files: `apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx`,
+ `production.service.ts` (group upsert already exists — reuse), route for the
+ toggle if one doesn't fit an existing action.
+ Verify: typecheck; browser check in T6.
+
+- [x] **T6 — End-to-end on the real model**
+ Re-upload (or plan.rerun) the 431-part model: expect ~7 planned units,
+ plan runtime **≪ 11 min** (target < 2 min), Generate Steps produces ~7 draft
+ steps with sane titles, PCB animates as one unit.
+ Verify: `assemblyPlanJob` row Success + timing; steps count; visual check.
+
+- [x] **T7 — Spec + docs sync**
+ Update `.ai/specs/2026-07-04-animated-work-instructions-contracts.md`
+ (units option, v3, group name) and the production module `AGENTS.md` row for
+ `generateAssemblyStepsFromPlan`/plan pipeline.
+
+## Risks / notes
+
+- **Name-similarity misgrouping**: a subassembly wrongly collapsed hides real
+ steps. Mitigations: only subtree candidates are eligible (never arbitrary
+ node sets), the BOM tree shows what collapsed and why, and the toggle undoes
+ it per model. The failure mode is conservative (fewer, coarser steps), not
+ corrupt motion.
+- **No instruction/BOM at plan time** (model uploaded standalone): derivation
+ degrades to hierarchy-only — still strictly better than today's flat soup.
+- **Collision cost of merged meshes**: a collapsed PCB keeps its full
+ triangle count in one body; pair count drops quadratically so net runtime
+ falls sharply. If a pathological model is still slow, decimating unit
+ collision meshes is the follow-up lever (not in this pass).
+- **Plan v3 staleness bump** auto-invalidates every existing v2 plan —
+ intended (they're leaf-soup plans), but note reruns will trigger on next
+ Generate Steps for existing models.
+- **`assemblyUnit.partNodeIds` vs re-uploads**: nodeIds are stable per the
+ nodeId contract for the same geometry; a changed model re-derives units
+ fresh (authored units referencing vanished nodeIds are skipped by
+ derivation).
+
+- **Two meanings of "group"**: plan.json `groups` (wire format for a
+ multi-part planned unit) is unrelated to the `assemblyUnit` table (persisted
+ subassembly override). Post-D0 nothing DB-side is called a "group", which
+ dissolves the collision.
+
+## Revision — CAD is flat, group by BOM membership (2026-07-06)
+
+Inspecting the real model (SA-BCU, 431 leaves) disproved the nesting
+assumption: the STEP export is **completely flat** — all 431 solids are direct
+children of the root, no subassembly nodes. The PCB's ~400 component solids
+(`R_0402`, `SOT-23`, `PG-TSDSO`, `minimalBCU_gen2_PCB`, …) are top-level
+siblings of the enclosure, seal, and screws. The BOM has 7 lines including
+**`BCU PCB` (qty 1)**.
+
+So units cannot come from the tree. `deriveAssemblyUnits` is rewritten to group
+by **BOM membership**:
+- The LLM (`assignPartsToBom`, gpt-4o-mini) assigns each distinct part *name* to
+ a BOM line — electronic footprints → the PCB line — since text similarity
+ can't (`minimalBCU_gen2_PCB` vs `BCU PCB` scores 0.25; `R_0402` shares nothing
+ with `BCU PCB`). Exact geometry↔BOM mappings win over the LLM guess.
+- Leaves group by assigned item. A group **collapses into one rigid body only
+ when quantity ≤ 1 and it has ≥ 2 leaves** (a single subassembly shown in
+ detail — the PCB). Multi-quantity lines (8 screws, 4 clips) stay separate
+ bodies; the viewer's identical-part grouping still merges them into a step.
+- The qty≤1 heuristic is imperfect (user: "1 seems most correct… may not be
+ true in other instances") — the T5 manual override (`assemblyUnit`) is the
+ escape hatch for the exceptions.
+
+Replaces the hierarchy-unwrap/descend rules and `assemblyUnitCandidates` from
+the original D1. `AssemblyUnit.source` is now `authored | bom | loose`. The
+worker sends only collapsed (multi-leaf) units as `options.units`.
+
+## T6 result — verified on SA-BCU (2026-07-06)
+
+Triggered a fresh plan for the real 431-leaf model end-to-end:
+- LLM assigned all 431 leaves, 0 unmatched: 412 → BCU PCB, 8+4 screws, 4 clips,
+ seal/lid/box (~1s, gpt-4o-mini).
+- Geometry planned **~20 bodies in 105s** (was 431 bodies / ~11 min).
+- plan.json v3 with two collapsed units: `BCU PCB` (411 members) and
+ `Electronics Box - 36 Pin` (2 members).
+- buildAssemblyStepGroups over the real graph → **431 parts render as 11 steps**,
+ the PCB one step titled "BCU PCB".
+- Caveat: the merged PCB and Box bodies flag (motion "none", fade in) — no
+ collision-free insertion into the sealed enclosure. Structurally correct;
+ motion quality is a follow-up (manual motion or an authored split).
+
+## Execution log (running)
+
+- 2026-07-06 — Plan drafted; rule = BOM-driven with top-level hierarchy
+ fallback + authored-group override (user-confirmed).
+- 2026-07-06 — D0 added: collapse the parity taxonomy to Subassembly-only,
+ in-place migration edit + local psql patch (user-confirmed).
+- 2026-07-06 — D0 revised: no child instructions at all (instructions attach
+ to items; each BOM level's item has its own instruction), so the override
+ rescopes to `modelUploadId` as lean `assemblyUnit` (user-confirmed).
diff --git a/.ai/plans/2026-07-06-order-preserving-motion-replan.md b/.ai/plans/2026-07-06-order-preserving-motion-replan.md
new file mode 100644
index 0000000000..8895e22792
--- /dev/null
+++ b/.ai/plans/2026-07-06-order-preserving-motion-replan.md
@@ -0,0 +1,283 @@
+# Plan: order-preserving "Re-run Motion Planning" (forward-collision re-motion)
+
+Status: **APPROVED — executing (2026-07-07).** Open questions resolved by the
+user: (1) preserve **Done** steps only — recompute manual ones; (2) ordering is
+derived **only** when generating steps from scratch (Re-run never reorders;
+Regenerate triggers its own fresh reordering plan); (3) modal copy approved
+(trimmed to mention Done only).
+
+## Context
+
+"Re-run Motion Planning" (the button in the Assembly editor, both tabs' footers)
+today triggers a **fresh** plan: the geometry service re-derives the assembly
+**order** from scratch (`_greedy_disassembly` → `_preference_topo_sort`) and
+recomputes every part's motion. Two problems the user hit:
+
+1. It's a heavy, destructive-feeling operation with **no confirmation**.
+2. It **ignores the step order the user has already authored** — the planner
+ invents its own order, so re-running can reshuffle everything.
+
+The user wants re-run to instead:
+
+- **Take the order of parts "as evident"** — use the *existing steps* (ordered by
+ `sortOrder`, each with its `partNodeIds`) as the fixed assembly sequence.
+- **Plan motion so each step's parts avoid collision with parts from *previous*
+ steps** — forward-collision only, against the accumulated placed geometry.
+- Sit behind a **confirmation modal**.
+
+Good news from code archaeology: the planner **already** does forward-only
+collision verification. `_verify_sequence()` (`services/geometry/app/plan.py`
+:1441–1488) walks the sequence, building a `CollisionManager` incrementally, and
+re-checks each part's motion against **only the parts already placed** (sets
+`verified=True` or demotes to `flagged` + `blockedBy`). The new mode reuses this
+almost verbatim — it just **fixes the sequence to the given step order** and skips
+the ordering phases.
+
+## Goal
+
+Three deliverables, in order of size:
+
+1. **Confirm modal** on "Re-run Motion Planning" (small, ERP-only).
+2. **Order-preserving re-motion**: re-run uses the current step order as the fixed
+ sequence and recomputes each step's motion with forward-collision avoidance
+ (geometry service + jobs + ERP service).
+3. **Map results back in place**: update each step's `motion`/`warnings` without
+ regenerating steps (preserve titles, typed fields, requirements, materials,
+ status, camera, and manual edits).
+
+`PLAN_VERSION` stays **3** — the new input (`options.sequence`) is additive and
+the plan.json output shape is unchanged (per the standing frozen-version rule,
+[[project — no plan version bumps]]).
+
+## Current flow (grounded)
+
+- Button → `apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx` →
+ `trigger("assembly-plan", { modelUploadId, companyId, userId })`.
+- Worker `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts`:
+ - `loadPlanUnits(...)` (`plan-units.ts`) → `options.units` (`{id,name,nodeIds}[]`).
+ - `POST {geometryUrl}/plan` with `{ jobId, source:{url,format:"step"}, options:{units} }`
+ (lines ~125–134), polls `GET /plan/{jobId}`, persists `plan.json` + `stats` on
+ `assemblyPlanJob`.
+ - If `event.data.generateStepsFor` is set, calls `generateAssemblyStepsFromPlan`.
+- Geometry `services/geometry/app/`:
+ - Endpoint `main.py:236–290` (`POST /plan`, `GET /plan/{job_id}`), schema
+ `schemas.py:66–74` (`PlanOptions`, `PlanUnit`).
+ - `plan_step()` (`plan.py:242–356`): `_merge_units()` (427–467) merges each unit
+ into one body, `_plan_parts()` (483–712) does classify → **greedy order** →
+ precedence → **topo order** → **forward-verify**, then expands units back to
+ members + emits `groups`.
+ - Per-part motion search: `_plan_removal()` (2594), `_plan_escape()` (2770),
+ `_path_is_clear()` (3249), `_path_blockers()` (813). Forward verify:
+ `_verify_sequence()` (1441).
+- Plan → steps: `generateAssemblyStepsFromPlan` (`generate-assembly-steps.ts` +
+ `production.service.ts`), `buildAssemblyStepGroups` (`packages/viewer/src/plan.ts`).
+- Step motion patch: `updateAssemblyStepMotion` (`production.service.ts:4158`),
+ route `$id.steps.motion.$stepId.tsx`.
+
+## Design
+
+### The new geometry mode: `options.sequence`
+
+Add an optional `sequence` to the `/plan` request:
+
+```
+options.sequence?: string[][] // ordered groups of leaf nodeIds; group i = step i's parts
+```
+
+When `sequence` is present, the planner **bypasses ordering** and treats each
+group as one rigid body installed in the given order:
+
+1. Merge each group into one body (reuse `_merge_units` — every group is a "unit"
+ for motion purposes; a single-part group is just that part).
+2. **Sequence = the given group order** (skip `_greedy_disassembly` and
+ `_preference_topo_sort` entirely).
+3. Walk the sequence forward, incrementally registering placed bodies in a
+ `CollisionManager`; for each group compute an insertion motion against **only
+ the already-placed groups** — reuse `_plan_removal` / `_plan_escape`, then the
+ existing `_verify_sequence` acceptance logic. A group with no collision-free
+ path → `motion:"none"` + `blockedBy` (`flagged`), exactly like today (the
+ viewer fades it in — no fabricated path).
+4. Emit the same plan.json shape: `sequence` (member leaves), `parts` (each member
+ carries the group motion + `groupId` + `verified`/`blockedBy`), and `groups`
+ (partNodeIds + motion). No `name` needed here (titles are owned by the steps).
+
+This is deliberately the **units mechanism with a fixed order** — maximal reuse,
+minimal new surface. `linearDeflection`/`clearance`/`pathSamples` still apply.
+
+### Mapping results back to steps (in place)
+
+Re-run must **not** regenerate steps. New ERP service fn
+`updateAssemblyStepMotionsFromPlan(client, { assemblyInstructionId, plan, companyId, userId })`:
+
+- For each step, take its `partNodeIds` as a set, find the plan `group` whose
+ `partNodeIds` set-equals it (same match rule as `describeStep`'s unit match —
+ reuse a shared helper), and update the step's `motion` + `warnings`
+ (`flagged`/`blockedBy`) via a Kysely transaction (multi-row).
+- Recompute `planConfidence` from the plan (`high`/`low`), **except** preserved
+ steps (below).
+- Leave `title`, typed fields, `camera`, `sortOrder`, requirements, materials,
+ and `status` untouched.
+
+### Trigger path
+
+Reuse the async `assembly-plan` job. Add an optional event field
+`reMotionFor?: assemblyInstructionId` (mirrors the existing `generateStepsFor`):
+
+- Rerun route reads the instruction's steps (ordered by `sortOrder`) and passes
+ `reMotionFor` (the worker reads the steps to build `sequence`, keeping the event
+ payload small).
+- Worker, when `reMotionFor` is set: build `options.sequence` from the steps'
+ `partNodeIds` (skip `loadPlanUnits` — the steps already encode grouping), submit,
+ poll, persist the plan.json as today, then call
+ `updateAssemblyStepMotionsFromPlan` instead of `generateAssemblyStepsFromPlan`.
+
+## Decisions (recommended — flag for veto)
+
+- **D1 — Re-run = order-preserving re-motion.** The "Re-run Motion Planning"
+ button always preserves the current step order/grouping and only recomputes
+ motions. Fresh reordering stays the job of the initial **Generate Steps** and
+ **Regenerate from Plan** paths. *(This is the user's explicit ask.)*
+- **D2 — Update motions in place**, never delete/re-insert steps. Preserves all
+ authored step content.
+- **D3 — Preserve DONE steps only (resolved).** Steps with `status:"Done"` keep
+ their existing motion (not overwritten); their parts are still **placed
+ obstacles** for later steps' collision checks. Steps with
+ `planConfidence:"manual"` (hand-adjusted but not Done) **are recomputed** — only
+ Done is treated as locked.
+- **D4 — Per-step (group) motion.** Each step's parts move together as one rigid
+ body (matches how a step animates today); forward-collision is checked for the
+ whole group against the union of all prior steps' parts.
+- **D5 — No `PLAN_VERSION` bump.** Additive input, unchanged output shape.
+- **D6 — Flagged steps** (no collision-free motion found) store `motion:"none"` +
+ `warnings:{flagged,blockedBy}` as today; the viewer fades them in.
+- **D7 — Regenerate owns ordering (resolved).** Ordering (`_greedy_disassembly`
+ → `_preference_topo_sort`) is derived **only** when generating steps from
+ scratch: initial **Generate Steps** and **Regenerate from Plan**. Both trigger a
+ fresh *reordering* plan. **Re-run Motion Planning never reorders** — it always
+ uses the existing step order (`options.sequence`). This means Regenerate must
+ trigger its OWN fresh plan (it can no longer rely on Re-run having produced one)
+ — folded into scope (Task C4 below).
+
+## Open questions — RESOLVED
+
+- **OQ1 (resolved).** Confirm-modal copy: *"Recomputes how each step's parts move
+ into place, using the current step order and avoiding collisions with parts from
+ earlier steps. Steps you've marked Done are left as-is."* (trimmed "manually
+ adjusted" per D3).
+- **OQ2 (resolved).** Preserve **Done** steps only; recompute manual (D3).
+- **OQ3 (resolved).** Regenerate triggers its own fresh reordering plan; Re-run
+ never reorders (D7, Task C4).
+- **OQ4 (resolved — recommendation accepted).** A step whose parts don't
+ set-equal any plan group is left untouched; surface a per-run count of unchanged
+ steps.
+- **OQ5 (resolved — recommendation accepted).** Force `motion:"none"` for the base
+ step (`sortOrder === 1`), matching `buildAssemblyStepGroups`' base exemption.
+
+## Tasks
+
+### Phase A — Geometry service (`services/geometry/`)
+
+- [ ] **A1. Schema.** `app/schemas.py` — add `sequence: list[list[str]] | None = None`
+ to `PlanOptions` (66–74). Validation: non-empty groups, nodeIds are strings.
+- [ ] **A2. Fixed-order planning.** `app/plan.py` — in `plan_step()` (242–356),
+ when `options.sequence` is set, branch to a new `_plan_fixed_sequence(parts,
+ groups_in_order, trimesh, clearance, path_samples, ...)` that:
+ merges each group (reuse `_merge_units` per group), sets the sequence to the
+ given order, and runs the existing forward-verify acceptance
+ (`_verify_sequence` logic) computing each group's motion via `_plan_removal`
+ / `_plan_escape` against the incrementally-built manager. Emit the same
+ `_PlanOutcome`/plan.json shape (sequence, parts, groups). Reuse the base
+ exemption (OQ5). **No new tiers, no version bump.**
+ - Keep `_greedy_disassembly` / `_preference_topo_sort` for the no-sequence
+ path unchanged.
+- [ ] **A3. Tests.** `services/geometry/tests/test_plan.py` — add cases:
+ (a) a 3-body stack with a **given** order returns forward-collision-clear
+ motions; (b) a given order that forces a collision flags the offending group
+ (`motion:"none"` + `blockedBy`); (c) reversing the given order changes which
+ group flags (proves order is respected, not re-derived); (d) a single group
+ == whole model behaves like the base.
+ - Verify: `cd services/geometry && <pytest cmd from repo>` → new tests pass.
+
+### Phase B — Jobs (`packages/jobs/`)
+
+- [ ] **B1. Event field.** Add optional `reMotionFor?: string` to the
+ `assembly-plan` event payload (event types in `@carbon/lib/events`; mirror
+ `generateStepsFor`).
+- [ ] **B2. Worker branch.** `src/inngest/functions/tasks/assembly-plan.ts` —
+ when `reMotionFor` is set: load the instruction's steps ordered by
+ `sortOrder`, build `sequence = steps.map(s => s.partNodeIds)` (skip preserved
+ steps per D3? — see below), send `options:{ sequence }` (omit `units`), poll,
+ persist plan.json as today, then call the new
+ `updateAssemblyStepMotionsFromPlan` instead of generating steps.
+ - Preserved (manual/Done) steps: still include their parts in `sequence`
+ (they're obstacles) but tell the mapping fn not to overwrite them.
+- [ ] **B3.** `plan-units.ts` unchanged (still used by the fresh path).
+
+### Phase C — ERP service (`apps/erp/app/modules/production/`)
+
+- [ ] **C1. Read steps for order.** Reuse `getAssemblyInstructionSteps` (ordered by
+ `sortOrder`).
+- [ ] **C2. Mapping fn.** `production.service.ts` — add
+ `updateAssemblyStepMotionsFromPlan(client, { assemblyInstructionId, plan,
+ companyId, userId })`: Kysely transaction; for each non-preserved step, match
+ its `partNodeIds` to a plan group (shared set-equality helper) and update
+ `motion` + `warnings` + `planConfidence`. Count unmatched (OQ4) and
+ preserved. Force base step `motion:"none"` (OQ5).
+ - Extract the set-equality match into a shared util reused by
+ `describeStep`'s unit match ([[feedback — module service pattern]] — keep it
+ in the module/service files, not scattered).
+- [ ] **C3. Rerun route.** `$id.plan.rerun.tsx` — pass `reMotionFor: id` in the
+ `trigger("assembly-plan", ...)` payload when the instruction already has
+ steps; keep the fresh (reordering) path when it has none.
+- [ ] **C4. Regenerate owns ordering (D7).** `$id.steps.generate.tsx` +
+ `generateAssemblyStepsFromPlan` — the `mode:"regenerate"` path must run on a
+ **fresh reordering plan**, not a stale one. Trigger a fresh `assembly-plan`
+ (no `reMotionFor`) and rebuild steps from it. Confirm the "Regenerate from
+ Plan" affordance in `AssemblyInstructionExplorer.tsx` still surfaces
+ correctly now that Re-run no longer produces newer reordered plans (it may
+ need to always offer Regenerate, gated on a fresh plan run rather than on
+ `planJob.createdAt > newestStepAt`).
+
+### Phase D — ERP UI (`apps/erp/app/modules/production/ui/Assemblies/`)
+
+- [ ] **D1. Confirm modal.** `AssemblyInstructionExplorer.tsx` — add
+ `showRerunConfirm` state + a `Modal` (mirror the existing `showRegenerate`
+ modal), copy per OQ1. Change the "Re-run Motion Planning" button `onClick` to
+ open it; the modal's confirm fires the existing `rerunPlanFetcher.submit(...)`
+ to `path.to.assemblyPlanRerun(id)`. (The button already lives in the Steps
+ footer; Parts-tab re-run is out of scope unless requested.)
+- [ ] **D2.** No change to the sticky Add Step buttons (already shipped).
+
+### Phase E — Verification
+
+- [ ] **E1.** `pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=erp`.
+- [ ] **E2.** `pnpm --filter @carbon/viewer test` (if the shared match helper moves
+ into viewer) + `pnpm --filter @carbon/jobs test`.
+- [ ] **E3.** Geometry: run `test_plan.py`.
+- [ ] **E4.** Browser (in an Electric-X-accessible session): author 3–4 steps, hit
+ Re-run → confirm modal → after the job, each step's motion updates, order is
+ unchanged, a deliberately-blocked step flags, and a manually-edited step's
+ motion is preserved.
+
+## Risks
+
+- **R1 — nodeId compatibility.** `options.sequence` uses graph leaf nodeIds; the
+ planner must map them to its `_Part`s. The existing `options.units` path already
+ does this (`_merge_units` looks up `by_id[member]`), so it's proven — but the
+ new mode must handle nodeIds present in a step but **absent** from the planner's
+ parts (stale after a model re-upload): drop them from the group, and if a group
+ becomes empty, skip it and count it as unmatched (OQ4).
+- **R2 — Planner sensitivity.** plan.py is under active tuning
+ (`2026-07-06-planner-regression-fix`, `-secured-last-and-gaskets`). Keep the new
+ mode a **separate branch** in `plan_step` so it can't perturb the fresh path;
+ add tests that pin the order-respecting behavior.
+- **R3 — Job cost.** Re-motion is roughly one motion search per step (no ordering
+ search), so it should be **cheaper** than a fresh plan — good.
+- **R4 — Partial overwrite consistency.** Use a Kysely transaction for C2 so step
+ motion updates are all-or-nothing.
+
+## Not in scope (unless requested)
+
+- Fresh-plan trigger for "Regenerate from Plan" independence (OQ3/D7).
+- A Parts-tab re-run affordance.
+- Re-motion for a subset of selected steps.
diff --git a/.ai/plans/2026-07-06-planner-regression-fix.md b/.ai/plans/2026-07-06-planner-regression-fix.md
new file mode 100644
index 0000000000..ba42bee642
--- /dev/null
+++ b/.ai/plans/2026-07-06-planner-regression-fix.md
@@ -0,0 +1,103 @@
+# Fix: planner regression from weakly-secured + sandwich changes
+
+## Context
+
+The 2026-07-06 ordering refactor (weakly-secured-last + sandwiched-gasket handling in `services/geometry/app/plan.py`) made real-model planning slower with worse results (observed on the SA Seat Rail / SA Mando & Battery Harness in-app jobs). Three first-principles causes, in likelihood order:
+
+1. **Greedy priority inversion**: `removal_priority` now tries "weakly-secured" parts first. On real models those are often the interlocked ones (cables, clips); each failure burns full tier-1+tier-2 sweeps, re-tried at the front of every scan. The greedy priority is not a preference — it schedules expensive attempts and picks flag/merge victims.
+2. **Weak-tier proxy explodes on real CAD**: fastener detection is name-only and clearance fits produce no contact pairs, so "unfastened ∧ contact_count==1" matches a large fraction of a harness. The special case becomes the common case in both greedy and topo.
+3. **Sandwich false positives corrupt collision truth**: detection matches rigid plate stacks (seen on seat-rail Part 7); each false positive grants an *isotropic* seated allowance (observed depth + 0.3mm, uncapped) to itself and partners — tunneling through a side door — and loses its support edges.
+
+Fix philosophy: keep the two principles but move all risk out of hot paths and gate everything on evidence. The topo-side preference is inert (reorders only among already-legal choices) — keep it, tightened. The greedy-side change and the isotropic/uncapped allowance are the dangerous parts — revert/gate them.
+
+Target file: `services/geometry/app/plan.py` (+ tests, spec prose). No schema/version changes (PLAN_VERSION stays 3 per Brad).
+
+On execution start, copy this plan to `.ai/plans/2026-07-06-planner-regression-fix.md`.
+
+## Changes
+
+### 1. Revert the greedy-side weak tier entirely (theory 1)
+
+`removal_priority` in `_greedy_disassembly` goes back to the pre-refactor tuple: fasteners first (0), structure (1), negated `_structural_key`, nodeId. Delete `removal_tier`, the per-call `largest_id` max, and the now-unused `fastened`/`contact_count` params from `_greedy_disassembly`'s signature and call site. Keep the `sandwiched` param (merge protection stays). Greedy order is only a witness — the topo sort owns the final order, so nothing of the "clips last" outcome is lost.
+
+### 2. Tighten `is_weakly_secured` in `_preference_topo_sort` (theory 2)
+
+Demotion additionally requires removability *evidence*:
+- `entry.tier == "linear"` (clean tier-1 straight-line removal — a terminal snap-on slides off; cable spaghetti that happens to read one contact needs L/escape/flag and is excluded)
+- `not unit.is_proxy` (bbox-proxy parts have fake contact data)
+
+Existing conditions stay: not a fastener unit, not in `fastened`, `edges[p]` empty, contact_count == 1 (group members aggregated as today). Update the docstring.
+
+### 3. Defang sandwich handling (theory 3)
+
+In `_sandwiched_parts` / consumers:
+
+- **Absolute thickness cap**: new constant `SANDWICH_MAX_THICKNESS_MM = 6.0` beside the ratio — a candidate must satisfy BOTH `thickness ≤ 0.3 × max_extent` AND `thickness ≤ 6mm`. Gaskets/seals/shims qualify; brackets and PCBs in rigid stacks don't.
+- **Squish cap**: new constant `SANDWICH_MAX_SQUISH_MM = 0.6`. If any partner pair's observed depth exceeds it, the candidate is NOT classified (no edges, no allowance, no merge exemption) — deep bites are press fits or bad CAD, not compliant squish. Real gaskets compress a few tenths.
+- **Axis-gate the allowance** (mirror `_mate_exempt`'s bore-axis gating): store the sandwich axis per partner (`_Part.seated_allowance_axes: dict[str, np.ndarray]` alongside the depth dict). In `_path_is_clear`, `_path_blockers`, and `_group_exempt`, merge a partner's allowance only when `abs(dot(direction, axis)) > 0.99`. Lateral motion is judged strictly — no more isotropic pass-through.
+- **Restore support edges**: remove the `sandwiched` skip param from `_add_support_edges`; instead call `_add_sandwich_edges` BEFORE `_add_support_edges` in `_plan_parts`. The existing cycle guard then rejects a wrong-direction support edge (sandwich edge already establishes gasket→lid), and correct support edges are no-ops. False positives keep their support edges — no constraint loss.
+
+### 4. Tests (`services/geometry/tests/test_plan.py`)
+
+- Existing 4 refactor tests must still pass (clip-last is now topo-only; gasket bites 0.4 ≤ 0.6 cap; gasket/lid motions are axis-aligned so allowances still apply).
+- New unit tests for the detection gates (call `_sandwiched_parts` directly, no planning):
+ - `test_thick_stack_is_not_a_sandwich` — 15mm plate seated between two bodies → `{}`.
+ - `test_deep_bite_is_not_a_sandwich` — thin ring with 1.5mm interference → `{}`.
+- New: `test_sandwich_allowance_is_axis_gated` — assert lateral direction doesn't receive the exemption (direct call to the merge helper or via `_path_blockers` on a gasket scenario with a lateral segment).
+
+### 5. Diagnostics + real-model verification
+
+- Write a **classification-only probe** at `.ai/scratch/geometry-probe.py` (same import style as `.ai/scratch/geometry-explain.py`): tessellate a STEP, compute pair_depths/fasteners/joints/sandwiches/contact_count, print: part count, fastener count, `fastened` size, weak-cohort size (old vs new definition), sandwich count with per-part thickness/depths/axis. No greedy — runs in ~1–2 min even on the harness model.
+- Run the probe on `~/Downloads/SA Mando & Battery Harness.step` BEFORE the fix (current working tree) to confirm theories 2/3 numerically, and AFTER to show the cohorts collapse.
+- Full pytest suite.
+- Seat-rail harness (`geometry-explain.py --sequence` twice): tiers/sequence must match the accepted baseline (24 linear / 2 group / 2 flagged, verified 29/31); the two "sandwich preference … skipped" warnings should disappear (Part 7 stack now excluded by thickness/squish caps).
+- Timed solo run of the harness model (`--step ~/Downloads/"SA Mando & Battery Harness.step" --sequence`) post-fix; sanity-check flags/tiers and wall time. (A pre-fix A/B run is optional — 20–30 min — only if the probe numbers don't already tell the story.)
+
+### 6. Docs
+
+- Re-sync the two paragraphs I added to `.ai/specs/2026-07-04-animated-work-instructions-contracts.md` (weak-secured description gains the tier-linear/non-proxy gates and loses the greedy-side claim; sandwich paragraph gains thickness/squish caps and axis gating).
+- Append to the plan artifact and add a lesson to `.ai/lessons.md`: scale-dependent ordering heuristics must be gated on a large noisy model, not just the 31-part seat rail; greedy priority changes are schedule changes (cost + flag/merge victims), not preferences.
+
+## Verification summary
+
+```bash
+cd services/geometry
+.venv/bin/python ../../.ai/scratch/geometry-probe.py --step ~/Downloads/"SA Mando & Battery Harness.step" # before + after
+.venv/bin/python -m pytest -q # all green
+.venv/bin/python ../../.ai/scratch/geometry-explain.py --sequence # ×2, baseline-identical, no sandwich warnings
+.venv/bin/python ../../.ai/scratch/geometry-explain.py --step ~/Downloads/"SA Mando & Battery Harness.step" --sequence # timed solo
+```
+
+Then re-run the two in-app jobs (user-triggered) to confirm end-to-end.
+
+## Risks
+
+- The tier-linear gate could un-demote a legitimate clip that needs a slide (tier L) — e.g. TPF119 "slide in to avoid collision". If SA-BCU clips plan as tier 2, they'd no longer demote. Mitigation: accept for now (they're still ordered late by small volume) or extend the gate to `tier in ("linear", "L")` — decide from the probe/SA-BCU evidence, default to including "L" since both tiers are verified collision-free motions. (Plan: gate on `tier in ("linear", "L")`, exclude escape/group/flagged.)
+- Axis-gating uses one axis per partner; a part sandwiched along two axes keeps only per-partner axes, which is correct since allowances are per-partner.
+- Seat-rail baseline must stay byte-identical — it's the regression gate before any real-model timing.
+
+---
+
+## Result addendum (2026-07-06, same session)
+
+**Regression fix verified end-to-end**, then two follow-on changes landed on top:
+
+1. **Performance (the "3 minutes" question):** profiled the seat rail — 86% of
+ time was pass-through contact enumeration in `_path_blockers` (53M contact
+ objects). Fixes: park discovered blockers out of the broadphase for the rest
+ of the sweep (the real win) + unregister the moving part during its own
+ sweeps (kills the synthetic-test self-flood). Seat rail 191–211s → **20–26s**
+ byte-identical; harness >30min (killed, unfinished) → **557.7s**; pytest
+ suite ~53s → ~6s.
+2. **Dependency-spine ordering + corridor-gated steps** (Brad's expected order):
+ one topo sort_key term (`0 if edges.get(node_id) else 1` after the securing
+ jump) yields rail → sliders → Part 7 → Torx 2+2 exactly, with the badge
+ group and washer+screw deferred to the tail; `buildAssemblyStepGroups`
+ (viewer) now merges simultaneous steps only when swept corridors are
+ AABB-disjoint — side-by-side screws share a step, in-line TPF119-style
+ clips each slide in on their own step.
+
+Gates: geometry pytest 30/30 (plan) + full suite green; viewer 67 tests +
+typecheck green; seat rail deterministic with tiers unchanged (24/2/2,
+verified 29/31). Known non-goal: harness flags 53/115 — cable interlock needs
+BOM unit collapsing, not ordering heuristics.
diff --git a/.ai/plans/2026-07-06-planner-secured-last-and-gaskets.md b/.ai/plans/2026-07-06-planner-secured-last-and-gaskets.md
new file mode 100644
index 0000000000..c285d2eeae
--- /dev/null
+++ b/.ai/plans/2026-07-06-planner-secured-last-and-gaskets.md
@@ -0,0 +1,130 @@
+# Planner refactor: explicit "least-secured last" + compliant sandwiched parts
+
+## Context
+
+The SA-BCU expected order exercise (seat rail BCU, 11 steps) showed the v3 planner gets the right answer in two places for reasons that won't generalize:
+
+1. **Snap-on clips (TPF119) assemble last only because they're small.** `removal_priority` and the topo `sort_key` rank structure purely by material volume + centrality. A *large* snap-on part (e.g. a big slide-on cover panel) would wrongly assemble early. The real principle: parts held only by friction/snap — nothing clamps them, nothing depends on them — assemble as late as their constraints allow.
+2. **Gaskets/seals have no handling at all.** A thin compliant part sandwiched between two flanges (SA-BCU: box rim → gasket → lid) currently risks: (a) missing/wrong support edges (bbox z-center comparison degenerates for thin parts), (b) if modeled with seated interference, becoming unremovable → `flagged` → **zero precedence edges** (topo can place it anywhere), (c) spurious blocker edges on neighbors sweeping past it, and (d) silent single-blocker rigid merge into its flange. This is very likely the root cause of the T6 caveat where the merged PCB/Box units flag ("no collision-free insertion into the sealed enclosure").
+
+Target file: `services/geometry/app/plan.py` (planner v3, 2858 lines). No API/schema changes; plan.json shape unchanged.
+
+On execution start, copy this plan to `.ai/plans/2026-07-06-planner-secured-last-and-gaskets.md` (project convention).
+
+## Design
+
+### A. Weakly-secured parts assemble last (explicit principle)
+
+New per-part signals, computed in `_plan_parts` from data that already exists:
+
+- `fastened: set[str]` — every unit appearing as a member of any `joints[f]` (mates + through-parts), built by inverting `joints` after the merge remap (plan.py:406-427).
+- `contact_count: dict[str, int]` — number of non-fastener seated pairs per unit, from `pair_depths` keys remapped through `merged_into`.
+
+**Definition (topo sort, the one that decides final order):**
+`weakly_secured(p)` = `p ∉ fasteners` ∧ `p ∉ fastened` ∧ `edges[p] == ∅` (p must-precede nothing: no sweep/joint/support edge out of it) ∧ `contact_count[p] ≤ 1`.
+
+The `edges[p] == ∅` term is what makes this safe: the seat rail sliders have an outgoing sweep edge (their insertion is blocked by Part 7's seated body), so they are *not* demoted; TPF119 clips, the marketing badge, and any glued-on terminal part have no outgoing edges and exactly one seated neighbor, so they are.
+
+Edit points:
+
+- `_preference_topo_sort` sort_key (plan.py:1005-1018): insert a `1 if weakly_secured(node_id) else 0` term between `is_securing` and `_structural_key`. Weakly-secured parts rank after everything else that's available; among themselves they still sort big→small.
+- `removal_priority` closure (plan.py:1753-1769): edges don't exist yet at greedy time, so use the pre-greedy approximation `p ∉ fastened ∧ contact_count[p] ≤ 1` as tier 0 (removed before fasteners — outermost off first), fasteners tier 1, structure tier 2. Greedy order is only a witness; the topo sort owns the final order, so the approximation being looser here is fine.
+- Thread `fastened` + `contact_count` into `_greedy_disassembly` (call site plan.py:444-455) and `_preference_topo_sort` (call site plan.py:482-495) as new keyword args with safe defaults (empty), so `.ai/scratch/geometry-explain.py`'s direct imports keep working.
+
+### B. Sandwiched compliant parts (gaskets/seals)
+
+New detection function `_sandwiched_parts(parts, pair_depths, fasteners, merged_into) -> dict[unit_id, _SandwichInfo]`, called in `_plan_parts` after the joints remap:
+
+- Candidate: non-fastener, non-proxy unit with ≥2 seated partners.
+- Sandwich axis: principal axis of the pairs' contact structure tensors (already stored per pair in `pair_depths` — winding-invariant Σn·nᵀ); pairs must agree on the axis (|dot| > ~0.9).
+- Sandwiched: partners' mean contact positions fall on *both* sides of the part's centroid along that axis. Uses contact-point positions, never normal signs (FCL normals follow winding) and never bbox z-centers (thin-part degeneracy).
+- Thin: extent along the sandwich axis ≤ ~0.3 × max lateral extent (module-top constant next to the other tolerances).
+- `_SandwichInfo` = `{axis, side_a: set, side_b: set, allowance: dict[partner_id, depth]}` where allowance = observed seated pair depth + `MATE_DEPTH_MARGIN_MM`, granted only to sandwich partners. Rationale mirrors the thread-mate precedent: the *seated state itself* proves the interference is intentional (compliant squish); the planner still never fabricates motion through parts it doesn't touch when seated.
+
+Four consumers:
+
+1. **Precedence edges** — new `_add_sandwich_edges(...)` called alongside `_add_joint_edges`/`_add_support_edges` (plan.py:480-481), same cycle-guard pattern: the side with larger total part volume (the enclosure) precedes P; P precedes the other side (the compressor/lid). Ambiguous volume tie → skip + warn.
+2. **`_add_support_edges`** (plan.py:831-899) — skip pairs involving a sandwiched part; sandwich edges own them (avoids the z-center degeneracy creating a contradictory edge that the cycle guard would resolve arbitrarily).
+3. **Seated-interference allowance** — thread a `seated_allowance: dict[str, dict[str, float]]` (symmetric: both `gasket→lid` and `lid→gasket`) through `_greedy_disassembly` → `_plan_removal`/`_plan_escape`/`_escape_blockers` → merged into the exempt dict next to `_mate_exempt` output (pattern at plan.py:677-679), and into `_derive_precedence`'s `_path_blockers` call via `extra_exempt` (plan.py:727-735). This stops the seated gasket from (a) being unremovable itself and (b) showing up as a spurious blocker of the lid's sweep.
+4. **Merge protection** — sandwiched units are skipped by the stuck single-blocker rigid merge (plan.py:1833-1891) and removed from `deep_bitten` (plan.py:432-440); a compliant part must never silently fuse into its flange.
+
+### Version bump (recommendation — veto here if unwanted)
+
+Bump `PLAN_VERSION` 3→4 in plan.py and `CURRENT_PLAN_VERSION` in `packages/viewer/src/plan.ts` (re-exported via `packages/viewer/src/steps.ts`; the jobs worker refuses stale plans and re-plans on next Generate Steps). Same precedent as the v3 bump: ordering heuristics changed, stored plans should regenerate. Two constants, no schema change.
+
+## Tasks
+
+1. Copy plan to `.ai/plans/2026-07-06-planner-secured-last-and-gaskets.md`.
+2. **Goal A**: build `fastened`/`contact_count` in `_plan_parts`; extend `removal_priority` tuple + topo `sort_key`; thread new kwargs (defaulted) through `_greedy_disassembly`/`_preference_topo_sort`. Update both functions' docstrings/comments (they state the principles verbatim).
+3. **Goal B**: `_SandwichInfo` dataclass + `_sandwiched_parts()` + `_add_sandwich_edges()`; support-edge skip; `seated_allowance` plumbing through the removal/escape/blocker call chain; merge/deep-bitten protection. New module-top constants beside `PENETRATION_TOLERANCE_MM`.
+4. **Tests** (`services/geometry/tests/test_plan.py`, synthetic trimesh like existing tests):
+ - `test_large_snap_on_clip_assembles_last` — base + small screwed-down bracket + a *larger* slide-on clip touching only the base → clip last despite bigger volume (kills the volume coincidence).
+ - `test_part_with_blocked_insertion_is_not_demoted` — slider-like part touching only the base but whose insertion path is blocked by a later part → stays early (guards the seat-rail slider case).
+ - `test_sandwiched_gasket_orders_between_flanges` — box + thin gasket + lid + screws, clean contact → sequence box < gasket < lid < screws.
+ - `test_interfering_gasket_still_plans` — same with ~0.3mm seated interference → 0 flagged, gasket not rigid-merged, same order.
+5. Version bump (plan.py + `packages/viewer/src/plan.ts`).
+6. Sync the heuristics prose in `.ai/specs/2026-07-04-animated-work-instructions-contracts.md` (and its `docs/specs/` mirror if present) — the ordering-preferences paragraph and the tolerance/allowance paragraph.
+
+## Verification
+
+```bash
+cd services/geometry && .venv/bin/python -m pytest -q # 45 existing + 4 new, all green
+```
+
+Seat-rail acceptance (constraints from `.ai/plans/2026-07-05-assembly-planner-v3.md:180-199` — rail first, sliders in first quarter, Part 7 before its 4 consecutive Torx, washer before screw, flagged ≤ 2, determinism):
+
+```bash
+cd services/geometry
+.venv/bin/python ../../.ai/scratch/geometry-explain.py --sequence # run twice, byte-identical
+.venv/bin/python ../../.ai/scratch/geometry-explain.py --edges slider
+```
+
+SA-BCU spot check (slow, leaf-soup without units — optional now; the authoritative check is the in-app "Re-run plan" after merge, which needs the stack + OPENAI key):
+
+```bash
+.venv/bin/python ../../.ai/scratch/geometry-explain.py --step "/Users/barbinbrad/Downloads/SA BCU.step" --sequence
+```
+
+Expected on SA-BCU: gasket ordered box < gasket < lid, clips last, and (if gasket interference was the cause) the previously-flagged enclosure parts get real motions.
+
+TS side (only if version bump lands):
+
+```bash
+pnpm --filter @carbon/viewer test
+pnpm exec turbo run typecheck --filter=@carbon/viewer --filter=@carbon/jobs
+```
+
+## Risks
+
+- **Seat-rail regression** is the main one; the `edges[p] == ∅` term is the mitigation, and the harness run is the gate. If sliders still demote, tighten `weakly_secured` (drop the greedy-side demotion, keep topo-side only) before touching anything else.
+- **Sandwich false positives** (e.g. a rigid spacer plate): gets ordering edges (harmless — they're correct for spacers too) but an allowance only if seated interference is actually observed, so no motion is fabricated through truly rigid geometry.
+- **Harness compatibility**: all new params are keyword-defaulted; no renames of the `_private` symbols `geometry-explain.py` imports.
+- planMs: detection is one pass over `pair_depths` (cheap); allowance adds dict lookups inside existing sampling loops. No new collision passes.
+
+---
+
+## Result (2026-07-06)
+
+All tasks complete except the version bump, which Brad vetoed mid-run
+("we don't need to maintain plan versions like this; we are on v1 for the
+foreseeable future") — `PLAN_VERSION`/`CURRENT_PLAN_VERSION` stay at 3 and
+heuristic changes are NOT version events. Stored plans persist until
+manually re-planned.
+
+- Goal A + B landed in `services/geometry/app/plan.py`; two definition
+ refinements emerged during implementation:
+ - weakly-secured requires contact_count == 1 exactly (zero structural
+ contacts = fastener-positioned cover, regular structure), and the
+ largest remaining part is exempt in greedy so fastener-less stacks
+ keep their base.
+ - seated allowances live on `_Part.seated_allowance` (consulted inside
+ `_path_is_clear`/`_path_blockers`/`_group_exempt`) instead of threading
+ a new parameter through six signatures.
+- Tests: 47 passed, 2 env-skipped (4 new ordering tests).
+- Seat rail: byte-identical to the accepted v3 baseline across two runs —
+ tiers 24 linear / 2 group / 2 flagged / 0 forced, verified 29/31,
+ sequence unchanged (~125s). Sandwich detector fired on the rigid Part 7
+ clamp stack; cycle guard correctly skipped the conflicting edges
+ (warnings only, no behavior change).
+- SA-BCU end-to-end re-plan (in-app, needs stack + OPENAI key) not run —
+ follow-up when the stack is up.
diff --git a/.ai/plans/2026-07-07-assembly-part-to-component-rename.md b/.ai/plans/2026-07-07-assembly-part-to-component-rename.md
new file mode 100644
index 0000000000..acd444f40d
--- /dev/null
+++ b/.ai/plans/2026-07-07-assembly-part-to-component-rename.md
@@ -0,0 +1,128 @@
+# Refactor: rename CAD "part" → "component" across the assembly-instructions feature
+
+## Context
+
+On the assembly-instructions page, the 3D pieces of a CAD model are called **parts**. But
+"Part" is a distinct concept in Carbon (an item type on the BOM), so the term collides and
+confuses. This refactor renames the CAD-geometry concept to **component** everywhere it
+surfaces — user-facing text, ERP code, the `@carbon/viewer` API, the DB columns/table, and
+the Python geometry service — while deliberately **keeping** "part"/"item" wherever the word
+actually refers to a Carbon BOM item (e.g. "Pick a BOM part" → "Pick a BOM **item**", the
+`itemId` FK, `bomMaterials`).
+
+Scope confirmed with the user: **everything** (DB + viewer + geometry service + shared viewer
+labels); BOM-item references stay accurate.
+
+**Nothing is merged yet**, so this is a straight rename with no migration/deploy gymnastics:
+- Edit the **existing** assembly migrations **in place** (rename columns/table directly in their
+ `CREATE TABLE` statements) — no rename migration, no idempotency guards, no data back-compat.
+ The user rebuilds the database from scratch afterward.
+- The app→service `POST /plan` request carries no "part" keys anyway (`options.units[].nodeIds`,
+ `sequence`), and there are no stored artifacts to preserve — so app + service just adopt the new
+ key names together. No lockstep/back-compat shim needed.
+
+## Canonical naming map
+
+CAD-geometry → component (rename):
+
+| Old | New |
+|---|---|
+| `partNodeIds` (DB col, validators, types, vars) | `componentNodeIds` |
+| `partCount` (DB col, graph.json, convert/status wire, viewer `AssemblyGraph`) | `componentCount` |
+| `plan.parts` (plan.json dict) | `plan.components` |
+| `PartGroup` (viewer type) / `groupPartNodeIds` (viewer fn) | `ComponentGroup` / `groupComponentNodeIds` |
+| `AssemblyPlanPart` / `AssemblyStepGroup.partNodeIds` / `NamedUnit.partNodeIds` / `AssemblyStep.partNodeIds` | `AssemblyPlanComponent` / `.componentNodeIds` (all) |
+| `assemblyPartMapping` (table) + `assemblyPartMapping_*_idx` | `assemblyComponentMapping` (+ indexes) |
+| svc `getAssemblyPartMappings` / `upsertAssemblyPartMapping` / `deleteAssemblyPartMapping` / `autoMatchAssemblyParts` / `updateAssemblyStepParts` | `…ComponentMapping(s)` / `autoMatchAssemblyComponents` / `updateAssemblyStepComponents` |
+| path segments `part-mappings`, `steps/parts`; helpers `newAssemblyPartMapping`, `deleteAssemblyPartMapping`, `autoMatchAssemblyParts`, `assemblyInstructionStepParts` | `component-mappings`, `steps/components`; `…ComponentMapping`, `autoMatchAssemblyComponents`, `assemblyInstructionStepComponents` |
+| route files `$id.part-mappings.*.tsx`, `$id.steps.parts.$stepId.tsx` | `$id.component-mappings.*.tsx`, `$id.steps.components.$stepId.tsx` |
+| ERP UI ids: `StepPartsEditor`, `onSelectParts`, `onHighlightParts`, `onHideParts`, `onRemoveParts`, `draftPartNodeIds`, `isAddingParts`, `partGroups`, `PartColorSwatch`, `PartDetails`, `BomRow` | `StepComponentsEditor`, `onSelectComponents`, `onHighlightComponents`, `onHideComponents`, `onRemoveComponents`, `draftComponentNodeIds`, `isAddingComponents`, `componentGroups`, `ComponentColorSwatch`, `ComponentDetails`, `ComponentRow` |
+| Python internal `_Part`, `PlannedPart`, `plan_parts_payload`, `part_count`, `part_node_ids` | `_Component`, `PlannedComponent`, `plan_components_payload`, `component_count`, `component_node_ids` |
+
+**KEEP as-is** (Carbon BOM item / not CAD): `itemId`, the mapping's target item, `bomMaterials`,
+`geometryHash`, `nodeId(s)`, `options.units[].nodeIds`, `plannedCount`, `sequence`, and the
+`AssemblyBomTree` / `AssemblyStepBom` names (they concern the **BOM** mapping — Bill of Materials
+is a real, separate concept; only the CAD-part sub-identifiers inside them rename).
+
+Display-string BOM exceptions: `"Pick a BOM part"` → `"Pick a BOM item"`; `"Match parts to BOM items"`
+→ `"Match components to BOM items"`; `"… mapped to BOM"` unchanged.
+
+## Execution order (each step verifiable before the next)
+
+### 1. Database migrations — edit existing files IN PLACE (user rebuilds)
+Edit the `CREATE TABLE` / column definitions directly in:
+- `20260610143217_assembly-foundations.sql` — `modelUpload.partCount` → `componentCount`.
+- `20260610151942_assembly-instructions.sql` — `assemblyInstructionStep.partNodeIds` → `componentNodeIds`.
+- `20260611134652_assembly-editor-parity.sql` — `assemblyUnit.partNodeIds` → `componentNodeIds`.
+- `20260611194237_assembly-part-mappings.sql` — table `assemblyPartMapping` → `assemblyComponentMapping`,
+ the three `assemblyPartMapping_*_idx` index names, and all in-file references (RLS `CREATE POLICY … ON`,
+ grants). Optionally rename the file → `…_assembly-component-mappings.sql` for tidiness.
+- No new migration, no idempotency guards (these are the authoritative CREATE statements).
+- After the user rebuilds: `pnpm run generate:types` (never hand-edit `packages/database/src/types.ts`;
+ don't commit the unrelated 55k-line local diff — see `reference_types_gen_cloud_db`).
+
+### 2. `@carbon/viewer` (types + API + labels)
+- Rename exports/fields across `graph.ts` (`PartGroup`→`ComponentGroup`, `groupPartNodeIds`→
+ `groupComponentNodeIds`, `AssemblyGraphIndex.groups`), `types.ts` (`AssemblyStep.componentNodeIds`,
+ `AssemblyGraph.componentCount`), `plan.ts` (`AssemblyPlanComponent`, `AssemblyPlan.components`,
+ `groups[].componentNodeIds`, `AssemblyStepGroup.componentNodeIds`), `describe.ts`
+ (`NamedUnit.componentNodeIds`), `steps.ts`, `motion.ts`, `fallback.ts`, and the `index.ts` barrel.
+- `AssemblyPlayer.tsx` viewer labels → "Show future components ghosted" / "Hide future components" /
+ "Show all components solid" (+ the "plan as one component" docstring wording).
+- Verify: `pnpm --filter @carbon/viewer typecheck && test` (update `plan.test.ts` fixtures to new keys).
+
+### 3. ERP services + models + validators (`apps/erp/app/modules/production/`)
+- `production.models.ts`: rename `partNodeIds` in the 3 validators; `assemblyInstructionStepPartsValidator`
+ → `assemblyInstructionStepComponentsValidator`.
+- `production.service.ts`: rename functions (`updateAssemblyStepComponents`, `getAssemblyComponentMappings`,
+ `upsertAssemblyComponentMapping`, `deleteAssemblyComponentMapping`, `autoMatchAssemblyComponents`),
+ every `.from("assemblyComponentMapping")`, and `componentNodeIds` column refs; leave `itemId`/BOM logic.
+- `types.ts`: `AssemblyPartMapping` → `AssemblyComponentMapping` (derives via `Awaited<ReturnType<…>>`,
+ follows automatically — `feedback_fullstack_type_chain`). Update the module `index.ts` barrel.
+
+### 4. `@carbon/jobs` Inngest workers
+- `assembly-plan.ts` / `plan-units.ts` (`.select("componentNodeIds")`, `PlanUnit`), `assembly-convert.ts`
+ (`componentCount`), `generate-assembly-steps.ts` (`group.componentNodeIds` → DB `componentNodeIds`).
+ Keep outgoing `options.units[].nodeIds`. Verify: `pnpm --filter @carbon/jobs typecheck`.
+
+### 5. ERP routes + path helpers + UI
+- `apps/erp/app/utils/path.ts`: rename the 4 helpers + URL segments (`part-mappings`→`component-mappings`,
+ `steps/parts`→`steps/components`).
+- Rename route files under `apps/erp/app/routes/x+/assembly+/`: `$id.part-mappings.*.tsx` →
+ `$id.component-mappings.*.tsx`, `$id.steps.parts.$stepId.tsx` → `$id.steps.components.$stepId.tsx`;
+ update internal action/validator refs.
+- UI (`AssemblyBomTree.tsx`, `AssemblyInstructionProperties.tsx`, `AssemblyInstructionExplorer.tsx`,
+ `AssemblyStepBom.tsx`, `AssemblyStepMaterials.tsx`, `$id.tsx`, MES `Assembly.tsx`): rename identifiers
+ per the map AND update every **display string** (tab "Components", "Search components",
+ "Add components", counts `{n} component{s}`, empty states, aria/tooltips) — with the **BOM exceptions**.
+- Verify: `pnpm exec turbo run typecheck --filter=erp --filter=mes`; `pnpm run lint`.
+
+### 6. Python geometry service (`services/geometry/`)
+- `schemas.py`/`main.py`: response `partCount` → `componentCount` (convert + status). `plan.py`: emit
+ `plan["components"]` (was `parts`), `groups[…]["componentNodeIds"]`; rename internal
+ `_Part`/`PlannedPart`/`plan_parts_payload`/`part_count`. `convert.py`: graph.json `componentCount`.
+ Keep request-side `units[].nodeIds`/`sequence`.
+- Verify: `services/geometry` tests (`test_plan.py`) pass.
+
+### 7. Docs / rules / specs
+- Update the `/plan` + `/convert` contract field names in
+ `.ai/specs/2026-07-04-animated-work-instructions-contracts.md`,
+ `.ai/specs/2026-07-06-geometry-service-deployment.md`, the production `AGENTS.md`, and any curated
+ `docs/` page describing assembly parts (`feedback_keep_docs_in_sync`).
+
+## Verification (end-to-end, after the user rebuilds the DB)
+- `generate:types` clean; scoped typechecks (`@carbon/viewer`, `@carbon/jobs`, `erp`, `mes`) green;
+ `pnpm run lint`; viewer + geometry unit tests pass.
+- Grep guard: no remaining CAD-sense `partNodeIds` / `PartGroup` / `assemblyPartMapping` / `plan.parts`;
+ remaining "part" hits are only BOM/item (`itemId`, `bomMaterials`, "BOM part/item").
+- Browser (Electric X session, fresh model after rebuild): create/open an assembly → Parts panel reads
+ "Components"; select components, add a step, plan-as-one-component, hide/show; convert + re-run motion
+ planning end-to-end against the renamed geometry service; steps render.
+
+## Risks / notes
+- Table rename touches RLS/indexes — policies are named `production_*` and don't reference the table
+ name in SQL, so they carry over; still confirm all four policies + three indexes read
+ `assemblyComponentMapping` after the edit.
+- Since migrations are edited in place, the change only takes effect on a DB rebuild — the user owns that
+ step; `generate:types` runs after.
+- Land DB edits + all code together (one branch); a partial rename would break typechecks by design.
diff --git a/.ai/plans/2026-07-09-assembly-sequence-connectivity.md b/.ai/plans/2026-07-09-assembly-sequence-connectivity.md
new file mode 100644
index 0000000000..59802c8b68
--- /dev/null
+++ b/.ai/plans/2026-07-09-assembly-sequence-connectivity.md
@@ -0,0 +1,200 @@
+# Assembly sequence from first principles: connected growth from a real base
+
+## Context
+
+Two instructions exist for the same BCU model (`5xnsD-LXJzfYduUs1GUIz`, 431 leaves):
+`Sync 3 - SA BCU - Auto Generated` (`d97h24n5i0h4l3vdo3kg`, from the fresh planner
+run) and `Sync 3 - SA BCU - Fixed` (`d97h5675i0h4vsndo3rg`, Brad's hand-authored
+order — the ORDER is the reference; its motions are none/flagged and explicitly
+not to be trusted). The auto order is nonsense on screen: the **seal** is the
+base, the **lid** mounts onto the floating seal, seven lid screws drive into
+nothing, the LQFP chip (13.7mm from anything placed) and the PCB (14.3mm) appear
+in empty space, the **Electronics Box — the true anchor — arrives 9th, flagged**,
+and the 409 PCB components come dead last.
+
+Root causes, each verified empirically against the real model (mesh-distance
+audit of both step sequences; greedy/topo-sort code reading):
+
+1. **Base selection is an accident of the greedy loop.** The base is whatever
+ part survives removal last (`_greedy_disassembly`, plan.py:2447–2460). On an
+ enclosure model the loop deadlocks (box can't escape past its contents, the
+ compressed seal can't escape past box+lid), flags the box
+ (plan.py:2616–2647), which frees lid then seal — so the SEAL becomes base and
+ the box a flagged afterthought.
+2. **Nothing constrains a step to touch the already-placed set.** The topo sort
+ (`_preference_topo_sort`, plan.py:1523–1694) has soft support/sandwich edges
+ but no connectivity requirement; forward verification
+ (`_verify_sequence`, plan.py:1697) checks collision only. Floating installs
+ (LQFP at 13.7mm, PCB at 14.3mm) pass every gate.
+3. **Flagged parts get no ordering anchor.** They land at their reversed removal
+ position with no precedence edges (plan.py:2627, 2649) — the box's
+ `blocked_by` (its entire contents) is recorded but never used for order.
+4. **The contact/adjacency world only sees interpenetrating pairs.**
+ `_seated_pair_depths` (plan.py:1776) feeds support edges, sandwich detection,
+ and contact counts from FCL *collision* contacts. Real CAD gaps — the LQFP
+ sits 0.05mm above its pads — are invisible, so clean models order blind.
+5. **Unit derivation splits the populated PCB.** `deriveAssemblyUnits`
+ (packages/utils/src/assembly-units.ts:130) groups leaves by their assigned
+ flattened-BOM item; the 409 footprints collapsed into one unit but the board
+ itself (`minimalBCU_gen2_PCB`), the `C-1-776163-1` connector, and the LQFP
+ were assigned to their own qty-1 single-leaf lines and stayed out. Per Brad:
+ Fixed steps 2 + 3 (swarm + board/connector) must be ONE group. This also
+ feeds ordering: the swarm alone doesn't touch the box (6.0mm), but the board
+ does — group them and the unit mates with the box bosses.
+
+First principles for an instructional assembly animation:
+- **The base is the part everything mounts into** — the most-connected, most
+ massive structural part (the enclosure), not the last part a disassembler
+ could pry out.
+- **Every step must mate with the already-placed assembly** (grow a connected
+ assembly). "Mate" tolerates real CAD clearances (≈0.5mm), not just
+ interpenetration.
+- **An interlocked core (box⇄contents⇄seal⇄lid deadlock) anchors at its
+ enclosure**, with the compliant member (seal) fading in on the rim — never
+ the other way round.
+
+Non-goals / constraints:
+- `PLAN_VERSION` stays frozen (heuristic changes are never version events).
+- Fixed-sequence re-motion mode (`_plan_fixed_sequence`) is untouched — order is
+ caller-given there.
+- Per `.ai/lessons.md`: no new logic in `removal_priority` (it schedules
+ expensive sweeps); ordering logic belongs in edge derivation + topo sort; no
+ new collision *allowances*; and every heuristic must be gated on the large
+ noisy model (this BCU) plus the seat-rail regression baseline.
+
+## Tasks
+
+### Task 1 — Near-contact adjacency graph (ordering world)
+
+File: `services/geometry/app/plan.py`.
+
+- New helper `_ordering_adjacency(parts, pair_depths, trimesh_mod, contact_mm=0.5)`:
+ start from `pair_depths` pairs, then add near-contact pairs — candidate pairs
+ from an AABB prefilter (boxes inflated by `contact_mm`), confirmed with an
+ FCL distance query (`min_distance` between cached BVHs, cf. `_mesh_bvh`
+ plan.py:2654). Returns `dict[node_id, set[node_id]]` at the UNIT level
+ (respecting `merged_into` / group units the way `_add_support_edges` does).
+- Profile on the BCU before adopting (lesson: cProfile first): the AABB
+ prefilter must keep confirmed distance queries in the low thousands.
+- Feed it to: contact counts for `is_weakly_secured` (replacing the
+ penetration-only `contact_count`), Task 2's base selection, and Task 3's
+ connectivity constraint. Support/sandwich edge derivation keeps using
+ `pair_depths` normals/depths (they need contact geometry, not just adjacency).
+
+### Task 2 — Principled base selection
+
+File: `services/geometry/app/plan.py` (`_plan_parts`, after greedy + before topo
+sort, ~line 610–660).
+
+- Candidates: the greedy base ∪ flagged non-fastener structural parts.
+- Score by (adjacency degree, volume) — the enclosure wins on both axes. Retag:
+ winner becomes `tier="base"` (motion none, confidence high, sequence head);
+ the demoted ex-base keeps no motion and becomes `tier="flagged"` with
+ `blocked_by` = its sandwich/support partners (honest: it fades in at its
+ ordered position — for the BCU the seal fades onto the box rim, matching the
+ Fixed order).
+- Only rescore when the greedy base is NOT the degree/volume winner by a clear
+ margin (e.g. winner ≥ 2× on both) — don't churn models the greedy already
+ gets right (seat rail's Part 7 must stay base).
+
+### Task 3 — Connectivity-constrained topo sort
+
+File: `services/geometry/app/plan.py` (`_preference_topo_sort`, Kahn loop
+~line 1666).
+
+- Restrict each pick to `available ∩ touches(placed)` using Task 1's adjacency
+ (a unit touches if ANY member is adjacent to ANY placed member). If the
+ intersection is empty (genuinely disconnected islands — fixtures, reference
+ geometry), fall back to full `available`, anchor the island by its own
+ (degree, volume) maximum, and append a warning (`log`-visible in plan.json
+ warnings; no silent caps).
+- Existing hard edges and the 8-tuple soft preference key stay; connectivity is
+ a filter on candidates, not a new score component.
+- Expected BCU order: box → populated-PCB unit → PCB screws → seal → lid → lid
+ screws → TPF119s — the Fixed order, modulo step merging.
+
+### Task 4 — Populated-subassembly units (board + connector + footprints as one)
+
+Files: `packages/utils/src/assembly-units.ts` (`deriveAssemblyUnits`),
+`packages/jobs/src/inngest/functions/tasks/plan-units.ts`,
+`packages/utils/src/assembly-units.test.ts`.
+
+- Group leaves by the **top-most Make-subassembly ancestor** of their assigned
+ BOM line instead of the leaf line itself, so the bare board, the connector,
+ and the chips all collapse into the PCB-assembly unit alongside the 409
+ footprints (collapse rule stays: ancestor quantity ≤ 1 and ≥ 2 leaves).
+ Requires the flattened BOM's parent chain — check the shape
+ `getFlattenedBomMaterials` returns and what `plan-units.ts` already loads;
+ extend the loader if the parent path isn't present.
+- Keep authored units as absolute overrides (unchanged precedence).
+- Unit test: BCU-shaped fixture — footprint leaves on the child line + board
+ leaf on the bare-board line under the same Make parent → one unit; two
+ screws on a qty-8 line → separate bodies (unchanged).
+
+### Task 5 — Acceptance + regression harness
+
+Files: `services/geometry/tests/test_plan.py` (synthetic), promote
+`.ai/scratch/geometry-bcu-acceptance.py` patterns into a repeatable check
+(scratch is fine for the harness itself; the synthetic tests are the committed
+gate).
+
+- Synthetic pytest: enclosure deadlock fixture (open box + content + compliant
+ seal + lid, subdivided meshes per the sliding-contact lesson) → asserts base
+ = box, seal fades (flagged) between box and lid, and **no step installs
+ without adjacency to the placed set**.
+- Synthetic pytest: two disconnected islands → both anchored, warning emitted.
+- Real-model acceptance (manual, documented in the plan run log): plan the
+ Sync-3 BCU STEP with Task-4 units; assert zero FLOATING steps under the
+ mesh-distance audit (script from this investigation), base = Electronics
+ Box, and step-collapsed order ≈ Fixed reference (box; PCB unit; 2.5mm screws;
+ seal; lid; 4mm screws; TPFs).
+- Seat-rail regression: fresh-plan the seat rail model; sequence unchanged
+ (Part 7 base) and all motions still verified.
+- Run the classification probe (`.ai/scratch/geometry-probe.py`) on the BCU and
+ eyeball the new adjacency degrees + any sandwich detections before shipping
+ (lesson: gate on the large noisy model).
+
+## Verification
+
+1. `cd services/geometry && .venv/bin/python -m pytest tests/ -q` — all green,
+ including the new enclosure/connectivity tests.
+2. BCU acceptance run (planner on the real STEP + mesh-distance audit): 0
+ floating steps, box base, order matches Fixed within grouping.
+3. Seat-rail fresh plan unchanged.
+4. `pnpm --filter @carbon/utils test && pnpm exec turbo run typecheck
+ --filter=@carbon/utils --filter=@carbon/jobs` for Task 4.
+5. End-to-end: delete the Auto instruction's steps, re-run Generate Steps
+ against a fresh plan, and browser-verify the playback builds box-outward
+ with no floating parts (dev stack + `/auth`; Minimal X membership fixture
+ already in place).
+
+## Implementation notes (as built — deviations from the tasks above)
+
+- Task 2 grew: base candidacy is ALL structural units (not just flagged ones —
+ mesh-source variance can hand the greedy base to anything), margin is
+ degree-dominant (1.5x degree + 0.5x volume sanity; a thin-walled box loses
+ mesh volume to a potted component blob).
+- Fastener classification fixes fell out of the BCU acceptance: "pin" removed
+ from `FASTENER_NAME_RE` (connector pin counts — "Electronics Box - 36 Pin"
+ classified the enclosure as hardware and inverted the whole sequence),
+ plurals now match ("…Self Tapping Screws" never classified before), and a
+ size sanity gate (`max(100mm, 0.35 × assembly diagonal)`) keeps structure
+ structural.
+- Caller units are `protected` through the greedy: they never rigid-merge into
+ another part, never absorb riders, and never dissolve into extracted groups.
+- Flagged parts get their `blocked_by` recomputed against the FULL seated
+ assembly (greedy-time blockers reflect a half-emptied world) and a
+ fade-before-blockers SORT PREFERENCE (a hard edge version flooded the DAG on
+ servo models and forced mid-air picks).
+- Support + sandwich orderings moved from hard DAG edges to a SOFT graph
+ (sort preference): gravity-stacking edges were forcing the far end of
+ hanging pairs before the end that touches the assembly.
+- Added `_connectivity_repair`: a final connectivity-first stable reinsertion
+ over the sorted order; it may violate derived edges deliberately — forward
+ verification demotes any now-colliding insertion to a fade-in (a fade-in
+ attached to the assembly beats an animation into empty space).
+- Acceptance results: seat rail 0 floating steps (was 2 + wrong base), BCU
+ matches the hand-fixed reference (box → PCB unit → screws → TPFs → chip →
+ PCB screws → seal → lid), Packing Arm 10 → 4 floating steps — the residual
+ 4 are ≤12mm ball-joint pose gaps inside a linkage chain the CAD models
+ detached (plus unit-membership blind spots in the leaf-level audit).
diff --git a/.ai/plans/2026-07-10-geometry-rs-implementation.md b/.ai/plans/2026-07-10-geometry-rs-implementation.md
new file mode 100644
index 0000000000..887bdfcd02
--- /dev/null
+++ b/.ai/plans/2026-07-10-geometry-rs-implementation.md
@@ -0,0 +1,838 @@
+# Geometry Service Rust Rewrite — implementation plan
+
+**Spec:** .ai/plans/2026-07-10-geometry-service-rust-rewrite.md (feasibility plan; §9 decisions resolved — see Locked Decisions)
+**Research:** embedded in the spec (§1 ground truth, ecosystem survey)
+**Branch:** `feat/geometry-rs` (create from `main`)
+**Executor:** Claude Opus — this plan is self-contained; no session memory assumed.
+
+## Locked decisions (do not re-litigate)
+
+1. `/plan` consumes the **GLB + graph.json** that `/convert` produced (signed GET URLs), not the STEP file. New payload shape, new service.
+2. The OCCT cxx bridge is **vendored in-repo** at `services/geometry-rs/crates/occt-bridge`. No fork of opencascade-rs; depend on `occt-sys` for the OCCT build only.
+3. **No PyO3 phase 0.** Straight to Phase A.
+4. New code lives at `services/geometry-rs/` during transition. Python `services/geometry/` stays untouched and running until the final cutover tasks.
+5. Python planner semantics are **frozen** for the duration of the port. If `services/geometry/app/plan.py` changes on `main` mid-port, STOP and report — goldens must be re-based deliberately.
+
+## Rust conventions (apply to every task)
+
+From `.agents/skills/rust-best-practices` (read `references/chapter_01.md`, `chapter_04.md`, `chapter_05.md` before writing code):
+
+- Errors: `thiserror` enums in library crates (`planner`, `converter`, `glb`, `geometry-types`, `occt-bridge`); `anyhow` only in the `server` binary.
+- **Never `unwrap()`/`expect()` outside `#[cfg(test)]`.** OCCT and mesh data are hostile inputs.
+- `&str`/`&[T]` parameters over owned types; no clones in loops; iterators over manual index loops where clarity allows.
+- Test names describe behavior: `seated_pair_depths_reports_max_penetration_for_overlapping_boxes()`.
+- Lint gate for every task: `cargo clippy --all-targets --locked -- -D warnings` must pass.
+- Use the `nalgebra` version re-exported by parry3d (`use parry3d::na`) — never a separately-pinned nalgebra (version skew breaks the math types).
+- `//` comments only for non-obvious *why* (mirrors repo-wide comment rule).
+
+## Hard rules from `.ai/lessons.md` (encoded as task constraints, but read them: lines 114–220)
+
+- **Never fabricate a motion.** No tier-4 "forced removal". Unsolvable part ⇒ `motion: "none"` + `blockedBy` + warning.
+- **Tolerance ≪ sample spacing.** `PENETRATION_TOLERANCE_MM = 0.15` vs `MAX_SAMPLE_SPACING_MM = 2.0` — allowances are pair-scoped and axis-gated, never global.
+- **Fail-closed heuristics.** Classification with out-of-range evidence rejects; it never grants an allowance.
+- **BVH per mesh, built once.** Never rebuild per query. "Excluding" a part during its own sweep = unregister the same collision object from the broadphase (rebuilds nothing), re-register after. Blocker discovered mid-sweep ⇒ unregister for the rest of that sweep.
+- **Fastener names:** no ambiguous single tokens (`pin` is out); name match + physical sanity cap (`max(100mm, 0.35 × assembly diagonal)`).
+- **GLB↔graph join must be validated by bbox** against graph.json (authoritative), asserting full coverage with max error < 1 mm.
+
+---
+
+## Progress
+
+- [ ] Task 1: Scaffold the cargo workspace
+- [ ] Task 2: Wire types crate (`geometry-types`)
+- [ ] Task 3: Fixture generation script (Python-side, emits GLB/graph/STEP test data)
+- [ ] Task 4: GLB reader with meshopt decode (`glb` crate, read half)
+- [ ] Task 5: SPIKE — meshopt quantization error vs penetration tolerance (GO/NO-GO gate)
+- [ ] Task 6: Planner scaffolding — constants, `Component`, world-part collection
+- [ ] Task 7: Parity tracker (`PARITY.md`) enumerating all Python plan tests
+- [ ] Task 8: Collision layer — broadphase manager + calibration suite
+- [ ] Task 9: Seated pair depths + ordering adjacency
+- [ ] Task 10: Fastener classification
+- [ ] Task 11: Rigid merge + embedded pairs
+- [ ] Task 12: Fastener ring joints
+- [ ] Task 13: Sandwich detection
+- [ ] Task 14: Removal planning — tier 1 linear + tier 2 "L"
+- [ ] Task 15: Tier 3 escape BFS + group removal
+- [ ] Task 16: Greedy disassembly loop + base re-selection
+- [ ] Task 17: Precedence DAG, preference topo sort, forward verification
+- [ ] Task 18: Fixed-sequence mode + units
+- [ ] Task 19: `plan_step` orchestration + plan.json v3 output parity
+- [ ] Task 20: Determinism test, then rayon parallelization
+- [ ] Task 21: Server binary — axum `/health`, `/plan`, `/plan/{jobId}`
+- [ ] Task 22: Shadow-comparison harness + large-noisy-model gate
+- [ ] Task 23: Jobs-side switch — `assembly-plan.ts` calls the Rust planner
+- [ ] Task 24: Dev-stack wiring for the Rust planner
+- [ ] Task 25: `occt-bridge` crate — build skeleton + exception guards
+- [ ] Task 26: Bridge surface — STEP/XCAF document read
+- [ ] Task 27: Bridge surface — tessellation, volume, bbox, colors
+- [ ] Task 28: Converter crate — XCAF walk, nodeIds, graph.json parity
+- [ ] Task 29: GLB writer (`glb` crate, write half)
+- [ ] Task 30: meshopt encode pipeline (replaces gltf-transform)
+- [ ] Task 31: Server `/convert` route + endpoint tests
+- [ ] Task 32: Rust fixture generator (drop Python from geometry-rs CI)
+- [ ] Task 33: Converter parity gate (Python vs Rust on fixtures + real STEP)
+- [ ] Task 34: Dockerfile + CI workflow
+- [ ] Task 35: Full cutover + Python removal (**requires user approval**)
+
+## Dependencies
+
+- Tasks 1→2→{3,4}→5 are strictly sequential. **Task 5 is a GO/NO-GO gate.**
+- Tasks 6–8 after 5. Tasks 9–13 depend on 8; 9 must precede 10–13 (they consume pair depths). Tasks 10, 11, 12, 13 are mutually independent (parallelizable).
+- 14→15→16→17→18→19→20 sequential. 21 needs 19. 22 needs 21. 23 needs 22 pass. 24 needs 23.
+- Phase B: 25→26→27→28→29→30→31; 32 after 26; 33 needs 31+32. Phase B can start any time after Task 1 (independent of Phase A beyond scaffolding) if parallel capacity exists.
+- 34 needs 31. 35 needs 22 AND 33 green + user sign-off.
+
+---
+
+## Task 1: Scaffold the cargo workspace
+
+**Depends on:** none
+**Files:**
+- Create: `services/geometry-rs/Cargo.toml` (workspace)
+- Create: `services/geometry-rs/rust-toolchain.toml`
+- Create: `services/geometry-rs/.gitignore` (`/target`)
+- Create: `services/geometry-rs/crates/geometry-types/{Cargo.toml,src/lib.rs}`
+- Create: `services/geometry-rs/crates/glb/{Cargo.toml,src/lib.rs}`
+- Create: `services/geometry-rs/crates/planner/{Cargo.toml,src/lib.rs}`
+- Create: `services/geometry-rs/crates/server/{Cargo.toml,src/main.rs}`
+
+**Steps:**
+1. Verify toolchain: `rustc --version`. If rustc is missing or < 1.80, STOP and report — do not install toolchains silently.
+2. Workspace `Cargo.toml`: `[workspace]` with `members = ["crates/*"]`, `resolver = "2"`. Central `[workspace.dependencies]`: `serde = { version = "1", features = ["derive"] }`, `serde_json = "1"`, `thiserror = "2"`, `parry3d-f64 = "0.29"` (f64 — the Python planner is float64 throughout; f32 would shift every tolerance), `rstar = "0.13"`, `meshopt = "0.6"`, `sha1 = "0.10"`, `hex = "0.4"`, `rayon = "1"`, `tokio = { version = "1", features = ["full"] }`, `axum = "0.8"`, `reqwest = { version = "0.12", features = ["stream"] }`, `anyhow = "1"`, `dashmap = "6"`, `tracing = "0.1"`, `tracing-subscriber = "0.3"`. If a pinned version doesn't resolve, use the nearest compatible latest and note it in the commit message.
+3. Workspace lints in root `Cargo.toml`:
+ ```toml
+ [workspace.lints.clippy]
+ unwrap_used = "deny"
+ expect_used = "deny"
+ [workspace.lints.rust]
+ missing_docs = "allow"
+ ```
+ Each crate adds `[lints] workspace = true`. In test modules, use `#[allow(clippy::unwrap_used, clippy::expect_used)]` at the module top.
+4. `rust-toolchain.toml`: `[toolchain] channel = "stable" components = ["rustfmt", "clippy"]`.
+5. Each crate compiles empty (`lib.rs` with `//! doc line`; `server/src/main.rs` printing nothing, returning `Ok(())` from `fn main() -> anyhow::Result<()>`).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo build --locked 2>&1 | tail -2 && cargo clippy --all-targets --locked -- -D warnings 2>&1 | tail -2
+# Expected: "Finished `dev` profile" twice, zero warnings/errors
+```
+
+**Out of scope:** occt-bridge and converter crates (Phase B, Task 25). No CI workflow yet (Task 34).
+
+## Task 2: Wire types crate (`geometry-types`)
+
+**Depends on:** Task 1
+**Files:**
+- Create: `services/geometry-rs/crates/geometry-types/src/{graph.rs,plan.rs,wire.rs,lib.rs}`
+- Copy from (precedent): `packages/viewer/src/types.ts` (graph + motion types), `packages/viewer/src/plan.ts` (plan v3), `services/geometry/app/schemas.py` (wire request/response)
+
+**Steps:**
+1. `graph.rs`: `AssemblyGraph { version: u32 /* =1 */, unit: String /* "mm" */, source_unit: String, component_count: u32, root: AssemblyGraphNode }`; `AssemblyGraphNode { node_id, name, is_assembly, geometry_hash: Option<String>, transform: [f64; 16] /* col-major */, bbox: Bbox { min: [f64;3], max: [f64;3] }, volume: Option<f64>, color: Option<[f32;4]>, children: Vec<AssemblyGraphNode> }`. All types `#[derive(Debug, Clone, Serialize, Deserialize)]` + `#[serde(rename_all = "camelCase")]`.
+2. `plan.rs`: mirror `packages/viewer/src/plan.ts` exactly — `AssemblyPlan` (version 3, unit "mm", `sequence: Vec<String>`, `components: BTreeMap<String, PlannedComponent>` — **BTreeMap, not HashMap**, for deterministic JSON key order), `Motion` as a `#[serde(tag = "type")]` enum with variants `linear`, `l` (serde rename `"L"`), `helix`, `path`, `none`, plus `groups`, `warnings`, per-component `confidence/tier/verified/groupId/mergedInto`. Read the TS file field-by-field; every field present there must exist here.
+3. `wire.rs`: `PlanRequest` (NEW shape — this is the contract change): `{ jobId: String, source: PlanSource { glbUrl: String, graphUrl: String }, options: PlanOptions }`. `PlanOptions` ports `services/geometry/app/schemas.py` `PlanOptions` verbatim: `linearDeflection=0.1, angularDeflection=0.5, clearance=0.5, pathSamples=60, units: Option<Vec<PlanUnit>>, sequence: Option<Vec<Vec<String>>>` with defaults via `#[serde(default = "...")]`; `PlanUnit { id, name: Option<String>, nodeIds }`. Also `PlanStartResponse`, `PlanStatusResponse`, `PlanStats { planMs, tiers: BTreeMap<String, u32>, warnings, verifiedCount }`, `HealthResponse` — mirror schemas.py field-for-field, camelCase on the wire.
+4. Reject empty `sequence` groups on deserialize (custom `Deserialize` or a `validate()` method returning `Result<(), TypesError>`), matching the Pydantic `field_validator`.
+5. Tests: round-trip a hand-written graph.json sample and a plan.json v3 sample (embed as `include_str!` string literals — take real output shapes from `packages/viewer/src/plan.ts` doc comments and `services/geometry/tests/test_convert.py` expectations); assert unknown fields are ignored (serde default behavior) and camelCase renames hold (`assert!(json.contains("\"nodeId\""))`).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p geometry-types 2>&1 | tail -3
+# Expected: "test result: ok." with 0 failed
+```
+
+**Out of scope:** ConvertRequest/Response wire types (Phase B, Task 28 adds them to this crate).
+
+## Task 3: Fixture generation script (Python-side)
+
+**Depends on:** Task 1
+**Files:**
+- Create: `services/geometry-rs/scripts/make_fixtures.py`
+- Copy from (precedent): `services/geometry/tests/fixtures/make_fixtures.py` (STEP generation), `services/geometry/app/convert.py` (`convert_step`), `services/geometry/app/optimize.py` (`compress_glb`)
+
+**Steps:**
+1. Script runs with the Python service's venv: it imports `app.convert.convert_step` and `app.optimize.compress_glb` via `sys.path.insert(0, "../geometry")` (adjust to actual relative path from the script's location).
+2. It generates the three STEP fixtures the Python tests use (`box.step`, `plates.step`, `nested.step` — reuse the functions in `services/geometry/tests/fixtures/make_fixtures.py`) into `services/geometry-rs/fixtures/`, then runs `convert_step` on each producing `<name>.glb` + `<name>.graph.json`, then `compress_glb` producing `<name>.meshopt.glb`. Keep BOTH compressed and uncompressed GLBs — Task 5 needs the pair.
+3. Add `services/geometry-rs/fixtures/` to `services/geometry-rs/.gitignore` (generated, never committed — repo rule: no binary files).
+4. Rust tests that need fixtures must `skip` cleanly when `fixtures/` is absent (check path, print `"fixtures missing — run scripts/make_fixtures.py"`, return early). Document this at the top of the script.
+
+**Verify:**
+```bash
+cd services/geometry && source .venv/bin/activate && cd ../geometry-rs && python scripts/make_fixtures.py && ls fixtures/
+# Expected: box.step plates.step nested.step + .glb, .graph.json, .meshopt.glb for each (12 files total minimum)
+# If services/geometry/.venv does not exist, STOP and report — do not pip install into the system.
+```
+
+**Out of scope:** Rust-native fixture generation (Task 32). Committing any fixture binary.
+
+## Task 4: GLB reader with meshopt decode (`glb` crate, read half)
+
+**Depends on:** Tasks 2, 3
+**Files:**
+- Create: `services/geometry-rs/crates/glb/src/{read.rs,meshopt_decode.rs,error.rs}`
+- Modify: `services/geometry-rs/crates/glb/src/lib.rs` — export `read_assembly_glb`
+
+**Steps:**
+1. Parse GLB container manually (12-byte header, JSON chunk, BIN chunk — the format is trivial; do NOT pull the full `gltf` crate import machinery, parse the JSON chunk with `serde_json::Value` plus small typed structs for the parts we need: nodes/meshes/accessors/bufferViews/extensions). Rationale: we need `extras.nodeId` (typed gltf crates drop or complicate extras) and `EXT_meshopt_compression` bufferViews (unsupported by gltf-rs).
+2. `meshopt_decode.rs`: decode `EXT_meshopt_compression` bufferViews using the `meshopt` crate decoders (`decode_vertex_buffer`, `decode_index_buffer`, plus filter decoders for OCTAHEDRAL/QUATERNION/EXPONENTIAL). If the `meshopt` crate does not expose a needed decode function, call the corresponding `meshopt-sys` FFI function directly behind a safe wrapper — check `meshopt-sys` docs first; if neither exposes it, STOP and report.
+3. Public API: `read_assembly_glb(bytes: &[u8]) -> Result<GlbAssembly, GlbError>` where `GlbAssembly { parts: Vec<GlbPart> }`, `GlbPart { node_id: String, vertices: Vec<[f64; 3]> /* world-space */, indices: Vec<[u32; 3]> }`. Compute world transforms by walking the scene node tree (node.matrix or TRS), multiply into vertices. Note: the converter bakes vertices in world space with identity node transforms — but do NOT rely on that; apply transforms anyway (correct in both cases).
+4. **Join validation (mandatory, from lessons):** `validate_against_graph(assembly: &GlbAssembly, graph: &AssemblyGraph) -> Result<(), GlbError>` — every graph leaf (non-assembly node) has a GLB part with matching `node_id`; each part's computed AABB matches the graph node's world bbox within 1.0 mm max component error; error lists every mismatched nodeId. Callers must run this before planning.
+5. Tests (fixture-gated per Task 3): read `plates.meshopt.glb` + `plates.graph.json` → validation passes, part count matches `componentCount`, 4 plate screws share... (don't assert mesh sharing here — after decode each part has its own vertex copy; assert counts and bbox validation only). Same for uncompressed `plates.glb` (reader must handle both).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p glb 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed (tests skip with a message if fixtures/ absent — run Task 3 first)
+```
+
+**Out of scope:** GLB writing (Task 29), meshopt encoding (Task 30).
+
+## Task 5: SPIKE — quantization error vs penetration tolerance (GO/NO-GO)
+
+**Depends on:** Task 4
+**Files:**
+- Create: `services/geometry-rs/crates/glb/tests/quantization_spike.rs`
+- Create: `services/geometry-rs/SPIKE-QUANTIZATION.md` (findings)
+
+**Steps:**
+1. For each fixture pair (`<name>.glb` vs `<name>.meshopt.glb`): decode both, match parts by nodeId, compute per-vertex position error (max + p99 across all parts).
+2. Threshold: the planner's collision truth uses `PENETRATION_TOLERANCE_MM = 0.15` (scaled up to `2.5 × linearDeflection`). Quantization error must be **≤ 0.05 mm max** (one order below the scaled floor is not achievable; a third of the base tolerance is the bar).
+3. Write measured numbers into `SPIKE-QUANTIZATION.md` with the verdict.
+4. **If error > 0.05 mm:** STOP and report with the numbers. The fallback (Python `/convert` also uploads an uncompressed `model.raw.glb` for the planner) is a contract change that needs user sign-off — do not implement it unilaterally.
+5. If available, also run one real customer GLB (ask the user; the "seat rail" and "SA Mando harness" models are the known references) — record in the same doc.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p glb --test quantization_spike -- --nocapture 2>&1 | tail -5
+# Expected: printed max/p99 error per fixture, all max ≤ 0.05, "test result: ok."
+```
+
+**Out of scope:** Any change to the Python service.
+
+## Task 6: Planner scaffolding — constants, `Component`, world-part collection
+
+**Depends on:** Task 5 (GO)
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/{constants.rs,component.rs,collect.rs,error.rs}`
+- Copy from (precedent): `services/geometry/app/plan.py` lines 61–173 (constants), `_collect_world_parts` (line 2195), `_part_volume` (line 1110)
+
+**Steps:**
+1. `constants.rs`: transcribe EVERY module-level constant from `services/geometry/app/plan.py` lines 61–173 with identical names (Rust SCREAMING_SNAKE, same values): `PLAN_VERSION=3`, `PENETRATION_TOLERANCE_MM=0.15`, `EXIT_MARGIN_MM=5.0`, `MAX_SAMPLE_SPACING_MM=2.0`, `MAX_PATH_SAMPLES=400`, `MATE_MIN_DEPTH_MM=0.2`, `MATE_DEPTH_MARGIN_MM=0.3`, `ORDERING_CONTACT_MM=0.5`, `MAX_ADJACENCY_DISTANCE_PAIRS=20000`, `SANDWICH_*` (4), `MAX_FASTENER_DIAGONAL_FRACTION=0.35`, `MAX_FASTENER_EXTENT_MM=100.0`, `MAX_ESCAPE_SEGMENTS=3`, `MAX_ESCAPE_EXPANSIONS=24`, `MIN_HOP_FRACTION=0.25`, `MAX_GROUP_SIZE=4`, `MAX_GROUP_TESTS=40`, `GROUP_PROXIMITY_MM=2.0`, `WORLD_AXES`, the `FASTENER_NAME_RE` regex (port to the `regex` crate — add `regex = "1"` to workspace deps; copy the pattern character-for-character from plan.py line 138, including the deliberate absence of a bare `pin` token), and `_mesh_tolerance(linear_deflection)` (line 73). Read the actual file — do not trust this list to be exhaustive.
+2. `component.rs`: `Component` port of `_Component` (find the dataclass/class definition in plan.py; fields include node_id, name, mesh (parry `TriMesh`), world bbox, volume, plus the caches the Python code hangs on the mesh — `bvh`/volume become owned struct fields instead of monkey-patched attributes).
+3. `collect.rs`: `collect_world_parts(glb: &GlbAssembly, graph: &AssemblyGraph) -> Result<Vec<Component>, PlannerError>` — port `_collect_world_parts` semantics: leaves only, world-space `TriMesh` from GLB parts (join by nodeId — GLB is the mesh source in Rust; Python re-tessellated from STEP), volume via `_part_volume` port: watertight → mesh volume; non-watertight → split into watertight components and sum, else bbox-volume fallback. parry3d `TriMesh` has orientation/topology flags; if watertightness cannot be determined from parry, implement a closed-mesh check (every edge shared by exactly 2 triangles) in this crate — small and deterministic.
+4. Unit tests with hand-built meshes (a unit cube TriMesh helper in `#[cfg(test)]` — this helper gets reused by every later task; give it `subdivided(size)` support now, mirroring the `subdivide_to_size(5.0)` lesson for sliding-contact tests).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** Any collision logic (Task 8).
+
+## Task 7: Parity tracker
+
+**Depends on:** Task 6
+**Files:**
+- Create: `services/geometry-rs/PARITY.md`
+
+**Steps:**
+1. Run `grep -n "^def test_" services/geometry/tests/test_plan.py` (and the class-based variants if any: `grep -n "def test_" services/geometry/tests/test_plan.py`). List EVERY test name in `PARITY.md` as a checkbox table: `| Python test | Rust test | Task | Status |`, status one of `pending / ported / n-a (reason)`.
+2. Assign each test to one of Tasks 9–19 by subject (read each test's body to classify: seated/adjacency → 9, fastener classification → 10, merge/embedded → 11, joints → 12, sandwich → 13, removal tiers → 14/15, greedy/base → 16, precedence/topo/verify → 17, fixed-sequence/units → 18, end-to-end/determinism → 19/20).
+3. Rule for all subsequent tasks: a task is NOT done until its assigned PARITY.md rows are `ported` and green. `n-a` requires a written reason (e.g. tests Python-internal monkey-patching).
+
+**Verify:**
+```bash
+grep -c "^def test_" services/geometry/tests/test_plan.py && grep -c "| test_" services/geometry-rs/PARITY.md
+# Expected: two equal numbers (every Python test has a row)
+```
+
+**Out of scope:** porting any test yet.
+
+## Task 8: Collision layer — broadphase manager + calibration suite
+
+**Depends on:** Task 6
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/collision.rs`
+- Create: `services/geometry-rs/crates/planner/tests/calibration.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` — `_mesh_bvh` (3121), `_unregistered` (3138), `_contacts_at` (3168), `_seated_pair_depths` (2226), `_blocking_depth` (3835)
+
+**Steps:**
+1. Design a `CollisionWorld` owning: per-part parry3d `TriMesh` (its internal QBVH is the BVH-built-once), an `rstar::RTree` of part AABBs as the broadphase (replaces fcl's DynamicAABBTreeCollisionManager), and a registered/unregistered flag set (`HashSet<usize>`) so unregister/re-register is O(1) bookkeeping, never a rebuild — this implements the two lessons (self-exempt sweep, blocker-unregister-mid-sweep) structurally.
+2. `Contact { part_a: usize, part_b: usize, point: [f64;3], normal: [f64;3], depth: f64 }`. Narrowphase via parry3d mesh-mesh contact manifolds at a transformed pose (`parry3d::query::contact` / `contact_manifolds` on TriMesh pairs). **Semantic risk lives here:** FCL reports per-triangle-pair local penetration; parry manifolds aggregate differently. The calibration suite defines the required semantics; adapt the extraction (e.g. per-manifold-point depth) until calibration passes.
+3. Calibration tests (all with the Task 6 cube helper, subdivided where sliding contact is sustained — lesson from `.ai/lessons.md` "Synthetic box meshes fake huge penetration"):
+ - two 10 mm cubes overlapping 0.05 mm face-on → max depth ∈ [0.04, 0.06] (below tolerance ⇒ "seated, not colliding")
+ - overlapping 1.0 mm → depth ∈ [0.9, 1.1]
+ - disjoint by 0.1 mm → no contacts
+ - 5 mm cylinder (tessellated ~32 segments, helper) inside 5.05 mm bore → radial depths all < PENETRATION_TOLERANCE_MM
+ - subdivided slider seated 0.05 mm into a channel floor, sampled while translating tangentially → depth stays < 0.15 at every sample (the FCL artifact this guards against reported 29.8 mm)
+ - exact distance between two cubes 0.3 mm apart → ∈ [0.29, 0.31] (parry `distance`)
+ - point-containment: centroid of a cube → inside; point 0.1 mm outside a face → outside (parry point projection; this replaces `mesh.contains` ray-casts)
+4. If any calibration bound cannot be met by any parry contact-extraction strategy, STOP and report with the failing case and measured values — this invalidates the parry choice and the user must decide (options: different query strategy, or wrapping the C++ FCL — do not choose unilaterally).
+5. `seated_pair_depths(world) -> PairData` port (plan.py 2226): one broadphase pass over all registered pairs; per pair: max depth, contact points capped at 64, **uncapped** normal structure tensor `Σ n·nᵀ`, contact AABB.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner --test calibration 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** path sampling / sweeps (Task 14 builds on `contacts_at`).
+
+## Task 9: Seated pair depths + ordering adjacency
+
+**Depends on:** Task 8
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/adjacency.rs`
+- Modify: `services/geometry-rs/crates/planner/src/lib.rs` — exports
+- Copy from (precedent): `services/geometry/app/plan.py` `_ordering_adjacency` (1632), `_rollup_adjacency` (1702), `_separation_distance` (grep for it)
+
+**Steps:**
+1. Port `_ordering_adjacency`: inflated-AABB prefilter → exact parry distance for pairs within `ORDERING_CONTACT_MM = 0.5`; budget cap `MAX_ADJACENCY_DISTANCE_PAIRS = 20000`, past budget degrade to bbox-only adjacency exactly as Python does (read the degradation branch carefully).
+2. Port `_rollup_adjacency` (post-merge unit adjacency) and the analytic per-axis `_separation_distance`.
+3. Port PARITY.md rows assigned to Task 9. Python tests that build synthetic `_Component`s translate to the Task 6 helper; keep the Python test names as Rust test names (snake-case as-is).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner adjacency 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed; PARITY.md Task-9 rows flipped to ported
+```
+
+**Out of scope:** precedence edges (Task 17).
+
+## Task 10: Fastener classification
+
+**Depends on:** Task 9
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/fasteners.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_classify_fasteners` (2287), `_is_fastener` (170), `_shank_radius` (2364), `_symmetry_axis_kind` (2721), `_symmetry_axis` (2758), `_axis_from_contacts` (2543), `_bbox_axis_kind` (2584), `_normal_clusters` (2763), `_head_direction` (3217)
+
+**Steps:**
+1. Port the full cascade: name regex (+ the structural-size sanity cap `max(MAX_FASTENER_EXTENT_MM, MAX_FASTENER_DIAGONAL_FRACTION × assembly diagonal)` — lesson: "Electronics Box - 36 Pin") → SVD symmetry axis (rod vs disc from singular-value ratios; use `parry3d::na::SVD` on the centered vertex matrix) → bbox-extent kind → contact-ring PCA → dominant contact-normal cluster. Read each Python function fully before porting; the singular-value ratio thresholds are load-bearing.
+2. `_shank_radius`: mate-contact radial mean, falling back to vertex-radial 25th percentile (implement percentile by sorting — no numpy; nearest-rank method, verify against numpy's default `linear` interpolation on a test vector and match Python's result for the test inputs).
+3. Port PARITY.md Task-10 rows.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner fasteners 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** joint detection (Task 12), removal ordering (Task 16).
+
+## Task 11: Rigid merge + embedded pairs
+
+**Depends on:** Task 9
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/merge.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_embedded_pairs` (2605), `_merge_rigid_groups` (2637), `_merge_units` (479), `_eject_fastened_unit_members` (412)
+
+**Steps:**
+1. `_embedded_pairs`: bbox containment prefilter → point-containment on ≤ 24 sampled inner vertices, > 80 % inside ⇒ embedded (uses Task 8 containment).
+2. `_merge_rigid_groups`: union-find (implement inline — 20 lines; no crate) over deep-interpenetration pairs + embedded pairs; merged cluster becomes one concatenated `TriMesh` (rebuild QBVH once for the merged mesh).
+3. `_merge_units` / `_eject_fastened_unit_members`: caller-specified `PlanUnit` pre-grouping + the fastener-ejection rule (fasteners named in a unit get ejected back out — read the Python for the exact condition).
+4. Port PARITY.md Task-11 rows (embedded-logo test et al.).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner merge 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** group removal (Task 15).
+
+## Task 12: Fastener ring joints
+
+**Depends on:** Tasks 10, 11
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/joints.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_fastener_joints` (2391), `_axis_span` (2523), `_mate_exempt` (3259), `_seated_exempt` (3278), `_self_exempt` (3201)
+
+**Steps:**
+1. Ring-containment probe: 8 points on circle of `shankRadius × 1.2` (+ clearance radius) at 3 heights along the axis; candidate surrounding ≥ 6/8 ⇒ through-part. Point-containment from Task 8.
+2. Exemption model: port `_mate_exempt` / `_seated_exempt` / `_self_exempt` as a single `Exemptions` struct consulted by `contacts_at` filtering. **Lesson constraint:** every exemption is pair-scoped and axis-gated with a depth cap (seated interference + `MATE_DEPTH_MARGIN_MM`); no global allowances. If the Python code has a branch that looks like a blanket allowance, port it exactly anyway (parity first) but flag it in PARITY.md notes.
+3. Port PARITY.md Task-12 rows (unscrew-through-mate, washer-before-bolt, snug counterbore, stud-clamping, never-tunnel-thin-cover…).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner joints 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** sweep mechanics (Task 14).
+
+## Task 13: Sandwich detection
+
+**Depends on:** Task 9
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/sandwich.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_sandwiched_parts` (1382)
+
+**Steps:**
+1. Port `_sandwiched_parts`: symmetric eigendecomposition (`parry3d::na::SymmetricEigen`) of the pair structure tensor; thickness caps BOTH ratio (`SANDWICH_MAX_THICKNESS_RATIO=0.3`) AND absolute (`SANDWICH_MAX_THICKNESS_MM=6.0`); axis alignment ≥ 0.9; squish cap `SANDWICH_MAX_SQUISH_MM=0.6`. These dual caps exist because ratio-only classification produced a 33 mm "gasket" (lesson: "Ordering heuristics must be gated on a large noisy model") — do not weaken them.
+2. Port PARITY.md Task-13 rows (gasket ordering, axis-gating, thickness/depth negatives).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner sandwich 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** the soft ordering edges it feeds (Task 17).
+
+## Task 14: Removal planning — tier 1 linear + tier 2 "L"
+
+**Depends on:** Tasks 8, 12
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/sweep.rs`
+- Create: `services/geometry-rs/crates/planner/src/removal.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_contacts_at` (3168), `_path_is_clear` / `_path_blockers` (1178), `_plan_removal` (3301), `_candidate_directions` (2789), `_free_travel` (3856), `_recorded_travel` (3890), `_removal_segments` (1162)
+
+**Steps:**
+1. `sweep.rs`: `contacts_at(world, part, pose, exemptions)` (narrowphase at a sampled pose, exemption-filtered), `path_is_clear` (dense sampling: spacing ≤ `MAX_SAMPLE_SPACING_MM=2.0`, ≤ `MAX_PATH_SAMPLES=400`, bounded by AABB `separation_distance` + `EXIT_MARGIN_MM`), `path_blockers` with the **blocker-unregister optimization**: once a partner exceeds tolerance it is recorded and unregistered for the remainder of that sweep, re-registered before return (lesson: this was the 8× win; the mechanism is the Task 8 flag set).
+2. `removal.rs`: `plan_removal` tier 1 (candidate directions: symmetry axis ± , contact-normal clusters, world axes — port `_candidate_directions` ordering exactly; the `entanglement` sort closure at 3370 decides candidate order and hence output determinism) and tier 2 "L" (lift-then-slide two-segment motions). Motion output = ordered `(direction, travel)` segments; the recorded plan motion is the reversed removal (port `_removal_segments_to_planned`, 3803).
+3. Port PARITY.md Task-14 rows (top-down stack, pin-in-bore, rod-axis-preference…). Sliding-contact synthetic tests use the subdivided helper.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner removal 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** escape BFS + groups (Task 15), the greedy loop (Task 16).
+
+## Task 15: Tier 3 escape BFS + group removal
+
+**Depends on:** Task 14
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/escape.rs`
+- Modify: `services/geometry-rs/crates/planner/src/removal.rs` — tier 3 + group hooks
+- Copy from (precedent): `services/geometry/app/plan.py` `_plan_escape` (3477), `_plan_group_removal` (3621), `_group_exempt` (3584)
+
+**Steps:**
+1. `_plan_escape`: axis-aligned hop BFS, ≤ `MAX_ESCAPE_SEGMENTS=3` segments, ≤ `MAX_ESCAPE_EXPANSIONS=24` expansions, hop length ≥ `MIN_HOP_FRACTION` of part extent. Deterministic expansion order (BTreeMap/sorted frontier — no HashMap iteration order anywhere in planner logic; enforce with a grep in the Verify step).
+2. `_plan_group_removal`: proximity-graph subassembly groups ≤ `MAX_GROUP_SIZE=4`, ≤ `MAX_GROUP_TESTS=40`, proximity `GROUP_PROXIMITY_MM=2.0`; group treated as one rigid body for the sweep.
+3. **No tier 4.** If the Python file still contains any forced-removal remnant, do not port it; unsolvable ⇒ flagged (`motion: none`, `blockedBy`, warning) per lesson "Never fabricate a best-effort motion".
+4. Port PARITY.md Task-15 rows (blind-pocket multi-segment escape, group extraction, captive-part flag-or-merge).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner escape 2>&1 | tail -3 && ! grep -rn "HashMap" services/geometry-rs/crates/planner/src/{escape,removal,sweep}.rs
+# Expected: tests ok; grep exits non-zero (no HashMap in planning-order code paths)
+```
+
+**Out of scope:** ordering of removal attempts (Task 16).
+
+## Task 16: Greedy disassembly loop + base re-selection
+
+**Depends on:** Tasks 10, 11, 13, 15
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/greedy.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_greedy_disassembly` (2815), `removal_priority` (2868), `_reselect_base` (1735), `_structural_key` (1138), `_assembly_centroid` (1156)
+
+**Steps:**
+1. Port `_greedy_disassembly` (~300 LOC): the removal_priority ordering (read the closure carefully — priority ranking schedules expensive attempts AND picks flag/merge victims; a mis-ported comparator silently wrecks quality per the "preferences don't belong in removal_priority" lesson), per-part `plan_removal` attempts, merge-on-failure and flag-on-failure paths.
+2. Port `_reselect_base` scoring (`mate-degree × volume`, exact tuple ordering from the `score` closure at 1763).
+3. All orderings sort with explicit stable keys ending in `node_id` as the final tiebreak (determinism).
+4. Port PARITY.md Task-16 rows.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner greedy 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** final sequence ordering (Task 17).
+
+## Task 17: Precedence DAG, preference topo sort, forward verification
+
+**Depends on:** Task 16
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/ordering.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_derive_precedence` (1248), `_add_joint_edges` (1290), `_add_sandwich_edges` (1483), `_add_support_edges` (1561), `_preference_topo_sort` (1861), `_connectivity_repair` (1816), `_verify_sequence` (2129), `_motion_travel` (1371)
+
+**Steps:**
+1. Port hard precedence edges (`_derive_precedence`, `_add_joint_edges` with its `reaches` cycle guard) and soft preference edges (`_add_sandwich_edges`, `_add_support_edges` — soft edges are preferences consulted only inside the topo sort's tie-break, never hard constraints).
+2. Port `_preference_topo_sort` (~270 LOC: connected-growth constraint, `is_securing`/`is_weakly_secured` predicates, the `sort_key` closure at 2075 verbatim) + `_connectivity_repair`.
+3. Port `_verify_sequence`: replay each insertion against parts present at that step; failure demotes to flagged, sets `verified: false`.
+4. Port PARITY.md Task-17 rows (topo connectivity, washer/bolt/nut ordering end-cases that live at this layer).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner ordering 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** wire output (Task 19).
+
+## Task 18: Fixed-sequence mode + units
+
+**Depends on:** Task 17
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/fixed.rs`
+- Copy from (precedent): `services/geometry/app/plan.py` `_plan_fixed_sequence` (844)
+
+**Steps:**
+1. Port `_plan_fixed_sequence`: caller-supplied ordered groups, each installed as one rigid body against previously-installed groups only; no reordering; forward-collision insertion motion per group. Validation of group membership against graph leaves (unknown nodeId ⇒ error listing the ids, matching the Python behavior — read what it does with unknowns and mirror exactly).
+2. Port PARITY.md Task-18 rows (the entire fixed-sequence and unit merge/eject test set).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner fixed 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** re-motion callers in `packages/jobs` (no TS change in this task).
+
+## Task 19: `plan_step` orchestration + plan.json v3 output parity
+
+**Depends on:** Tasks 17, 18
+**Files:**
+- Create: `services/geometry-rs/crates/planner/src/plan.rs` (public `plan_assembly(glb, graph, options) -> Result<PlanOutcome, PlannerError>`)
+- Copy from (precedent): `services/geometry/app/plan.py` `plan_step` (270), `_plan_parts` (537), `_tally_tiers` (1080), `_part_to_dict` (2179)
+
+**Steps:**
+1. Wire the pipeline in `_plan_parts` order: collect → seated depths → adjacency → fasteners → merge → joints → sandwich → greedy → base re-selection → precedence/topo → verify → output. `PlanOutcome { plan: AssemblyPlan, component_count, planned_count, stats: PlanStats }`.
+2. Output must serialize to the exact plan.json v3 shape (`geometry-types::plan`); tiers tally keys match Python's `_tally_tiers` strings.
+3. End-to-end fixture test: run `plan_assembly` on `plates.meshopt.glb` + graph; assert the 4 screws are planned before/after per current Python behavior — generate the Python reference by running the Python planner on the same fixture from `services/geometry-rs/scripts/make_fixtures.py` (extend the script to also emit `<name>.plan.json` via `app.plan.plan_step`); compare `sequence`, per-component `tier` and `motion.type` (NOT float travel values — epsilon-free fields only).
+4. Port remaining PARITY.md end-to-end rows. All PARITY.md rows must now be `ported` or `n-a` with reasons.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner 2>&1 | tail -3 && ! grep -n "pending" services/geometry-rs/PARITY.md
+# Expected: tests ok; grep exits non-zero (no pending rows left)
+```
+
+**Out of scope:** HTTP layer (Task 21), parallelism (Task 20).
+
+## Task 20: Determinism test, then rayon parallelization
+
+**Depends on:** Task 19
+**Files:**
+- Modify: `services/geometry-rs/crates/planner/src/{sweep.rs,greedy.rs,plan.rs}` — rayon
+- Create: `services/geometry-rs/crates/planner/tests/determinism.rs`
+
+**Steps:**
+1. FIRST commit the determinism test single-threaded: run `plan_assembly` twice on `plates` fixture, assert byte-identical `serde_json::to_vec` of the plan (port `test_plan_is_deterministic`).
+2. THEN parallelize with rayon, preserving determinism: parallel over candidate directions within `plan_removal` (collect all results, pick by the same `entanglement` comparator — an ordered reduction, not first-wins), parallel over pairs in `seated_pair_depths` and `_embedded_pairs` (collect then sort by pair key). Do NOT parallelize across greedy iterations (order-dependent).
+3. `CollisionWorld` must be `Sync` for read-only narrowphase; the unregister flag-set becomes a per-sweep local exclusion list passed by value into parallel closures instead of shared mutation.
+4. Determinism test re-run 5× under `--release`; add a timing print (`--nocapture`) for the fixture plan to document the speedup in the task commit message.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p planner --release --test determinism -- --nocapture 2>&1 | tail -4
+# Expected: "test result: ok.", identical-bytes assertion passing, printed timing
+```
+
+**Out of scope:** micro-optimizations beyond rayon (profile first — lesson: "Profile the planner before optimizing").
+
+## Task 21: Server binary — axum `/health`, `/plan`, `/plan/{jobId}`
+
+**Depends on:** Task 19
+**Files:**
+- Create: `services/geometry-rs/crates/server/src/{main.rs,auth.rs,config.rs,jobs.rs,routes.rs,fetch.rs}`
+- Copy from (precedent): `services/geometry/app/main.py` (routes, semaphore, job dict), `app/auth.py` (auth semantics), `app/config.py` (env vars)
+
+**Steps:**
+1. `config.rs`: same env vars, same defaults — `GEOMETRY_SERVICE_API_KEY`, `GEOMETRY_DEV_MODE` (only consulted when the key is unset: `"true"` ⇒ allow unauthenticated, anything else ⇒ 401; also disables https-required and TLS-verify), `GEOMETRY_MAX_CONCURRENCY` (default 2), `GEOMETRY_MAX_SOURCE_MB` (250), `GEOMETRY_ALLOWED_URL_HOSTS` (comma list), `PORT` (default 8000).
+2. `auth.rs`: `Authorization: Bearer <key>` check as an axum middleware/extractor; constant-time comparison (`subtle` crate or length-then-`ct_eq`).
+3. `fetch.rs`: reqwest streaming GET with size cap enforced on both Content-Length and streamed bytes; URL validation (https unless dev mode; host allowlist); `danger_accept_invalid_certs(true)` only when dev mode (mirrors `verify_tls`).
+4. `jobs.rs`: `DashMap<String, PlanJob>` keyed by jobId, states `pending|running|done|error`, 1 h TTL sweep (spawned tokio interval task). Semaphore: `tokio::sync::Semaphore` with `try_acquire` ⇒ 429 `{"error":"BUSY"}` when full. Planner runs in `tokio::task::spawn_blocking` (CPU-bound; rayon inside).
+5. `routes.rs`: `GET /health` → `{"ok":true,"version":<CARGO_PKG_VERSION>}` unauthenticated; `POST /plan` → validate `PlanRequest` (new glbUrl/graphUrl shape), 202 + `PlanStartResponse`; `GET /plan/{jobId}` → `PlanStatusResponse` with inline `plan` on done (NEVER an upload URL — lesson: 60 s signed-upload expiry). Unknown jobId ⇒ 404 (callers treat as service-restarted and re-submit).
+6. Endpoint tests with a local hyper/axum stub server serving fixture GLB/graph bytes (port the `StorageStub` idea from `services/geometry/tests/conftest.py`): submit → poll → done with a valid plan; auth matrix (5 cases from `services/geometry/tests/test_api.py`); 429 when slots exhausted; https/allowlist/size-cap rejections (from `test_limits.py`).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p server 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** `/convert` (Task 31). Redis job store (explicitly deferred; DashMap matches Python semantics).
+
+## Task 22: Shadow-comparison harness + large-noisy-model gate
+
+**Depends on:** Task 21
+**Files:**
+- Create: `services/geometry-rs/scripts/shadow_compare.py`
+- Create: `services/geometry-rs/SHADOW-RESULTS.md`
+
+**Steps:**
+1. Script inputs: a directory of `{model.glb, graph.json}` pairs (downloaded from real company storage by the user, or the fixture set). For each: run Python `plan_step` (via `services/geometry/.venv`, importing `app.plan`) and the Rust planner (`cargo run --release -p server` is not needed — add a tiny `cargo run --release -p planner --example plan_file <glb> <graph>` example binary that prints the plan JSON) and diff: sequence order, per-component tier, motion type, flagged set, warning count. Report per-model PASS/DIVERGENCE with the diff.
+2. Timing both sides per model into `SHADOW-RESULTS.md` (this is the perf-claim evidence).
+3. **Gate (lesson: seat rail is best-case):** the comparison set MUST include one large noisy model (the 118-part "SA Mando & Battery Harness" class or the "SA BCU"). Ask the user to provide the GLB/graph pair from a real environment; if unavailable, STOP and report — do not sign off shadow parity on fixtures alone.
+4. Acceptance: identical sequences OR divergences individually reviewed and explained in SHADOW-RESULTS.md (e.g. equal-priority tie broken differently is acceptable ONLY if the Rust side is internally deterministic and the tie is provably equal-cost; anything else is a bug).
+
+**Verify:**
+```bash
+cd services/geometry-rs && python scripts/shadow_compare.py fixtures/ && head -20 SHADOW-RESULTS.md
+# Expected: PASS for every fixture model; SHADOW-RESULTS.md has a per-model table with timings
+```
+
+**Out of scope:** production traffic mirroring.
+
+## Task 23: Jobs-side switch — `assembly-plan.ts` calls the Rust planner
+
+**Depends on:** Task 22 (fixtures PASS at minimum)
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts` — payload + URL
+- Modify: `packages/env/src/index.ts` — add `GEOMETRY_PLAN_SERVICE_URL` (optional)
+- Copy from (precedent): `packages/jobs/src/inngest/functions/tasks/assembly-convert.ts` (signed URL minting with `createSignedUrl`)
+
+**Steps:**
+1. `packages/env/src/index.ts`: add optional `GEOMETRY_PLAN_SERVICE_URL` next to `GEOMETRY_SERVICE_URL` (same pattern; not secret). Empty ⇒ fall back to `GEOMETRY_SERVICE_URL` (transition switch; removed in Task 35).
+2. `assembly-plan.ts`: before submit, read `modelUpload.glbPath` and `graphPath` for the row. **If either is missing** (convert never succeeded), fail the job with the existing failure path and message `"model not converted yet"` — do not fall back to the STEP payload. Mint signed GET URLs for both via `client.storage.from("private").createSignedUrl(path, SIGNED_URL_EXPIRY)` (same call pattern the file already uses for the STEP source — replace it). New payload: `{ jobId, source: { glbUrl, graphUrl }, options }` (options unchanged: units/sequence/deflections pass through). Re-submit path (404 recovery) re-mints both URLs — keep that behavior, it exists for expiry.
+3. Poll loop, timeouts (`AbortSignal.timeout(60_000)`), re-submit cap, inline-plan persistence: **unchanged**.
+4. Escape hatch: if `assembly-plan.ts` has drifted from the structure described here (grep for `createSignedUrl` and the poll loop first), STOP and re-read the whole file before editing.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs 2>&1 | tail -3
+# Expected: "Tasks: 1 successful" (or the package's typecheck task exiting 0)
+```
+
+**Out of scope:** `assembly-convert.ts` (unchanged until Phase B cutover). Any ERP route.
+
+## Task 24: Dev-stack wiring for the Rust planner
+
+**Depends on:** Task 23
+**Files:**
+- Modify: `packages/dev/src/services/apps.ts` — spawn the Rust planner alongside uvicorn
+- Modify: `packages/dev/src/env.ts` — write `GEOMETRY_PLAN_SERVICE_URL` into `.env.local`
+
+**Steps:**
+1. Read `packages/dev/src/services/apps.ts` lines ~240–282 (the existing geometry uvicorn spawn) — copy its pattern: spawn `services/geometry-rs/target/release/server` (or `cargo run --release -p server` if the binary is absent — prefer checking for the built binary and printing a skip message `"geometry-rs not built — cargo build --release"` when missing, mirroring the `.venv` skip message). Env: `PORT` = a new `PORT_GEOMETRY_RS` (default 54008 — check `packages/dev/src/env.test.ts` / wherever `PORT_GEOMETRY` 54007 is defined and register the new port the same way), `GEOMETRY_SERVICE_API_KEY: "dev-local-key"`, `GEOMETRY_DEV_MODE: "true"`.
+2. `packages/dev/src/env.ts`: write `GEOMETRY_PLAN_SERVICE_URL=http://localhost:54008` (or the portless-domain form if that's what the sibling `GEOMETRY_SERVICE_URL` line does — mirror it exactly, lines ~101–103).
+3. Escape hatch: if the dev package's service-spawning structure differs from this description, STOP, read the file, and follow its actual conventions.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/dev 2>&1 | tail -3
+# Expected: typecheck exits 0. Manual smoke (user-run): pnpm dev, then trigger a re-plan in the ERP assembly editor and watch the Rust service logs.
+```
+
+**Out of scope:** production deployment (Task 34/35).
+
+## Task 25: `occt-bridge` crate — build skeleton + exception guards
+
+**Depends on:** Task 1 (parallel-safe with Phase A)
+**Files:**
+- Create: `services/geometry-rs/crates/occt-bridge/{Cargo.toml,build.rs,src/lib.rs,src/bridge/mod.rs,cpp/guard.hpp,cpp/guard.cpp}`
+
+**Steps:**
+1. `Cargo.toml`: `occt-sys = "0.6"` (build-dep + dep as its docs prescribe), `cxx = "1"`, build-dep `cxx-build = "1"`. If occt-sys 0.6 fails to build on this machine, try the git rev used by opencascade-rs `main` and record the pin; if that also fails, STOP with the build log tail.
+2. `build.rs`: `cxx_build::bridge` over the bridge modules; add OCCT include path + static libs from `occt-sys` (follow `https://github.com/bschwind/opencascade-rs/blob/main/crates/opencascade-sys/build.rs` as the reference for which `TK*` libs to link — must include `TKXCAF TKLCAF TKCAF TKDESTEP TKXDESTEP` equivalents for the pinned OCCT version; the exact TK names for STEP+XCAF in OCCT 7.8 are `TKSTEP TKSTEPAttr TKSTEPBase TKSTEP209 TKXDESTEP TKXCAF TKLCAF TKCDF TKVCAF` plus core `TKernel TKMath TKBRep TKGeomBase TKGeomAlgo TKG2d TKG3d TKTopAlgo TKShHealing TKMesh TKPrim` — verify against the occt-sys lib dir listing at build time and adjust).
+3. `cpp/guard.hpp`: every bridged OCCT call goes through a `GUARDED(expr)` macro wrapping `OCC_CATCH_SIGNALS` + `try { ... } catch (Standard_Failure const& e) { return err(e.GetMessageString()); } catch (...) { return err("unknown OCCT failure"); }` returning a `Result`-shaped struct cxx can pass (`struct OcctResult { bool ok; rust::String error; }` pattern). NO OCCT exception may cross the FFI boundary (opencascade-rs issue #172: aborts).
+4. Smoke bridge: one function `occt_version() -> String` returning `OCC_VERSION_COMPLETE`, tested from Rust.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p occt-bridge 2>&1 | tail -3
+# Expected: "test result: ok." (first build takes ~20-25 min — occt-sys compiles OCCT; do not kill it)
+```
+
+**Out of scope:** any real OCCT class (Tasks 26–27).
+
+## Task 26: Bridge surface — STEP/XCAF document read
+
+**Depends on:** Task 25
+**Files:**
+- Create: `services/geometry-rs/crates/occt-bridge/src/bridge/{step.rs,xcaf.rs}` + matching `cpp/*.cpp` shims
+- Copy from (precedent): `services/geometry/app/convert.py` `_read_step` and the XCAF walk (the class list below is the verified inventory), and `https://github.com/bschwind/opencascade-rs/blob/main/docs/writing_bindings.md` for cxx mechanics
+
+**Steps:**
+1. Bridge exactly this surface (verified against `convert.py` — nothing speculative): `STEPCAFControl_Reader` (SetColorMode/SetNameMode/SetLayerMode/SetMatMode/ReadFile/Transfer), `Interface_Static::SetCVal("xstep.cascade.unit","MM")`, `IFSelect_ReturnStatus`, `TDocStd_Document` creation, `XCAFDoc_DocumentTool::ShapeTool`, `XCAFDoc_ShapeTool::{IsAssembly, GetComponents, GetReferredShape, GetLocation, GetShape, GetFreeShapes}`, `XCAFDoc_ColorTool::GetColor` (ColorSurf + ColorGen), `TDF_Label`/`TDF_LabelSequence`/`TDF_Tool::Entry`, `TDataStd_Name` (GetID/FindAttribute/Get), `TopLoc_Location::Transformation` + `gp_Trsf::Value(i,j)`, `Quantity_ColorRGBA` accessors.
+2. Expose a Rust-idiomatic layer on top of the raw bridge: `read_step_document(path) -> Result<XcafDocument, OcctError>`; `XcafDocument::free_shapes() -> Vec<Label>`; `Label::{entry(), name(), is_assembly(), components(), referred_shape(), location_matrix() -> [f64;16], shape()}`; `color_for(label/shape) -> Option<[f32;4]>`. Handle<T> template instantiations need per-type C++ typedefs (writing_bindings.md covers this).
+3. Test (fixture-gated): read `fixtures/plates.step` → free shapes count, assembly flags, component names include `M5-SHCS`, a color is present. Compare counts against `fixtures/plates.graph.json` (produced by Python from the same file).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p occt-bridge step 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** tessellation (Task 27), STEP writing (Task 32).
+
+## Task 27: Bridge surface — tessellation, volume, bbox
+
+**Depends on:** Task 26
+**Files:**
+- Create: `services/geometry-rs/crates/occt-bridge/src/bridge/mesh.rs` + shim
+- Copy from (precedent): `services/geometry/app/convert.py` `_tessellate` (per-face loop), and `https://github.com/bschwind/opencascade-rs/blob/main/crates/opencascade/src/mesh.rs` (the reference tessellation walk)
+
+**Steps:**
+1. Bridge: `BRepMesh_IncrementalMesh` with **both** linear AND angular deflection (the opencascade-rs high-level API only exposes linear — bind the full constructor), `TopExp_Explorer` over `TopAbs_FACE`, `BRep_Tool::Triangulation` + node/triangle iteration with `TopLoc_Location` transform applied to nodes, `TopAbs_REVERSED` winding flip, `BRepGProp::VolumeProperties` + `GProp_GProps::Mass`, `Bnd_Box` + `BRepBndLib::Add`.
+2. Rust API: `tessellate(shape, linear_deflection, angular_deflection) -> Result<MeshData, OcctError>` (`MeshData { vertices: Vec<[f64;3]>, triangles: Vec<[u32;3]> }`), `volume(shape) -> Result<f64, OcctError>`, `bbox(shape) -> Result<([f64;3],[f64;3]), OcctError>`.
+3. Test: tessellate the box from `fixtures/box.step` at deflection 0.1/0.5 → triangle count within ±20 % of the count recorded in `fixtures/box.graph.json`-adjacent stats (extend `scripts/make_fixtures.py` to dump a `<name>.stats.json` with Python's per-part triangle counts if not already available); volume of a 10 mm box ∈ [999, 1001] mm³.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p occt-bridge mesh 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** proxy-bbox fallback policy (converter concern, Task 28).
+
+## Task 28: Converter crate — XCAF walk, nodeIds, graph.json parity
+
+**Depends on:** Task 27
+**Files:**
+- Create: `services/geometry-rs/crates/converter/{Cargo.toml,src/lib.rs,src/{tree.rs,node_ids.rs,units.rs}}`
+- Modify: `services/geometry-rs/crates/geometry-types/src/wire.rs` — add `ConvertRequest/ConvertResponse/ConvertOptions/ConvertStats` (mirror `services/geometry/app/schemas.py` exactly, including defaults `linearDeflection=0.1, angularDeflection=0.5, compress=true`)
+- Copy from (precedent): `services/geometry/app/convert.py` — the whole file (594 LOC), function-by-function
+
+**Steps:**
+1. Port `_read_step` → `_count_leaf_instances` (max_parts limit → typed `LimitExceeded` error) → `_build_tree` (recursive XCAF walk; per-unique-part tessellation cached by label entry string; per-part tessellation failure ⇒ bbox-proxy mesh + warning, never abort) → `_assign_node_ids` (SHA1 of `"{geometryHash}:{parentPath}:{siblingOrdinal}"`, first 16 hex chars — the STRING construction must match Python byte-for-byte; read `_assign_node_ids` and `_geometry_hash` (grep for it) and replicate the exact hash-input formatting including separators and ordinal formatting) → `_compute_world_bboxes`.
+2. Port `_detect_source_unit` (regex over raw STEP text — pure Rust `regex`, copy the pattern).
+3. Parity test (fixture-gated): convert `fixtures/plates.step` → produced graph must equal `fixtures/plates.graph.json` with: nodeIds **byte-identical**, tree shape identical, floats within 1e-6 relative (transforms/bboxes/volumes), colors identical. Any nodeId mismatch is a hard failure — print both hash inputs on mismatch.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p converter 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed, including graph parity for box, plates, nested
+```
+
+**Out of scope:** GLB output (Task 29).
+
+## Task 29: GLB writer (`glb` crate, write half)
+
+**Depends on:** Task 28
+**Files:**
+- Create: `services/geometry-rs/crates/glb/src/write.rs`
+- Copy from (precedent): `services/geometry/app/glb.py` (180 LOC — the entire file)
+
+**Steps:**
+1. Port `write_glb`: node tree mirrors the graph 1:1; every node `extras: {"nodeId": ...}`; identical `geometryHash` shares one glTF mesh; materials deduped by RGBA; area-weighted smooth vertex normals (port the `np.add.at` accumulation as an index loop); buffers laid out as pygltflib does (positions f32, indices u32, ARRAY_BUFFER/ELEMENT_ARRAY_BUFFER targets). Write the GLB container (header + JSON + BIN, 4-byte padding).
+2. Vertices are baked world-space with identity node transforms — replicate exactly (the viewer and the Task 4 reader both tolerate either, but parity means matching Python's choice).
+3. Round-trip test: `converter` output for `plates.step` → `write_glb` → Task 4 `read_assembly_glb` → `validate_against_graph` passes; triangle totals equal the converter's tessellation totals; two of the four `M5-SHCS` nodes reference the same mesh index (parse the JSON chunk to assert mesh sharing).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p glb write 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** compression (Task 30).
+
+## Task 30: meshopt encode pipeline
+
+**Depends on:** Task 29
+**Files:**
+- Create: `services/geometry-rs/crates/glb/src/meshopt_encode.rs`
+- Copy from (precedent): behavior of `gltf-transform meshopt` (the only mode used — see `services/geometry/app/optimize.py`); spec `https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md`
+
+**Steps:**
+1. Implement quantize (positions per gltf-transform defaults) → vertex-cache reorder (`meshopt::optimize_vertex_cache` + `optimize_vertex_fetch`) → `encode_vertex_buffer` / `encode_index_buffer` (**encode version 0** for decoder compatibility — set via `encode_gltf`/`encode_index_version` equivalents in the meshopt crate) → rewrite bufferViews with `EXT_meshopt_compression` extension JSON + `extensionsRequired`.
+2. HARD CONSTRAINT: node graph untouched — no join/flatten/dedup/prune (that's why Python never used `gltf-transform optimize`). Only bufferView-level rewriting.
+3. Tests: (a) encode `plates` GLB → Task 4 reader decodes it → `validate_against_graph` passes and max vertex error vs pre-encode ≤ the Task 5 measured bound; (b) compressed size < 60 % of uncompressed for the plates fixture (gltf-transform achieves well under this); (c) `extras.nodeId` preserved on every node (port `test_optimize.py::compression preserves extras`).
+4. Escape hatch: if quantization here exceeds the Task 5 bound, raise quantization bits until it passes and record final settings in `SPIKE-QUANTIZATION.md`.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p glb meshopt_encode 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** other gltf-transform features (simplification, texture handling — the pipeline has no textures).
+
+## Task 31: Server `/convert` route + endpoint tests
+
+**Depends on:** Tasks 21, 30
+**Files:**
+- Modify: `services/geometry-rs/crates/server/src/routes.rs` — add `/convert`
+- Copy from (precedent): `services/geometry/app/main.py` `/convert` handler (line 68 onward) and `services/geometry/tests/{test_endpoint.py,test_limits.py}`
+
+**Steps:**
+1. `POST /convert`: auth → URL validation (all three URLs) → semaphore try-acquire (429 BUSY) → tempdir (`tempfile` crate) → streamed download with size cap → `converter::convert(...)` in `spawn_blocking` (413 `LIMIT_EXCEEDED` for part cap; per-part warnings pass through) → meshopt encode (failure ⇒ keep uncompressed + warning, mirroring `compress_glb` fallback) → PUT GLB then graph.json with `Content-Type` + `x-upsert: true` headers (upload failure ⇒ 502 `UPLOAD_FAILED`) → `ConvertResponse { ok, componentCount, unit, stats: { convertMs, meshTriangles, warnings } }`.
+2. Endpoint tests against the Task 21 storage stub: full round-trip on `plates.step` (assert the stub captured both PUTs and the graph parses), read-failure 4xx, size-cap rejection, part-cap 413, busy 429.
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo test -p server convert 2>&1 | tail -3
+# Expected: "test result: ok." 0 failed
+```
+
+**Out of scope:** switching `assembly-convert.ts` (Task 35).
+
+## Task 32: Rust fixture generator
+
+**Depends on:** Task 26
+**Files:**
+- Create: `services/geometry-rs/crates/occt-bridge/src/bridge/primitives.rs` + shim (BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder, gp_Trsf/gp_Vec transforms, STEPCAFControl_Writer, XCAF SetColor/AddShape/NewShape/AddComponent/UpdateAssemblies)
+- Create: `services/geometry-rs/crates/converter/src/bin/make_fixtures.rs`
+- Copy from (precedent): `services/geometry/tests/fixtures/make_fixtures.py` (133 LOC)
+
+**Steps:**
+1. Bridge the fixture-writing surface (listed above — it's the test-only half of the §3 inventory in the spec).
+2. Port `make_fixtures.py` to a Rust bin producing the same `box.step`/`plates.step`/`nested.step` into `services/geometry-rs/fixtures/`.
+3. Cross-check: Rust-generated `plates.step` fed through the Rust converter yields the same component count/names as the Python-generated one (nodeIds may differ if STEP entity ordering differs — assert on names/counts/structure here, NOT hashes).
+
+**Verify:**
+```bash
+cd services/geometry-rs && cargo run -p converter --bin make_fixtures && ls fixtures/*.step
+# Expected: box.step plates.step nested.step regenerated
+```
+
+**Out of scope:** deleting the Python fixture script (Task 35).
+
+## Task 33: Converter parity gate
+
+**Depends on:** Tasks 31, 32
+**Files:**
+- Create: `services/geometry-rs/scripts/convert_compare.py`
+- Modify: `services/geometry-rs/SHADOW-RESULTS.md` — converter section
+
+**Steps:**
+1. Script: for each STEP in a given directory (fixtures + any real customer STEP files the user provides), run Python `convert_step` and the Rust converter binary; diff graph.json (nodeIds byte-equal, floats 1e-6) and GLB structure (node count, mesh sharing, triangle totals, extras.nodeId set equality). Record timings both sides.
+2. Same gate rule as Task 22: at least one real customer STEP (ask the user) or STOP.
+3. Viewer smoke: load one Rust-produced meshopt GLB + graph in the running dev app (user-assisted via the `/test` skill if a browser check is wanted) — the join in `packages/viewer/src/useAssembly.ts` must produce a full `nodesById` map.
+
+**Verify:**
+```bash
+cd services/geometry-rs && python scripts/convert_compare.py fixtures/ && grep -A5 "## Converter" SHADOW-RESULTS.md
+# Expected: PASS per model, nodeId sets byte-identical, timings recorded
+```
+
+**Out of scope:** production cutover.
+
+## Task 34: Dockerfile + CI workflow
+
+**Depends on:** Task 31
+**Files:**
+- Create: `services/geometry-rs/Dockerfile`
+- Create: `.github/workflows/geometry-rs.yml`
+- Copy from (precedent): `.github/workflows/geometry.yml` (triggers/structure), `services/geometry/Dockerfile` (healthcheck pattern)
+
+**Steps:**
+1. Dockerfile: stage 1 `rust:1-bookworm` — `cargo build --release -p server` (OCCT builds inside; use BuildKit cache mounts for `/usr/local/cargo/registry` and `target/`); stage 2 — try `gcr.io/debian12:latest`-class minimal (`debian:bookworm-slim`): copy the binary, `EXPOSE 8000`, `HEALTHCHECK CMD curl -f http://localhost:8000/health` (install curl or use a tiny healthcheck binary — simplest: `wget -qO-` from busybox layer or compile a `--health` flag into the server that curls itself; pick the simplest that works and note it). Check at build time whether the binary needs `libfontconfig`/`libgl` (OCCT sometimes links them even headless): `ldd` the binary in stage 1; add only the apt packages `ldd` proves are needed.
+2. CI workflow: on PR/push touching `services/geometry-rs/**`: jobs `test` (cargo test --release with `Swatinem/rust-cache@v2` — first uncached run ~25 min, note the timeout at 45 min; fixture-dependent tests skip in CI since fixtures are ungenerated — that's the designed behavior; unit + calibration + parity-on-synthetic still run) and `docker` (build only, `push: false`, GHA cache — mirror `geometry.yml`).
+3. Do NOT add to `deploy.yml` matrix or `sst.config.ts` — deployment topology belongs to `.ai/specs/2026-07-06-geometry-service-deployment.md` and Task 35's approval.
+
+**Verify:**
+```bash
+docker build -t geometry-rs-test services/geometry-rs 2>&1 | tail -3 && docker run --rm -d -p 54019:8000 -e GEOMETRY_DEV_MODE=true --name geomrs geometry-rs-test && sleep 2 && curl -s http://localhost:54019/health && docker rm -f geomrs
+# Expected: build succeeds; health returns {"ok":true,"version":"..."}
+```
+
+**Out of scope:** pushing images, SST resources, prod env vars.
+
+## Task 35: Full cutover + Python removal — **requires explicit user approval before starting**
+
+**Depends on:** Tasks 22 + 33 green on real models, user sign-off
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts` — remove `GEOMETRY_PLAN_SERVICE_URL` fallback (single `GEOMETRY_SERVICE_URL`)
+- Modify: `packages/env/src/index.ts` — remove `GEOMETRY_PLAN_SERVICE_URL`
+- Modify: `packages/dev/src/services/apps.ts` + `packages/dev/src/env.ts` — spawn only the Rust service on the primary geometry port
+- Delete: `services/geometry/` (entire Python service), `.github/workflows/geometry.yml`
+- Rename: `services/geometry-rs/` → `services/geometry/` (update workflow paths, dev spawn paths, script relative paths)
+- Modify: `.ai/rules/*` and any AGENTS.md referencing the Python service (grep `services/geometry` across `.ai/` and `*/AGENTS.md`; update per `.ai/rules/keep-sources-in-sync.md`)
+
+**Steps:**
+1. Confirm with the user: shadow results accepted, real-model gates passed, deployment story (per the deployment spec) agreed.
+2. Execute the file moves/deletes above; re-run the full Rust suite + `pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/dev`.
+3. Update `.ai/lessons.md` with any port lessons learned (format: Context → Problem → Rule → Applies to).
+
+**Verify:**
+```bash
+cd services/geometry && cargo test 2>&1 | tail -3 && pnpm exec turbo run typecheck --filter=@carbon/jobs --filter=@carbon/dev 2>&1 | tail -3 && ! grep -rn "geometry-rs" .github/workflows/ packages/dev/src/
+# Expected: all green; no stale geometry-rs references
+```
+
+**Out of scope:** SST/production deployment execution (separate spec), Redis job store.
diff --git a/.ai/plans/2026-07-10-geometry-service-rust-rewrite.md b/.ai/plans/2026-07-10-geometry-service-rust-rewrite.md
new file mode 100644
index 0000000000..6c1ef19ef2
--- /dev/null
+++ b/.ai/plans/2026-07-10-geometry-service-rust-rewrite.md
@@ -0,0 +1,195 @@
+# Geometry Service Rust Rewrite — Feasibility & Phased Plan
+
+**Date:** 2026-07-10
+**Status:** Draft — design decisions need sign-off before execution
+**Scope:** `services/geometry` (Python/FastAPI → Rust), callers in `packages/jobs`, deployment
+
+---
+
+## 0. TL;DR / Recommendation
+
+- **Do not adopt `opencascade-rs` as-is.** It has zero XCAF/assembly support (no `STEPCAFControl_Reader`, no `XCAFDoc_ShapeTool`/`ColorTool` — names, instance transforms, colors are all missing). The service's core value is assembly-structured STEP ingestion; opencascade-rs only reads STEP collapsed to a single shape.
+- **Do not use napi-rs to embed the pipeline into `packages/jobs`.** Planning runs 10+ minutes of saturated CPU; the Inngest functions run *inside the ERP app* on a 2 vCPU / 4 GB Fargate task. Embedding would starve the web app, balloon its image with OCCT, and tie multi-minute jobs to ERP deploy lifecycle. Details in §6.
+- **Recommended shape:** single static Rust binary (axum), same HTTP contract as today (`/health`, `/convert`, `/plan`, `/plan/{jobId}`), delivered in two phases:
+ - **Phase A — Rust planner, no OCCT at all.** Change `/plan` to consume the **GLB + graph.json that `/convert` already produced** instead of re-reading the STEP. The planner becomes pure Rust (parry3d, rstar, nalgebra, rayon). This is 76% of the code (`plan.py` = 4,103 of 5,410 app LOC) and essentially 100% of the performance pain.
+ - **Phase B — Rust converter.** Write a small, owned cxx bridge over `occt-sys` exposing the ~15 OCCT classes `convert.py` actually uses (inventory in §3). Write GLB with `gltf-json` + in-process `meshopt` crate — this also deletes the Node 20 + gltf-transform shell-out.
+- **Deployment simplification is real but bounded:** the service is *not deployed anywhere today* (CI builds the Docker image with `push: false`; no SST entry, no compose entry). The draft spec `.ai/specs/2026-07-06-geometry-service-deployment.md` plans a Fargate service either way. Rust changes the *image* (Python 3.12 + OCCT wheel + Node 20 + gltf-transform → one ~50–100 MB static binary in distroless), not the topology.
+- **Fallback option (smallest blast radius):** keep the Python service, rewrite only the planning hot core as a PyO3 extension. Captures most of the perf win, none of the deployment win. See §7.
+
+---
+
+## 1. Ground truth (verified 2026-07-10)
+
+### Current service
+- 5,410 app LOC Python: `plan.py` 4,103 · `convert.py` 594 · `main.py` 354 · `glb.py` 180 · rest small.
+- OCCT usage is **confined to `convert.py`** (+ test fixtures). `plan.py` never imports OCP directly — it re-reads the STEP through convert.py's reader to get world-space meshes.
+- Perf hot spots are **all in planning**, per in-code profiling notes:
+ - Per-sample fcl narrowphase collision during removal-path sweeps (up to 400 samples/path, `num_max_contacts=100000`). One past profile: ~86% of total plan time, 53M contact constructions on a real assembly.
+ - `mesh.contains` ray-casts (embedded solids, fastener ring probes), `fcl.distance` adjacency (budget-capped at 20k pairs), SVD/eigh for fastener axes and sandwich tensors.
+ - No SDFs, no convex decomposition, no voxelization — every primitive maps 1:1 onto mature Rust crates.
+- Conversion is OCCT-bound (C++ already); Python only adds per-face tessellation loop overhead and the GLB assembly. The gltf-transform compression is a `subprocess.run("gltf-transform meshopt in.glb out.glb")` with Node startup cost.
+- scipy and rtree are **transitive deps only** — zero direct call sites. Nothing to port for them.
+
+### Callers & deployment
+- Exactly two callers, both Inngest tasks in `packages/jobs`:
+ - `assembly-convert.ts` → `POST /convert` (synchronous; payload: signed GET url for STEP + signed PUT urls for GLB/graph; Inngest `retries: 2`; upload urls minted with `upsert: true` for idempotent retries).
+ - `assembly-plan.ts` → `POST /plan` (202) then polls `GET /plan/{jobId}` every 15 s, 30-min budget, 60 s per-request timeout, handles 404-after-restart with up to 3 re-submits. Plan JSON returned inline in the poll response; the *job* uploads `plan.json` to storage.
+- Jobs run inside the ERP app (`apps/erp/app/routes/api+/inngest.ts`, `inngest/remix` serve), deployed by SST to Fargate (2 vCPU / 4 GB, `node:22-slim`).
+- `/plan` job store is an in-process dict (1 h TTL) — restart loses jobs; callers recover by re-submitting.
+- Contract consumers: `packages/viewer` (`types.ts` mirrors graph.json; `useAssembly.ts` joins GLB nodes to graph via `extras.nodeId`; `plan.ts` expects plan version 3). Contract doc: `.ai/specs/2026-07-04-animated-work-instructions-contracts.md`.
+- Test suite: 68 tests; 45 in `test_plan.py` encode the planning semantics (fastener order, sandwich gaskets, captive parts, escape BFS, determinism). Fixtures generated programmatically with OCP; storage faked with an in-process HTTP stub.
+
+### Rust ecosystem (researched 2026-07)
+- **opencascade-rs** (bschwind): active but hobby-paced, one maintainer, no releases since 0.2.0 (Aug 2023) — you'd pin a git rev. Binds via hand-written cxx bridges per OCCT module. Has: `STEPControl_Reader` (single-shape only), good per-face `BRepMesh_IncrementalMesh` tessellation. **Missing: the entire XCAF/STEPCAF surface.** Known hazard: OCCT exceptions can abort across the cxx boundary (issue #172) — needs defensive wrapping.
+- **Mitigating fact:** its `occt-sys` crate already **compiles and links `TKXCAF`, `TKDESTEP`, `TKRWMesh`, `TKDEGLTF`** in the static OCCT build (pinned OCCT 7.8.1; upstream is 8.0.0). Exposing `STEPCAFControl_Reader` + XCAF tools is cxx bridge work only — no build-system surgery. Estimate 1–3 weeks focused FFI, permanently owned by us.
+- **Pure-Rust STEP is a dead end for assemblies:** fornjot archived; truck's STEP *input* immature, no assembly/color support; ruststep is a schema parser, not an evaluatable B-rep (foxtrot tried and died). OCCT stays mandatory for ingestion.
+- **Post-tessellation ecosystem is strong:** parry3d 0.29 (Dimforge, active) covers narrowphase contact manifolds, exact distance, ray-cast containment, BVH; rstar replaces rtree; `meshopt` crate binds meshoptimizer with full encoder surface (the EXT_meshopt_compression *codec*), but the document-level pipeline (quantize → reorder → encode → rewrite bufferViews/extension JSON) must be hand-written (~days); `gltf-json` can write GLB but it's low-level DIY.
+- **napi-rs v3** (Jul 2025) has a mature prebuild story, but nobody publicly ships native OCCT through it; the Node world uses emscripten/WASM (occt-import-js) instead. Statically linked `.node` with OCCT ≈ 30–100 MB per platform, built natively per-OS on CI.
+- **No public prior art** for "STEP→glTF in Rust" or "OCCT microservice in Rust" — we'd be first. Existing converters are C++ (Mayo, step2gltf) or WASM (occt-import-js).
+
+---
+
+## 2. Target architecture
+
+One Rust crate workspace, one binary, same wire contract:
+
+```
+services/geometry-rs/
+├── Cargo.toml # workspace
+├── crates/
+│ ├── server/ # axum: /health, /convert, /plan, /plan/{jobId}
+│ │ └── (auth bearer, url validation, semaphore slots, httpx-equivalent via reqwest)
+│ ├── planner/ # Phase A: pure Rust port of plan.py
+│ │ └── (parry3d, rstar, nalgebra, rayon)
+│ ├── converter/ # Phase B: STEP→tree+meshes via occt-bridge
+│ ├── glb/ # GLB write (gltf-json) + meshopt compression pipeline
+│ └── occt-bridge/ # Phase B: owned cxx bridge over occt-sys (~15 classes)
+└── Dockerfile # 2-stage: rust builder → distroless/cc, single binary
+```
+
+Crate choices:
+
+| Concern | Today | Rust |
+|---|---|---|
+| HTTP server | FastAPI + uvicorn | axum + tokio |
+| Wire schemas | Pydantic v2 (camelCase) | serde with `#[serde(rename_all = "camelCase")]` |
+| Download/upload signed URLs | httpx (streamed, size-capped) | reqwest (streamed, size-capped) |
+| Collision narrowphase + contacts | trimesh → python-fcl | parry3d (`TriMesh`, contact manifolds, BVH) |
+| Exact pair distance | fcl.distance | parry3d distance queries |
+| Point-in-mesh containment | `mesh.contains` (ray-cast) | parry3d point projection / ray-cast parity |
+| Spatial index | rtree (via trimesh) | rstar |
+| Linear algebra (SVD, eigh) | numpy | nalgebra |
+| Parallelism | none (single-threaded Python) | rayon (across candidate directions / path samples / pairs) |
+| STEP + XCAF read, tessellation | cadquery-ocp (OCP) | owned cxx bridge over occt-sys |
+| GLB write | pygltflib (hand-built) | gltf-json (hand-built, same 1:1 nodeId contract) |
+| meshopt compression | shell-out to gltf-transform (Node 20) | in-process `meshopt` crate + hand-written glTF pipeline |
+| SHA-1 nodeIds | hashlib | `sha1` crate (byte-identical scheme) |
+
+**Invariants that must hold bit-for-bit or contract-for-contract:**
+- `nodeId = sha1("{geometryHash}:{parentPath}:{siblingOrdinal}")[:16]` — same string construction, same hex slice. Existing stored graphs/plans reference these IDs.
+- graph.json shape (`version: 1`, `unit: "mm"`, col-major 4×4 transforms, RGBA colors, bbox, volume).
+- GLB: every node has `extras.nodeId`, identical `geometryHash` shares one mesh, materials deduped by RGBA, no node-graph rewriting during compression (this is why only `meshopt`-style compression is allowed, never join/flatten/dedup).
+- plan.json version 3 contract (`sequence`, `components{motion, tier, confidence, groupId, mergedInto}`, `groups`, `warnings`), fixed-sequence mode included.
+- Determinism: same input → same plan (`test_plan_is_deterministic` parity).
+
+---
+
+## 3. Phase B dependency: the owned OCCT bridge surface
+
+Exact classes `convert.py` uses today (must be bridged; nothing more):
+
+- Reader/doc: `STEPCAFControl_Reader` (SetColorMode/SetNameMode/SetLayerMode/SetMatMode/ReadFile/Transfer), `Interface_Static::SetCVal("xstep.cascade.unit","MM")`, `IFSelect_ReturnStatus`, `TDocStd_Document`
+- XCAF: `XCAFDoc_DocumentTool::ShapeTool`, `XCAFDoc_ShapeTool` (IsAssembly, GetComponents, GetReferredShape, GetLocation, GetShape, GetFreeShapes), `XCAFDoc_ColorTool::GetColor` (+ `XCAFDoc_ColorSurf`/`ColorGen`)
+- Labels/attrs: `TDF_Label`, `TDF_LabelSequence`, `TDF_Tool::Entry`, `TDataStd_Name`, `TCollection_*`
+- Topology: `TopoDS_Shape`, `TopoDS::Face`, `TopExp_Explorer`, `TopAbs_FACE`, `TopAbs_REVERSED`, `TopLoc_Location`
+- Mesh/props: `BRepMesh_IncrementalMesh` (linear + angular deflection — angular needs a trivial bridge addition upstream lacks), `BRep_Tool::Triangulation` (+ node/triangle iteration), `BRepGProp::VolumeProperties` + `GProp_GProps`, `Bnd_Box` + `BRepBndLib::Add`, `Quantity_ColorRGBA`
+- Test fixtures additionally need: `BRepPrimAPI_MakeBox/MakeCylinder`, `gp_Trsf/gp_Vec`, `STEPCAFControl_Writer`, XCAF SetColor/AddShape/NewShape/AddComponent/UpdateAssemblies
+
+Notes:
+- Source-unit detection is a **regex over raw STEP text** in Python, not an OCCT call — ports as plain Rust.
+- Wrap every OCCT call in exception guards (`OCC_CATCH_SIGNALS` / try-catch in the C++ shim returning Result) — opencascade-rs #172 shows aborts are real.
+- Decide: vendor the bridge in-repo (recommended — small, auditable, no upstream dependency on one busy maintainer) vs. PR upstream (nice-to-have later).
+- occt-sys pins OCCT 7.8.1. Acceptable; note 8.0.0 exists if we ever need it (would mean owning the occt-sys fork too).
+
+---
+
+## 4. Phased execution plan
+
+### Phase A — Rust planner (biggest win, no OCCT) — est. 4–6 weeks
+1. **Contract change (small, jobs-side):** `/plan` payload gains `source: { glbUrl, graphUrl }` instead of the STEP url. `assembly-plan.ts` already runs strictly after convert (lazy, on-demand) and `modelUpload` has `glbPath`/`graphPath` — mint signed GET urls for those instead. Version the payload so old/new services can coexist during rollout.
+2. **GLB ingestion in planner:** decode meshopt-compressed GLB (meshopt crate has decoders; gltf-rs won't decode `EXT_meshopt_compression` natively — hand-roll the bufferView decode, same code we need for Phase B encode anyway). Join meshes to graph.json by `extras.nodeId`, apply world transforms.
+ - **Risk to burn down first (spike, week 1):** quantization error from meshopt vs `PENETRATION_TOLERANCE_MM = 0.15` (scaled to 2.5× linearDeflection). Measure on real assemblies. Mitigations if it bites: raise position quantization bits at encode time, or have `/convert` also upload an uncompressed GLB variant for the planner. Decide by measurement, not vibes.
+3. **Port planning pipeline** in dependency order, mirroring `plan.py`'s phases: seated broadphase pair depths → ordering adjacency → fastener classification (name regex + SVD axis cascade) → rigid merge (union-find + containment ray-casts) → fastener ring joints → sandwich detection (eigh of contact tensor) → greedy disassembly (tier 1 linear / tier 2 "L" / tier 3 escape BFS / group extraction) → base re-selection → precedence DAG + preference topo sort → forward verification.
+4. **Tests first, as golden:** port all 45 `test_plan.py` cases before/alongside each phase (most build synthetic meshes in-memory — no OCCT needed, translate to parry TriMesh builders). Add a **shadow-comparison harness**: run Python and Rust planners on the same real assemblies, diff sequences/tiers/warnings. Semantic parity gate, not float parity.
+5. **Parallelize** with rayon only after parity: candidate directions per part, path samples, pair loops. Keep determinism (ordered reduction / stable sort of results).
+6. **fcl → parry3d calibration:** penetration depth and contact manifold conventions differ between FCL and parry. Write a small calibration test set (box-box, cyl-in-bore, coplanar contact) asserting the tolerance semantics the planner depends on. Budget real time here — this is the subtle-bugs zone.
+7. Ship as `/plan` v2 route in the Rust binary; Python service keeps serving `/convert`. Two containers during transition (or one Rust binary proxying `/convert` to Python — simpler: run both behind the jobs-side env urls, `GEOMETRY_PLAN_SERVICE_URL` temporary override).
+
+### Phase B — Rust converter + GLB/meshopt in-process — est. 3–4 weeks
+1. Build `occt-bridge` (surface in §3) against occt-sys. CI-cache the OCCT static build (~20–25 min cold; cache makes it minutes).
+2. Port `convert.py`: XCAF walk → per-unique-part tessellation cache (keyed by label entry) → nodeId assignment → world bboxes → GLB write via `gltf-json` (1:1 node contract) → in-process meshopt encode (quantize + reorder + `EXT_meshopt_compression`, v0 encoding for decoder compat).
+3. Port fixture generator (`make_fixtures.py`) using the bridge's BRepPrimAPI subset; port `test_convert.py` (nodeId stability across runs is the key test) + endpoint/limit/api tests.
+4. Byte-diff gate: same STEP in → Rust vs Python graph.json semantically identical (nodeIds byte-identical, floats within epsilon); GLB loads in `packages/viewer` with identical `nodesById` join.
+5. Per-part tessellation failure → bbox proxy + warning (preserve the never-abort behavior).
+6. Retire the Node stage from the image.
+
+### Phase C — cutover + deployment — est. 1 week
+1. Single Rust image: `FROM rust:… AS build` (static OCCT via occt-sys) → `FROM gcr.io/distroless/cc` (or debian-slim if OCCT needs fontconfig etc. — verify; the Python image needed libgl/fontconfig, static OCCT may not). Target: one binary, ~50–100 MB image vs today's Python+OCCT+Node stack.
+2. Wire into the deployment plan that already exists (`.ai/specs/2026-07-06-geometry-service-deployment.md`): add to `deploy.yml` matrix, SST `CarbonGeometryService` on `CarbonCluster`, `/health` checks, `GEOMETRY_SERVICE_API_KEY` injection. The Rust rewrite slots into that spec unchanged — smaller image, faster cold start, lower memory.
+3. Optional (carried over from that spec): externalize the `/plan` job store to Redis. In Rust it's a `DashMap` with TTL initially — same restart semantics as today; callers already recover via re-submit. Don't couple this to the rewrite.
+4. Shadow period: run Python and Rust side by side on real conversions/plans (jobs-side env flag per company or percentage), compare outputs, then flip `GEOMETRY_SERVICE_URL` and delete `services/geometry` (Python).
+
+---
+
+## 5. Expected gains (honest estimates)
+
+- **Planning:** the dominant costs are per-contact Python object construction (53M contacts on one profile) and single-threaded orchestration of native calls. Rust removes marshaling entirely and rayon parallelizes candidate sweeps. Realistic **5–20× wall-clock** on real assemblies, more on many-core boxes; the 10-minute plans are the target. (Narrowphase itself is native in both — the win is overhead removal + parallelism, not "Rust is faster than C++ FCL".)
+- **Conversion:** OCCT dominates; expect **1.5–3×** from removing the per-face Python loops, the numpy round-trips, and the Node subprocess (startup + double file I/O). Memory footprint drops materially.
+- **Image/deploy:** Python 3.12 + 70 MB OCP wheel + Node 20 + gltf-transform + numpy/scipy/trimesh/fcl → one static binary. Faster cold start, smaller attack surface, one runtime to patch.
+- **What Rust does NOT buy:** STEP parsing speed (same OCCT), fewer OCCT bugs (same OCCT), simpler service topology (still a sidecar service — see §6 for why that's correct).
+
+---
+
+## 6. napi-rs option — evaluated, rejected (for the pipeline)
+
+Considered: compile the Rust pipeline as a Node native addon consumed directly by `packages/jobs`, deleting the microservice.
+
+Rejected because:
+1. **Placement:** Inngest functions execute inside the ERP app (Fargate 2 vCPU / 4 GB). A 10-minute CPU-saturating plan inside the web app's task starves request handling; convert spikes would do the same. We'd end up carving out a dedicated worker service anyway — which is just the microservice again, with harder packaging.
+2. **Image coupling:** ERP image would carry OCCT (30–100 MB native addon) and redeploying ERP would kill in-flight plans; today's poll/re-submit protocol survives geometry restarts independently.
+3. **No prior art:** nobody ships native OCCT via napi; the Node ecosystem uses WASM (occt-import-js) for a reason. First-mover cost with no upside vs. a plain Rust HTTP service.
+4. **Scaling:** a sidecar service scales independently of ERP (the concurrency semaphore + 429 protocol already exists for this).
+
+Where napi-rs *could* make sense later: exposing the pure-Rust **planner** crate to Node for local/dev tooling or unit tests in `packages/viewer` — cheap because that crate has no OCCT. Not part of this plan.
+
+## 7. Fallback option — PyO3 hot-core (if appetite shrinks)
+
+Keep the Python service and OCCT via cadquery-ocp; rewrite only the collision/path-sweep core (`_contacts_at`, `_path_is_clear`, `_path_blockers`, `_seated_pair_depths`, BVH cache) as a Rust extension with PyO3/maturin using parry3d + rayon.
+
+- Captures the large majority of the perf win at ~2–3 weeks effort.
+- Zero contract risk, zero OCCT FFI, tests stay green as-is.
+- Buys nothing on deployment (still Python + Node + OCP wheel image).
+- Reasonable as Phase 0 / de-risking step, or as the endpoint if the full rewrite loses priority.
+
+---
+
+## 8. Risks & mitigations
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| parry3d vs FCL penetration-depth/contact semantics differ → planner behavior drift | High | Calibration test set + 45 golden tests + shadow comparison on real assemblies before cutover |
+| meshopt quantization vs 0.15 mm penetration tolerance (Phase A plans from compressed GLB) | High | Week-1 spike; raise quantization bits or upload uncompressed variant if needed |
+| Owning the OCCT cxx bridge forever (one-off FFI, exceptions abort across boundary) | Medium | Small pinned surface (~15 classes), exception guards in C++ shim, vendored in-repo |
+| opencascade-rs/occt-sys unversioned (git-rev pin, OCCT 7.8.1) | Medium | Pin rev + vendor; we depend on occt-sys build only, not their API surface |
+| Float determinism across platforms (plan determinism test) | Medium | Stable sorts, ordered rayon reductions, fixed candidate ordering; determinism test in CI |
+| 4,103 LOC of dense geometric heuristics silently mis-ported | High | Port test-first, phase by phase; shadow-compare; never port two phases without green goldens |
+| OCCT build time in CI (~25 min cold) | Low | Cache occt-sys artifact; only rebuilds on rev bump |
+| plan.py evolves on this branch while port is in flight | Medium | Freeze planner semantics before Phase A port starts, or rebase goldens deliberately |
+
+## 9. Open decisions (need sign-off)
+
+1. **Phase A plan-from-GLB contract change** — planner consumes GLB+graph instead of STEP (recommended; enables the OCCT-free phase). Alternative: keep STEP input and pull the OCCT bridge into Phase A (merges A and B risk).
+2. **Vendor the cxx bridge in-repo vs. fork/PR opencascade-rs** — recommend vendor in `services/geometry-rs/crates/occt-bridge`.
+3. **PyO3 fallback as explicit Phase 0** — do the 2–3 week hot-core extension first to bank the perf win, then continue the full rewrite? Or straight to Phase A?
+4. **Service location/name** — `services/geometry-rs` during transition, renamed to `services/geometry` after Python deletion?
+5. Total estimate **8–11 weeks** for A+B+C (single senior dev, Rust+C++ comfortable). Acceptable?
diff --git a/.ai/playbooks/assembly-instructions-editor.md b/.ai/playbooks/assembly-instructions-editor.md
new file mode 100644
index 0000000000..6bb974379c
--- /dev/null
+++ b/.ai/playbooks/assembly-instructions-editor.md
@@ -0,0 +1,78 @@
+# Assembly Instructions Editor
+
+Last tested: 2026-06-11
+Route: /x/production/assemblies (list), /x/assembly/:id (full-screen editor)
+
+## Prerequisites
+- **Log in as `[email protected]`** (magic link via the Inbucket mail app at
+ `mail.<prefix>.dev`, mailbox "brad"), NOT the `[email protected]` bypass user:
+ the seat-rail demo data (items, model upload) is seeded into brad's
+ "Carbon" company; [email protected]'s "Carbon Development" company is empty,
+ so every item combobox renders only "Create Item".
+- A modelUpload with processingStatus = Success. The seed's conversion can
+ fail if the geometry service was down or hit the portless TLS issue —
+ re-trigger with a POST to the Inngest dev server
+ (`/e/dev`, event `carbon/assembly-convert` with
+ `{modelUploadId, companyId, userId}`).
+- DB must include the assembly migrations (step status enum, requirement
+ tables, assemblyGroup) or step status shows blank and adds fail.
+
+## Creating an instruction (item-first form)
+- `/x/production/assemblies` → "Add Assembly Instruction".
+- The Item combobox lists only replenishment = Make items (seed:
+ "X000000001 Seat Rail").
+- Selecting an item runs a model check: green "Model: <file> (N parts)"
+ enables Save; an amber "no processed 3D model" warning keeps it disabled.
+- Name is optional (defaults to the item name). Save redirects to
+ `/x/assembly/:id`.
+
+## Steps
+
+### 1. Navigate to the list
+- URL: `/x/production/assemblies`
+- Expected: breadcrumb "Production / Assemblies", Production sidebar group
+ shows Jobs / Procedures / Assemblies, table with Name/Status/Item/Model/
+ Processing columns and "Add Assembly Instruction" button.
+
+### 2. Open the editor
+- Click an instruction name link in the table.
+- Expected: full-screen editor at `/x/assembly/:id` — header with editable
+ name, DRAFT badge, Publish button, item link; left panel Steps | Parts
+ tabs; center 3D viewer with view cube (top-right) and footer controls
+ (prev/play/next, step slider, Ghost/Hidden/Solid toggle group); right
+ panel "STEP" heading.
+
+### 3. Parts tab (BOM tree)
+- Click the "Parts" tab in the left panel.
+- Expected: "N parts · M instances" header with a sort toggle button, rows
+ with color swatch / name / — count, gear button per row (hover).
+- Click a row: row highlights, viewer frames the part instances with an
+ emerald tint. Click again to clear.
+
+### 4. Add a step
+- Steps tab → "Add Step" button (footer of the left panel).
+- Expected: a step row appears (status dot + "Untitled step" + part count),
+ right panel shows Details | BOM | Requirements tabs with the step form.
+
+### 5. Requirements tab
+- Right panel → Requirements: inner tabs Tools | Notes | Std Notes | Media.
+- Tools tab has a catalog combobox + free-text input + Add per section
+ (Tools/Fixtures/Consumables); Notes has textarea + severity toggle;
+ Std Notes lists templates with Insert + Manage; Media has a dropzone.
+
+## Selector Notes
+- List rows: the instruction name is a link containing an "Open" button.
+- The left-panel tabs are "Steps" and "Parts"; right-panel tabs are
+ "Details", "BOM", "Requirements".
+- The ghost-mode buttons have aria-labels "Show future parts ghosted",
+ "Hide future parts", "Show all parts solid".
+- The status dot button label reads "Step status: <status>. Click to mark
+ <next>".
+- The 3D canvas takes a few seconds to load the GLB — sleep ~3s after
+ navigation before screenshots.
+
+## Common Failures
+- Step status shows "undefined" / requirement Add fails with a column error:
+ the local DB predates the assembly migrations — rebuild the database.
+- "The model has not been processed": the instruction's modelUpload has no
+ glbPath/graphPath — pick a Success row or convert a STEP file first.
diff --git a/.ai/research/3d-model-cad-capabilities.md b/.ai/research/3d-model-cad-capabilities.md
new file mode 100644
index 0000000000..7a68628ac4
--- /dev/null
+++ b/.ai/research/3d-model-cad-capabilities.md
@@ -0,0 +1,124 @@
+# 3D Model / CAD Capabilities (verified 2026-06)
+
+## Storage: `modelUpload` table
+
+Created in `packages/database/supabase/migrations/20240630115404_model-uploads.sql`:
+`id` (xid), `name`, `size`, `modelPath`, `autodeskUrn` (legacy APS translation URN),
+`itemId` FK, `companyId`, audit cols. Referenced by `item`, `job`, `salesOrderLine`,
+`quoteLine`, `purchaseOrderLine` etc. via `modelUploadId` columns (see many view
+migrations, e.g. `20250109000722_increase-numeric-values.sql`).
+
+Files live in Supabase storage (`private` bucket, `models/` path), served via
+`apps/erp/app/routes/file+/model+/$id.tsx` and `file+/model+/public.$.tsx`.
+
+## Viewers (packages/react)
+
+- `packages/react/src/ModelViewer.tsx` — built on **online-3d-viewer** (`OV.EmbeddedViewer`)
+ + three.js 0.163 (pinned in `packages/react/package.json`). Loads STEP/STL/etc.
+ client-side via occt-import-js WASM. Computes bbox/surface area/volume, recolors
+ meshes, adds lights. Limitations: no assembly tree exposure, no animation —
+ occt-import-js bakes transforms into vertices.
+- `packages/react/src/AutodeskViewer.tsx` (+ `autodesk.d.ts`) — Autodesk Platform
+ Services (Forge) viewer: token provider context, URN-based loading. Pairs with
+ `modelUpload.autodeskUrn`.
+
+## Onshape integration (active, not removed)
+
+`packages/ee/src/onshape/` (`client.ts`, `data.ts`) + routes
+`apps/erp/app/routes/api+/integrations.onshape.*`. OAuth, documents/versions/elements,
+BOM sync into Quotes/Jobs/Items (`QuoteBoMExplorer.tsx`, `JobBoMExplorer.tsx`,
+`BoMExplorer.tsx`). Metadata/BOM only — no geometry export. (Earlier cache notes said
+Onshape code was removed — wrong; `ONSHAPE_SECRET_KEY` in `packages/auth/src/config/env.ts`.)
+
+## Background jobs: Inngest (NOT Trigger.dev)
+
+`packages/jobs/src/inngest/` with `inngest` ^3.52.7 in `packages/jobs/package.json`
+(also `events.ts`, `schemas.ts`, `trigger.ts` in `packages/jobs/src/`). Existing
+model-related pattern: `packages/jobs/src/inngest/tasks/model-thumbnail.ts` calls a
+Supabase edge function (`thumbnail`) that screenshots the viewer page and stores a PNG.
+Older cache references to Trigger.dev are stale.
+
+## MES model display
+
+`apps/mes/app/components/JobOperation/JobOperation.tsx` renders a "Model" tab on
+`/x/operation/:operationId` using ModelViewer when the job/item has a model.
+
+## Assembly instructions (animated work instructions) — production module
+
+Part of the **production** module (not a standalone module): permissions are
+`production_<view|create|update|delete>`; there is no `Assembly` module enum
+value or `assembly_*` permission family.
+
+- Docs: `.ai/research/animated-work-instructions.md`,
+ `.ai/specs/2026-07-04-animated-work-instructions-design.md` (+ `-contracts.md`,
+ `.ai/plans/2026-07-04-animated-work-instructions.md`,
+ `.ai/specs/2026-07-04-assembly-editor-requirements.md`).
+- `services/geometry/` — Python/FastAPI + OCCT (cadquery-ocp): POST /convert turns a
+ STEP file (signed GET URL) into a meshopt-compressed GLB + graph.json (signed PUTs).
+ POST /plan (app/plan.py) runs greedy assembly-by-disassembly motion planning
+ (trimesh + python-fcl collision; tier 1 straight-line along world axes + part
+ principal axis, tier 2 lift-then-slide L motions, leftovers flagged with
+ blockedBy) and uploads plan.json (insertion motions by nodeId + assembly
+ sequence). Stable nodeIds in glTF node extras. Limits via GEOMETRY_* env vars;
+ bearer auth; GEOMETRY_DEV_MODE also disables TLS verification (portless CA).
+ CI: `.github/workflows/geometry.yml` (pytest + docker build).
+- `packages/viewer` (@carbon/viewer) — react-three-fiber v8 AssemblyViewer (with drei
+ GizmoViewcube) / AssemblyPlayer (ghost/hidden/solid future-parts modes, overlay nav
+ arrows, `onGraphLoaded`, `highlightedNodeIds`, `hiddenNodeIds`); steps form one
+ continuous timeline (LoopOnce auto-advance, global-seconds scrubber with step
+ ticks, m:ss elapsed/total display, `stepTimelineSeconds`); AssemblyStep has
+ optional `durationSeconds`; runtime keyframes from step motion JSON
+ (linear/L/helix/path/none); pure utils `graph.ts` (indexAssemblyGraph,
+ groupPartNodeIds) and `describe.ts` (describeStep auto-titles) with vitest coverage.
+- DB: `assemblyPlanJob`, `assemblyInstruction`, `assemblyInstructionStep` (status enum
+ Todo/Review/Done, groupIds), `assemblyInstructionStepRequirement`
+ (Tool/Fixture/Consumable/Note/Media; itemId FK → item, name snapshot, severity),
+ `assemblyStandardNote`, `assemblyGroup` (Cluster/Kit/Combination/Subassembly);
+ `modelUpload` gained processingStatus/glbPath/graphPath/partCount/processedAt;
+ `jobOperation`/`methodOperation` gained nullable `assemblyInstructionId`.
+ All RLS via `get_companies_with_employee_permission('production_*')`.
+- Inngest `assembly-convert` + `assembly-plan` (`packages/jobs/src/inngest/functions/tasks/`)
+ auto-trigger from `apps/erp/app/routes/api+/model.upload.ts` for .step/.stp uploads.
+ Env: GEOMETRY_SERVICE_URL / GEOMETRY_SERVICE_API_KEY (packages/env).
+- ERP: code lives in `apps/erp/app/modules/production/` (assembly functions appended to
+ production.service.ts/.models.ts/types.ts; UI in `ui/Assemblies/`). List route
+ `x+/production+/assemblies.tsx` (/x/production/assemblies) + `assemblies.new.tsx`,
+ mirroring procedures; full-screen editor stays at `x+/assembly+/$id`
+ (/x/assembly/:id) with `handle.module: "production"` like `x+/procedure+/`.
+ Editor: Steps|Parts left tabs — step search/filter, status dots, "N steps · est."
+ footer; Parts tab is the BOM tree with click-to-highlight, hide-parts, a Groups
+ section, and a selection toolbar + right-click context menu that creates
+ clusters/kits/combinations/subassemblies (subassembly auto-creates a child
+ instruction via `$id.groups.new`); Details|BOM|Requirements right tabs
+ (tools/notes/standard notes/media, per-step timeline length display);
+ auto-generated step titles; header shows version badge ("Edit N", bumped on
+ publish) + "By you · edited <relative>". Nav: "Assemblies" in the Production
+ sidebar group (useProductionSubmodules); create-instruction button on item Model
+ tab (gated on production_create). MES: Assembly tab in
+ `apps/mes/app/components/JobOperation/` (read-only playback + active step's
+ notes/tools/media via requirements in getJobOperationAssembly; serviceRole read).
+- BOM mapping: `assemblyPartMapping` table maps distinct model parts
+ (geometryHash, per modelUploadId) to engineering BOM items;
+ `getFlattenedBomMaterials` walks makeMethod → methodMaterial →
+ materialMakeMethodId (Make subassemblies) multiplying quantities;
+ `autoMatchAssemblyParts` does greedy token-similarity name matching with a
+ unique-quantity fallback. Editor Parts tab: "Match BOM" button, coverage
+ count, mapped readable-ID under each row with BOM-vs-model quantity
+ mismatch warnings, map/unmap in the part popover
+ (routes `$id.part-mappings.{new,auto,delete.$mappingId}`).
+- Planner consumption (the core flow — authors never hand-author motions):
+ "Generate Steps" on an empty step list creates draft steps from plan.json
+ (route `$id.steps.generate` → `generateAssemblyStepsFromPlan`: sequence
+ order, consecutive identical parts grouped, planConfidence + status Review;
+ triggers the assembly-plan Inngest pipeline when no plan exists). Assigning
+ parts to a step auto-fills its motion via `planMotionForParts`
+ (@carbon/viewer plan.ts) with a "Planned automatically" indicator; the
+ manual motion form is the override. plan.json loads in the editor loader
+ via `getAssemblyPlanJson`. The step camera frames the full insertion travel.
+- Test playbook: `llm/test-playbooks/assembly-instructions-editor.md`.
+ Verified e2e on the seat-rail seed: convert → plan (22 linear + 1 L + 8
+ flagged) → 27 generated steps → animated 1:01 timeline. Status/requirement/
+ group CRUD verified against a fully migrated local db.
+- Not yet done: share link, PDF export, undo/redo, annotations, kit-aware
+ step animation semantics, helix motions for detected fasteners (planner
+ emits linear for screws), deploy config for the geometry container.
diff --git a/.ai/research/animated-work-instructions.md b/.ai/research/animated-work-instructions.md
new file mode 100644
index 0000000000..4bb2941981
--- /dev/null
+++ b/.ai/research/animated-work-instructions.md
@@ -0,0 +1,169 @@
+# Animated Work Instructions from CAD: Research
+
+## Summary
+
+Research into building automated assembly work instructions: a system that ingests a
+CAD assembly (STEP et al.) and automatically generates animated, step-by-step 3D work
+instructions — assembly sequence, per-part insertion animations, fastener handling,
+exploded views, and step text — with a human-in-the-loop editor for the last 20%
+(torque specs, tools, tribal knowledge). Commercial tools in this category automate
+roughly 80% of authoring and report order-of-magnitude reductions in authoring time.
+Conclusion: the core is **deterministic geometry, not ML** — a tiered
+"assembly-by-disassembly" planner built on open-source components (OCCT, trimesh/FCL,
+pybullet, MIT-licensed Assemble-Them-All) is buildable, and Carbon already owns the
+surrounding product surface (items/revisions, methods, procedures, MES execution,
+model uploads, a 3D viewer) that point solutions have to integrate into via connectors.
+
+## Market patterns (point solutions in this category)
+
+- **Input:** STEP plus selected native formats; drag-and-drop, minutes-to-draft.
+- **Automated (~80%):** assembly sequence generation; per-part removal/insertion path
+ planning rendered as 3D animations, regenerated when the sequence or CAD changes;
+ step text; EBOM → MBOM → bill-of-process transformation; clearance/DFM flags;
+ recurring-subassembly recognition and reuse.
+- **Manual (~20%):** torque specs, adhesives, tools, safety, quality checks, step
+ reordering, build-tree reshaping, annotations, custom cameras.
+- **Execution layer:** shop-floor playback with cycle-time capture and operator
+ feedback, pushing run data to the customer's MES/ERP via connectors.
+- **Exports:** interactive web link, PDF/Word/PowerPoint.
+- **Positioning pattern:** "deterministic" geometric/physics reasoning rather than
+ generative output; standalone tools must bridge into someone else's MES/ERP — a
+ native ERP/MES suite can own the loop end-to-end. That is Carbon's wedge.
+- **Common gaps:** flexible parts (cables, gaskets) and non-geometric process steps
+ (bonding, curing, testing) remain manual; large assemblies stress browser rendering.
+
+## Algorithmic Foundations
+
+### 1. Assembly sequence planning (ASP)
+- Standard approach: **assembly-by-disassembly** — repeatedly find a part (or
+ subassembly) that can be removed collision-free from the assembled state; reverse the
+ order. Theory: Wilson & Latombe non-directional blocking graphs (NDBG), AND/OR graphs.
+- State of the art: **Assemble-Them-All** (SIGGRAPH Asia 2022, MIT license,
+ github.com/yunshengtian/Assemble-Them-All) — physics-guided disassembly path search
+ with point-vs-SDF collision; handles rotational/interlocked removals. **ASAP** (ICRA
+ 2024, github.com/yunshengtian/ASAP, **no license — contact authors**) adds gravity
+ stability with ≤k held parts.
+- Practical simplification used by commercial tools: greedy disassembly testing **6–26
+ candidate straight-line directions** (axis-aligned + part principal axes + mate/hole
+ axes) ≈ a sampled NDBG; covers the vast majority of real assemblies. Escalate
+ leftovers to RRT (OMPL) or physics search; flag the rest for the human editor.
+- Cost: direction-sampled greedy on a 100-part assembly = seconds–minutes CPU.
+ Physics-complete search = minutes–1 h.
+
+### 2. Collision detection
+- trimesh `CollisionManager` (MIT) wrapping python-fcl (BSD) is the fastest prototype
+ path; Bullet (zlib)/Jolt (MIT) as alternatives; point-vs-SDF sampling (à la
+ Assemble-Them-All) is robust to dirty CAD meshes and GPU-parallelizable.
+- Don't compute swept volumes explicitly (the best open-source code implements a
+ patent-pending method): densely sample the removal path (~100 poses) and run discrete
+ checks with a clearance epsilon. Sub-second per part with BVH broadphase.
+
+### 3. Part-removal motion planning
+- 3-tier cascade: (1) straight line along candidate axes → (2) two-segment "L" motions
+ (lift-then-slide) → (3) OMPL RRT in SE(3) / physics-guided search. Tiers 1–2 resolve
+ ~90%+ of steps.
+- **Threaded fasteners: don't plan, parameterize.** Once classified as a screw with axis
+ and pitch, removal is an analytic helix + linear retraction; for human instructions
+ only the axis and turn direction matter — the animation is a canned helix.
+
+### 4. Fastener detection in CAD
+- Real STEP files rarely contain thread geometry; fasteners are simplified cylinders.
+ Highest-ROI detectors, in order:
+ 1. **Name regex** against fastener-standard tables (M5, SHCS, DIN 912, ISO 4762,
+ McMaster part numbers) — purchased components almost always carry these names.
+ 2. **Geometry heuristic:** small part dominated by coaxial cylindrical faces + hex/
+ socket head, duplicated N times with identical geometry. (OCCT face typing;
+ Analysis Situs, BSD-3, is the only OSS CAD feature-recognition framework.)
+ 3. Insertion axis = common cylinder axis, head→tip, disambiguated by the coaxial hole
+ in the mating part. Group identical fasteners into one step ("install 4× M5 SHCS").
+- **Mates/constraints do NOT survive STEP export** (AP242 kinematics is unimplemented by
+ mainstream CAD). Get real mates only via native APIs — **Onshape's API exposes mates
+ with full DOF semantics, and Carbon already has an Onshape integration**. Learned
+ joint inference exists (Autodesk JoinABLe/AutoMate, research licenses) as a later
+ option.
+
+### 5. Exploded views & cameras
+- Canonical: Li/Agrawala SIGGRAPH 2008 explosion graphs. For work instructions the
+ shortcut is better: explode along the per-step removal directions the planner already
+ computed; offset = bbox clearance × constant.
+- Camera per step: viewpoint-entropy style scoring — render ~26–64 candidate views
+ offscreen with ID buffers, score visibility of the active part + its destination
+ interface, penalize camera jumps between steps.
+- FTO note: occlusion-based auto-explode patents exist (US 9,053,258; US 7,295,201);
+ disassembly-planning patent US 11,813,756. Worth a freedom-to-operate review.
+
+### 6. Stability
+- Modern practice (ASAP): drop the intermediate subassembly in a physics sim (pybullet,
+ ~1 s sim time, 10–100 ms wall); if parts displace, it's unstable → emit "hold part
+ while fastening" / "do not flip until step N" notes. Heuristic pre-filter: a placed
+ part is unstable-until-fastened unless inserted downward into a pocket/onto a pin.
+
+## Engineering Stack
+
+### What Carbon already has (verified in repo)
+- `modelUpload` table (`20240630115404_model-uploads.sql`) attached to items, jobs,
+ quote/sales/purchase lines; files in Supabase storage; served via
+ `apps/erp/app/routes/file+/model+/$id.tsx`.
+- `packages/react/src/ModelViewer.tsx` — online-3d-viewer (occt-import-js WASM) +
+ three.js 0.163: loads STEP/STL in-browser today (no assembly tree, no animation —
+ transforms get baked into vertices, unusable for animation targeting).
+- `packages/react/src/AutodeskViewer.tsx` — APS (Forge) viewer with token provider, URN
+ loading; `modelUpload.autodeskUrn` column exists.
+- `packages/ee/src/onshape/` — live Onshape OAuth + BOM sync into quotes/jobs/items.
+- **Inngest** (`packages/jobs/src/inngest/`, inngest ^3.52.7) is the background job
+ system. Existing pattern: `tasks/model-thumbnail.ts` calls a Supabase edge function
+ to screenshot the viewer.
+- Work-instruction backbone: `makeMethod` → `methodOperation` → `methodOperationStep`;
+ `procedure`/`procedureStep`; `jobOperation` in MES with a Model tab at
+ `apps/mes/app/routes/x+/operation.$operationId.tsx`.
+- Deploy target: AWS ECS via SST; Docker images per app.
+
+### Recommended pipeline
+1. **Ingest (server-side):** Python worker with OCP (native OCCT bindings; OCCT is
+ LGPL-2.1-with-linking-exception, safe for SaaS): `STEPCAFControl_Reader` → XCAF
+ (assembly tree, per-node transforms, names, colors) → `BRepMesh_IncrementalMesh` →
+ `RWGltf_CafWriter` → GLB. WASM OCCT (OpenCascade.js) has a 4 GB ceiling and ~5×
+ slowdown — wrong tool for 1000-part assemblies. Keep occt-import-js for instant
+ client preview only.
+2. **Web format:** GLB + meshopt compression (`EXT_meshopt_compression` via
+ glTF-Transform — GPU-decodable, compresses animation tracks; Draco can't). Stable
+ part IDs stamped into node `extras` keyed to the assembly-graph JSON and BOM rows.
+ LODs via gltf-transform simplify for >500-part assemblies.
+3. **Viewer:** react-three-fiber + drei (three.js already a dependency). Animation as
+ **runtime-generated KeyframeTracks from a JSON step plan** (insertion vector / helix
+ params per step), NOT baked into the GLB — keeps the plan editable. BatchedMesh for
+ unique parts, InstancedMesh for repeated fasteners.
+4. **Compute:** Inngest orchestrates; heavy lifting in a dedicated Python container
+ (OCCT + trimesh + python-fcl + pybullet) on ECS (matches existing infra) — CPU-bound,
+ no GPU needed. Seconds for parts, ~1–10 min for large assemblies.
+5. **Fallbacks for native CAD formats:** APS Model Derivative (0.1–0.5 Flex tokens/job;
+ viewer already integrated) for SolidWorks/NX/CATIA natives; Onshape API direct glTF +
+ mates for Onshape customers. CAD Exchanger has stopped new SDK sales; HOOPS is
+ ~$50k+/yr — revisit only if native-format demand justifies it.
+6. **Physics:** pybullet (zlib) or MuJoCo (Apache 2.0) in the same worker for stability
+ checks; PhysX 5 (BSD-3, GPU) only if search throughput ever demands it.
+
+## Recommended Approach for Carbon
+
+1. **Own the loop point solutions can't:** generate instructions from the model on an
+ item revision, attach them to methods/procedures, execute them in MES with real
+ time/quantity/quality capture — no connectors needed.
+2. **Tiered deterministic planner** (name-regex + geometry fastener detection → greedy
+ direction-sampled disassembly → L-motions → physics escalation → human editor) —
+ ship value long before research-grade completeness; the market norm is 80/20.
+3. **Editor-first product**: the planner produces a draft; the editor (reorder, group,
+ annotate, torque/tools/checks) is what makes it shippable. Animations re-derive from
+ the plan JSON on every edit.
+4. **Revision propagation** as headline feature parity: diff assembly graphs between
+ item revisions, remap untouched steps, flag changed ones.
+5. Standalone potential: keep planner service + viewer package + instruction schema
+ decoupled from ERP routes so a standalone shell app is cheap later.
+
+## Sources
+
+Wilson & Latombe, *Geometric Reasoning About Mechanical Assembly* (AIJ 1994);
+github.com/yunshengtian/Assemble-Them-All (MIT) and /ASAP; Li/Agrawala, *Automated
+Generation of Interactive 3D Exploded View Diagrams* (SIGGRAPH 2008); Analysis Situs
+thread-recognition writeups; OCCT XDE/RWGltf documentation; gltf-transform.dev; Onshape
+translation/mates API docs; aps.autodesk.com/pricing; trade press and vendor materials
+on automated work-instruction tools.
diff --git a/.ai/research/inventory-valuation-variances.md b/.ai/research/inventory-valuation-variances.md
new file mode 100644
index 0000000000..18ebbc6aa4
--- /dev/null
+++ b/.ai/research/inventory-valuation-variances.md
@@ -0,0 +1,159 @@
+# Inventory Valuation Variances Research: PPV on Purchases vs Actuals on Production
+
+## Summary
+
+Carbon books a "Purchase Price Variance" when a supplier invoice price differs from
+the received (PO) cost — inventory stays at receipt cost, the delta is expensed —
+but costs shop-floor production at pure actuals (actual labor time × work-center
+rate, actual material) with no labor/overhead variance. This looks asymmetric. The
+research shows it is **not** an inconsistency: what Carbon calls "PPV" is, in strict
+accounting terms, an **Invoice Price Variance (IPV) / goods-received-not-invoiced
+(GR/IR) reconciliation** — an estimate-to-actual true-up on the *same purchase*, not
+a classical standard-cost PPV (which compares purchase price to a *maintained
+standard cost*). Under that reading **both sides of Carbon are actual-costing
+systems**: both converge to actual cost, neither maintains a performance standard,
+so neither produces a true variance. The purchase-side "variance" account is only a
+timing mechanism to absorb the delta without retroactively revaluing inventory that
+may already be consumed — the same role a revaluation adjustment plays under actual
+costing. This is a recognized, defensible design that matches how job-shop-oriented
+ERPs (Epicor Average, NetSuite Average default) behave.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — reference for enterprise standard vs moving-average (price
+ control S vs V), GR/IR, production-order settlement variance categories.
+- **Oracle (EBS / Fusion Cost Management)** — explicit PPV vs IPV terminology; WIP
+ standard-cost variances; actual/average cost behavior.
+- **NetSuite** — Average is the default; PPV only under Standard; Accrued Purchases
+ ("Inventory Received Not Billed") + Post Vendor Bill Variances for Average/FIFO.
+- **Dynamics 365 Business Central** — cleanest split: Standard → variance account;
+ FIFO/LIFO/Average → revalue inventory via Adjust Cost – Item Entries.
+- **Epicor Kinetic** — job-shop reference: Standard part → MFG-VAR at close; Average
+ part = "actual from a job standpoint", few/no variances.
+- **Fishbowl** — SMB job-shop actual costing (labor hours × actual wage into order).
+
+## Key Consensus Patterns
+
+### 1. A variance requires a maintained standard to vary from
+- **All vendors + theory**: A cost variance = actual − standard/budget. Under pure
+ actual/average/FIFO costing there is no standard operand, so classical price/
+ rate/efficiency/usage variances do not exist — the delta simply becomes part of
+ actual cost (or, at most, a revaluation adjustment).
+- **Rationale**: PPV, material usage, labor rate, labor efficiency, and overhead
+ variances are all defined as deviations from a predetermined standard. Remove the
+ standard and none can be computed. This is the crux for Carbon.
+
+### 2. Variance accounting is a property of the STANDARD costing method
+- **NetSuite / BC / Epicor**: PPV and production (material/labor/overhead)
+ variances arise **only** under Standard costing. Under Average/FIFO/actual,
+ output is valued at actual consumed cost with **no** manufacturing variance.
+- **Rationale**: Standard costing freezes inventory value and isolates every
+ deviation into variance GL accounts for management-by-exception; actual costing
+ puts real cost into inventory, so there is nothing to isolate.
+
+### 3. Two distinct "purchase price" differences, recognized at two moments
+- **Standard-cost PPV**: invoice/PO price vs the item's **maintained standard
+ cost**, recognized at goods receipt. Requires a standard. (SAP price control S,
+ Oracle standard cost, NetSuite Standard.)
+- **Invoice Price Variance (IPV) / GR-IR**: **PO/receipt price vs invoice price** on
+ the same purchase, recognized at invoice matching. Requires **no** standard — it
+ reconciles what we accrued at receipt against what we were actually billed. This
+ is what Carbon actually does.
+
+### 4. Under actual/average costing, the invoice delta is normally handled two ways
+- **Revalue inventory (BC-style, "correct" path)**: Adjust Cost – Item Entries
+ forwards the true invoiced cost into inventory value and applied COGS. Accurate
+ but expensive (retroactive re-costing).
+- **Hold inventory at receipt cost + expense delta to a difference account
+ (NetSuite Average default, the recognized simplification)**: inventory is not
+ retroactively revalued; the delta lands in a variance/holding account. Simpler
+ and cheaper; inventory carrying value is knowingly slightly off. **Carbon uses
+ this path.** SAP moving-average splits the delta proportionally by remaining
+ stock coverage (revalue the on-hand portion, expense the consumed portion);
+ Carbon expenses 100% regardless of stock on hand — a further simplification.
+
+### 5. Job shops legitimately use actuals for production
+- **Epicor / Fishbowl / Visual South / OpenStax**: For custom, low-volume,
+ make-to-order work, accumulating actual material + actual labor + actual burden
+ per job and receipting the finished good at accumulated actual cost is the
+ textbook-normal approach. Standards, where kept, are used for the **estimate /
+ quote / schedule**, not for valuation. Labor is actual hours × a fixed resource/
+ work-center rate — the job varies hours, not the per-hour rate.
+
+## Answers to Research Questions
+
+1. **When do ERPs use actual vs standard costing?** Standard for high-volume
+ repetitive/process manufacturing where variance control matters and standards
+ can be maintained; actual/average for job-order/low-volume/custom shops where
+ true per-job cost matters and maintaining standards is burdensome. Method is set
+ **per item**, so purchased and manufactured items can differ.
+
+2. **Where does PPV come from?** Standard costing. A true PPV presupposes a
+ maintained standard purchase cost. Without one, the only purchase difference is
+ the IPV/GR-IR estimate-to-actual reconciliation.
+
+3. **How do the vendors treat production variances?** Only under Standard costing,
+ and they decompose them (SAP: input price, input quantity/efficiency, resource-
+ usage, scrap, lot-size, overhead; Oracle/BC: material, capacity/labor, overhead,
+ subcontract). Under actual/average, none — actual cost is capitalized into the
+ finished good (Epicor Average, BC non-standard, NetSuite Average).
+
+4. **Is PPV-on-purchases + actuals-on-production consistent?** Yes, **provided the
+ purchase-side account is an IPV/GR-IR reconciliation, not a standard-cost PPV**.
+ Under that reading both sides are actual-costing systems converging to actual;
+ the difference account merely avoids retroactively revaluing consumed inventory.
+ It would only be a genuine *mixed* system (heavier, needing maintained standard
+ material costs + period-end PPV reallocation) if the purchase account were a real
+ standard-cost PPV while production ran on actuals — which is not what Carbon does.
+
+## Recommended Interpretation for Carbon
+
+1. **The design is coherent and industry-recognized** — it is Epicor-Average /
+ NetSuite-Average job-shop actual costing on both sides. No philosophical fix
+ needed.
+2. **The label overclaims.** Account 5210 "Purchase Price Variance" is really an
+ Invoice Price Variance / GR-IR reconciliation. Consider renaming or documenting
+ to prevent exactly the "why is this asymmetric?" confusion.
+3. **Known simplification to document:** the full invoice delta is expensed to the
+ variance account rather than revaluing on-hand inventory (SAP/BC would split by
+ stock still on hand). Immaterial when turnover is fast and price deltas small;
+ worth flagging for slow-moving, high-value stock.
+4. **Production side is correct.** No labor variance is right for Average/FIFO
+ items. Carbon's single `materialVariance` catch-all at job close already absorbs
+ the WIP residual — for a *Standard*-costed manufactured item that residual **is**
+ the aggregate manufacturing variance (actual WIP vs standard receipt), just not
+ decomposed into labor-rate / labor-efficiency / overhead. Decomposition is the
+ extension point if variance analysis is ever wanted.
+
+## Carbon Code Grounding (verified in this repo)
+
+- Receipt at PO cost → DR Inventory/WIP, CR GR/IR (Goods Received Not Invoiced):
+ `packages/database/supabase/functions/post-receipt/index.ts:910-1003`
+- Invoice delta → PPV (`purchaseVarianceAccount`, 5210), inventory held at receipt
+ cost: `packages/database/supabase/functions/post-purchase-invoice/index.ts:930-1049`
+- Labor at actual hours × work-center rate → DR WIP, CR labor absorption:
+ `packages/database/supabase/functions/post-production-event/index.ts:110-265`
+- Job-close WIP residual → `materialVarianceAccount` (5220):
+ `packages/database/supabase/functions/close-job/index.ts:64-140`
+- Item costing methods (Standard / Average / FIFO / LIFO) honored in COGS:
+ `apps/erp/app/modules/items/items.models.ts:42-47`,
+ `packages/database/supabase/functions/shared/calculate-cogs.ts:37-121`
+
+## Sources
+
+- SAP standard vs moving average / PPV to variance accounts — https://erpcorp.com/sap-controlling-blog/choosing-standard-or-moving-average-price
+- SAP Help — Valuation with Moving Average Price (stock-coverage split) — https://help.sap.com/docs/SAP_S4HANA_CLOUD/7f47a6d9441c46ac86c96fd27f6015f0/bbd9b6ce0be14516ad7868da0982024a.html
+- SAP invoice verification — entering invoices with variances — https://learning.sap.com/courses/invoice-verification-in-sap-s-4hana/entering-invoices-with-variances-1
+- SAP production order variance categories — https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-members/understanding-production-order-variance-part-2-the-sap-perspective/ba-p/12937397
+- Oracle Cost Management — standard cost variances (PPV vs IPV) — https://docs.oracle.com/cd/A60725_05/html/comnls/us/cst/stdvari.htm
+- NetSuite — Standard Costing and Transactions (PPV, Accrued Purchases) — https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2206397.html
+- NetSuite — Vendor Bill Variances (Accrued Purchases, Match Bill to Receipt) — https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2371184.html
+- Dynamics 365 BC — Design Details: Variance — https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-variance
+- Dynamics 365 BC — Design Details: Cost Adjustment — https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-cost-adjustment
+- Dynamics 365 BC — Design Details: Production Order Posting — https://learn.microsoft.com/en-us/dynamics365/business-central/design-details-production-order-posting
+- Epicor manufactured-part receipt Standard vs Average, MFG-VAR, WIP — https://dotnetitblog.wordpress.com/2013/10/15/inventory-costing-methods-which-way-forward/
+- Visual South — Standard Cost vs Actual Cost in a work-order-driven company — https://www.visualsouth.com/blog/standard-cost-actual-cost
+- AccountingCoach — What is a cost variance — https://www.accountingcoach.com/blog/what-is-a-cost-variance
+- AccountingTools — Purchase price variance (requires a standard) — https://www.accountingtools.com/articles/purchase-price-variance
+- OpenStax — Job Order vs Process Costing — https://openstax.org/books/principles-managerial-accounting/pages/5-1-compare-and-contrast-job-order-costing-and-process-costing
+- Stampli — GR/IR reconciliation — https://www.stampli.com/resources/grir-reconciliation/
diff --git a/.ai/specs/2026-07-04-animated-work-instructions-contracts.md b/.ai/specs/2026-07-04-animated-work-instructions-contracts.md
new file mode 100644
index 0000000000..1f862ac1cd
--- /dev/null
+++ b/.ai/specs/2026-07-04-animated-work-instructions-contracts.md
@@ -0,0 +1,360 @@
+# Animated Work Instructions — Shared Contracts (Phase 0)
+
+These contracts bind three components: the geometry service (`services/geometry`,
+Python), the viewer (`packages/viewer`, TypeScript), and the ERP/Inngest layer.
+Change them only by updating all three.
+
+## 1. Stable node IDs
+
+Every part instance in the assembly gets a stable `nodeId`:
+
+```
+nodeId = sha1(geometryHash : parentPath : siblingOrdinal)[:16]
+```
+
+- `geometryHash`: sha1 of the part's tessellated geometry (vertex positions quantized
+ to 1e-3 mm, triangle indices), independent of placement.
+- `parentPath`: '/'-joined product names from root to parent.
+- `siblingOrdinal`: 0-based index among siblings sharing the same geometryHash and
+ parent (disambiguates 4 identical brackets).
+
+The `nodeId` appears in (a) glTF node `extras.nodeId`, (b) `graph.json` nodes,
+(c) `assemblyInstructionStep.componentNodeIds`.
+
+## 2. graph.json (written by /convert)
+
+```jsonc
+{
+ "version": 1,
+ "unit": "mm", // normalized output unit (always mm in Phase 0)
+ "sourceUnit": "inch", // unit declared in the STEP file
+ "componentCount": 42, // count of leaf instances
+ "root": { // assembly tree, root has no geometry
+ "nodeId": "a1b2c3d4e5f60718",
+ "name": "MAIN-ASSY",
+ "isAssembly": true,
+ "geometryHash": null, // null for assemblies
+ "transform": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], // local, column-major 4x4
+ "bbox": { "min": [0,0,0], "max": [100,50,25] }, // world-space, mm
+ "volume": 1234.5, // mm^3, leaf nodes only (null for assemblies)
+ "color": [0.5, 0.5, 0.5, 1], // RGBA 0-1 or null
+ "children": [ /* same shape */ ]
+ }
+}
+```
+
+## 3. Geometry service API
+
+Auth: `Authorization: Bearer <GEOMETRY_SERVICE_API_KEY>` (shared secret env var on
+both sides).
+
+### POST /convert
+```jsonc
+// request
+{
+ "jobId": "string", // assemblyPlanJob.id, used in logs
+ "source": { "url": "https://signed-get-url", "format": "step" },
+ "outputs": {
+ "glb": { "url": "https://signed-put-url" },
+ "graph": { "url": "https://signed-put-url" }
+ },
+ "options": { "linearDeflection": 0.1, "angularDeflection": 0.5 } // optional
+}
+// response 200 (synchronous in Phase 0; Inngest applies its own timeout/retries)
+{ "ok": true, "componentCount": 42, "unit": "mm", "stats": { "convertMs": 1234, "meshTriangles": 100000 } }
+// response 4xx/5xx
+{ "ok": false, "error": "human-readable message", "code": "READ_FAILED" | "TESSELLATION_FAILED" | "UPLOAD_FAILED" | "INVALID_INPUT" | "LIMIT_EXCEEDED" | "BUSY" }
+// status mapping: 400 INVALID_INPUT (incl. URL policy violations), 413
+// LIMIT_EXCEEDED (source size / part count), 422 READ_FAILED, 429 BUSY (no
+// conversion slot free — caller should retry with backoff), 500
+// TESSELLATION_FAILED, 502 UPLOAD_FAILED.
+```
+
+### GET /health → `{ "ok": true, "version": "x.y.z" }`
+
+### POST /plan (async: submit → poll)
+
+Computes a collision-free insertion motion for every leaf part plus a
+constraint-consistent assembly sequence. Re-tessellates the same STEP source
+with the same nodeId derivation as /convert, so plan.json keys join against
+graph.json and GLB extras.
+
+**Async** (v3): planning a large model runs 10+ minutes — longer than any single
+HTTP request survives across the Inngest → tunnel → app → tunnel → geometry hops
+(and a pre-signed upload URL's 60s TTL). So `/plan` starts the work in a
+background thread and returns **202 immediately**; the caller polls
+`GET /plan/{jobId}` until it reports `done` and then persists the inline plan
+itself (the worker uploads plan.json with its service-role client — no expiring
+URL). Submits are idempotent: a duplicate `/plan` for a jobId already running
+attaches to it rather than starting a second planner.
+
+Pipeline: **merge `options.units` into single rigid bodies** (a purchased PCB's
+hundreds of component solids → one body; see units below) → classify named
+fasteners (symmetry axis + threaded mates) → rigid-merge inseparable pairs →
+greedy disassembly for motions → precedence DAG + preference topo sort → forward
+verification → **expand merged units back to member leaves** (each carries the
+unit's motion + `groupId`; the unit is one `groups` entry).
+
+```jsonc
+// POST /plan request
+{
+ "jobId": "string", // the caller's plan-job id; also the poll key
+ "source": { "url": "https://signed-get-url", "format": "step" },
+ "options": { // all optional
+ "linearDeflection": 0.1,
+ "angularDeflection": 0.5,
+ "clearance": 0.5, // mm of required clearance along the path
+ "pathSamples": 60, // collision checks per candidate path
+ // Pre-grouped units: leaf nodeIds merged into one rigid body for planning,
+ // then expanded back to members (one step, one motion). Derived app-side
+ // from BOM membership + an LLM part→BOM assignment + user overrides.
+ "units": [ { "id": "unit:<itemId>", "name": "BCU PCB", "nodeIds": ["leaf1", "..."] } ]
+ }
+}
+// POST /plan response 202 — accepted, running in the background
+{ "ok": true, "jobId": "string", "status": "pending" }
+
+// GET /plan/{jobId} response 200
+{ "ok": true, "status": "pending" | "running" | "done" | "error",
+ // present only when status == "done":
+ "plan": { "version": 3, "unit": "mm", "sequence": ["..."], "components": { }, "groups": { } },
+ "componentCount": 431, "plannedCount": 424,
+ "stats": { "planMs": 105000, "verifiedCount": 18,
+ "tiers": { "linear": 13, "l": 4, "escape": 0, "group": 0, "flagged": 2, "forced": 0, "unplanned": 0 },
+ "warnings": [] },
+ // present only when status == "error":
+ "error": "message" }
+// unknown jobId → 404; errors otherwise use the same codes/status mapping as /convert
+```
+
+plan.json is **version 3**: `groups` entries gain an optional `name` (the unit's
+BOM/subassembly name → the draft step title). A merged unit's member leaves each
+carry `groupId` (= the unit id) and sit consecutively in `sequence`, so
+`buildAssemblyStepGroups` folds them into one step.
+
+Motion tiers: 1 = straight-line removal (the part's symmetry axis first, then
+the six world axes; **named fasteners only ever exit along their bore axis**,
+with contacts against their threaded mate allowed up to the seated
+interference — there is no blanket penetration allowance, so thin blockers
+can never be tunneled), 2 = fixed lift-then-slide "L", 3 = adaptive
+multi-segment escape (BFS over axis-aligned hops), group = subassembly
+extraction in stuck states (mutually interlocked parts that remove as one
+unit — members share one step and one motion), flagged = **no collision-free
+escape exists: motion stays "none"**, blockers are recorded, and the viewer
+fades the parts in at the seated pose. The planner never fabricates a motion
+through geometry; `tiers.forced` is always 0 and remains only for stats
+compatibility.
+
+Sequence: after motions are chosen (per part: the least-entangling clear
+direction — fewest full-assembly sweep blockers, natural-axis order as the
+tiebreak; recorded travel is "reach free space", not exit-the-bounding-box),
+the order comes from a precedence DAG topologically sorted with
+preferences.
+
+Hard edges, all cycle-guarded:
+- **Derived**: U before X when X's seated body blocks U's insertion sweep.
+- **Joint**: everything a fastener joins — threaded mates plus every part
+ whose material radially surrounds its shank (ring-containment probes at
+ the shank radius, just outside the candidate's own bore, and at the
+ bore-rim height) — installs before it; the one inversion is a disc mate
+ (nut) after its rod fastener. Washer-before-bolt is therefore
+ unconditional, slip fits and counterbores included.
+- **Joint-stack**: a joint's members order by WHERE they engage the shank,
+ tip → head (head = the fastener's geometrically widest end) — the bolt
+ clamps the head-side part onto the tip-side part, across CAD air gaps.
+- **Support**: for mostly-vertical structure-structure seated contact
+ (hemisphere-aligned normals), the lower part precedes the upper.
+- **Sandwich**: a thin part with seated contact on BOTH sides along one
+ shared contact axis (gasket, seal, shim — detected from contact-point
+ positions and the winding-invariant structure tensor, never bbox
+ z-centers, which degenerate for thin parts) assembles after its
+ heavier side (the enclosure) and before its lighter side (the
+ compressor). Detection is strict because a false positive corrupts
+ collision truth: thickness is capped relative to the part's largest
+ extent AND absolutely (≤ ~6mm — gaskets are thin in millimeters), and
+ the observed interference must be squish-scale (≤ ~0.6mm; a 10mm bite
+ is a press fit or broken CAD, never compliance). Sandwich edges are
+ added BEFORE support edges so the cycle guard rejects a wrong
+ z-center-degenerate support edge. Near-equal sides add nothing rather
+ than guessing.
+
+Preferences, in order: the base first (the biggest part survives greedy
+disassembly by design); runs of identical parts kept together; **securing
+fasteners** — those whose joint contains a through-part that is neither
+their threaded mate nor the base — immediately after their joint
+completes (anchor bolts into the skeleton take no jump); the
+**dependency spine** — parts other parts are waiting on (outgoing
+precedence edges: their insertion window closes, or later parts build on
+them) precede terminal parts nothing depends on, regardless of size (a
+small slider beats a big badge subassembly; deferring the terminal
+accessory also defers its fasteners' securing jump, so a structural
+joint's fasteners aren't interrupted by accessory hardware); then
+structure big → small by MATERIAL volume (watertight mesh volume, else
+the sum of watertight split bodies, else bbox — bboxes lie for tilted and
+wrap-around parts), with horizontal centrality as the tiebreak —
+EXCEPT **weakly-secured terminal parts** (no fastener engages them, no
+outgoing precedence edge, exactly one seated structural neighbor, AND a
+verified tier-1/2 clean removal — snap clips, badges), which go last
+regardless of size. The removability-evidence gate matters on real CAD:
+fastener detection is name-only and clearance fits hide contacts, so
+the static signal alone matches a large share of a wire harness.
+Escape/flagged parts and bbox proxies never demote. This is a topo-sort
+preference ONLY — the greedy removal priority deliberately ignores it,
+because that ranking schedules expensive removal attempts and picks
+flag/merge victims, and fronting hard-to-remove one-contact parts
+(cables, interlocked clips) multiplies failed sweeps.
+
+Fastener axes come from an evidence cascade: own symmetry (SVD) → bbox
+shape → thread-mate contact band → the full seated contact cloud → the
+dominant contact normal; along its bore axis a fastener keeps sliding
+engagement with its joint (allowances capped at seated interference /
+mesh tolerance). Sandwiched parts and their flanges likewise exchange a
+seated-interference allowance (observed depth + the mate margin, valid
+ONLY along the sandwich axis — lateral motion is judged strictly, like a
+thread mate along its bore) — a compressed gasket's squish is
+evidence-backed compliance, same reasoning as thread interference, so it
+never reads as a blocking collision during removal sweeps or forward
+verification. Collision tolerance scales with tessellation:
+max(0.15mm, 2.5 × linearDeflection).
+
+Unresolvable geometry is handled by evidence, never fabrication: a stuck
+part blocked by exactly ONE other (captive SEMS washers, coincident CAD
+variants) rigid-merges into it (`mergedInto`) — sandwiched parts are
+exempt on both sides (a gasket pressed into its lid is compliant, not
+rigid with it) and their deep bites don't deprioritize them as group
+members; mutually interlocked sets that clear together become
+subassembly `groups`; anything else is flagged with its real sweep
+blockers. Finally the whole sequence is
+forward-verified: each part's insertion is re-checked against exactly the
+parts present at that point; failures demote to flagged
+(`verified: false`).
+
+plan.json (returned inline in the `done` poll response; the caller persists it):
+
+```jsonc
+{
+ "version": 3,
+ "unit": "mm",
+ "sequence": ["nodeId", "..."], // constraint-consistent assembly order; [0] is the base
+ "components": {
+ "<nodeId>": {
+ "motion": { /* INSERTION motion per §4 (removal reversed) */ },
+ "confidence": "high" | "low",
+ "removalDirection": [0, 0, 1], // unit vector, removal sense
+ "tier": "linear" | "L" | "escape" | "group" | "flagged" | "base",
+ "verified": true, // forward-verified against its predecessors
+ "blockedBy": ["nodeId"], // flagged parts: what obstructs them
+ "groupId": "g1", // subassembly members (see groups)
+ "mergedInto": "nodeId" // rigidly merged: rides the host's step
+ }
+ },
+ "groups": { // subassembly units (optional)
+ "g1": { "componentNodeIds": ["nodeId", "..."], "motion": { /* shared */ },
+ "name": "BCU PCB" } // v3: unit name → step title (optional)
+ },
+ "warnings": ["..."] // one entry per flagged part / merge / skipped preference
+}
+```
+
+All v2/v3 fields are optional additions — older files keep parsing. Bumping the
+version invalidates stored plans (consumers treat below-current as absent and
+re-plan), which is how pre-grouping (v2) plans get replaced.
+
+Editor semantics: when a step's `componentNodeIds` change, motion is auto-filled
+from plan.json (single part → its motion; multiple parts → the shared motion
+if all agree, else the first part's motion with confidence low). Parts the
+plan flagged are never auto-filled — their recorded motion is "none" and the
+editor shows the blockers. When the plan has nothing for the parts,
+`synthesizeFallbackMotion` (`@carbon/viewer`) derives an AABB-based motion
+from graph.json so the step still animates; the manual motion form is an
+override, only shown on demand. `buildAssemblyStepGroups` (`@carbon/viewer`)
+turns a plan into draft step groups: sequence order, consecutive identical
+parts merged, subassembly units one step, merged parts riding their host's
+step, flagged parts stored with motion "none" plus a
+`warnings: { flagged, blockedBy }` payload on `assemblyInstructionStep`.
+A step's parts animate SIMULTANEOUSLY, so merging is corridor-gated: each
+part's swept corridor (AABB of its seat pose union every insertion pose,
+from graph.json bboxes) must be disjoint from every corridor already in
+the step. Side-by-side same-direction screws share a step; clips sliding
+in-line into the same channel each take their own step (the only way
+their simultaneous animation avoids collision). Subassembly units (one
+rigid body) and graph-less calls are exempt.
+"Generate Steps" refuses while steps exist; `mode=regenerate` replaces them,
+guarded against manually authored (`planConfidence: "manual"`) or Done steps.
+
+### Operational limits (service env vars)
+
+- `GEOMETRY_MAX_SOURCE_MB` (default 250) — source download cap
+- `GEOMETRY_MAX_PARTS` (default 5000) — leaf instances, checked before meshing
+- `GEOMETRY_MAX_CONCURRENCY` (default 2) — conversion slots per worker; excess → 429 BUSY
+- `GEOMETRY_ALLOWED_URL_HOSTS` (optional, comma-separated) — allowlist for
+ source/output URL hosts (set to the Supabase storage host in production)
+- `GEOMETRY_DEV_MODE=true` — permits http URLs and unauthenticated access when
+ no API key is set (local dev only)
+
+## 4. Step motion JSON (`assemblyInstructionStep.motion`)
+
+Describes the **insertion** motion of the step's parts into the assembly. The viewer
+derives removal (the reverse) and start poses from it. Distances in mm, in the same
+world space as the GLB.
+
+```jsonc
+// linear insertion along a vector
+{ "type": "linear", "direction": [0, 0, -1], "distance": 80 }
+
+// multi-segment (2+, insertion order), e.g. slide then drop; the tier-3
+// escape planner emits up to 3 segments and the viewer interpolates any count
+{ "type": "L",
+ "segments": [
+ { "direction": [1, 0, 0], "distance": 60 },
+ { "direction": [0, 0, -1], "distance": 20 }
+ ] }
+
+// threaded fastener: helix about axis, then it is seated
+{ "type": "helix", "axis": [0, 0, -1], "origin": [10, 20, 5],
+ "pitch": 0.8, "turns": 6, "approach": 30 } // approach = linear travel before threading
+
+// explicit keyframe path (planner tier 5 / manual freeform)
+{ "type": "path", "keyframes": [
+ { "t": 0, "position": [0,0,100], "quaternion": [0,0,0,1] },
+ { "t": 1, "position": [0,0,0], "quaternion": [0,0,0,1] }
+ ] }
+
+// no geometry motion (process-only step: cure, inspect, torque pattern)
+{ "type": "none" }
+```
+
+`camera` JSON: `{ "position": [x,y,z], "target": [x,y,z], "fov": 45 }` or `null`
+(viewer auto-frames the active parts).
+
+`fastener` JSON: `{ "spec": "M5 SHCS", "count": 4, "torqueNm": 8, "tool": "4mm hex" }`
+(all fields optional).
+
+## 5. Viewer step shape (props of AssemblyPlayer)
+
+```ts
+type AssemblyStep = {
+ id: string;
+ title: string | null;
+ instructionText: string | null; // derived plain-text snapshot of the step's
+ // rich-text `description` (tiptap JSON)
+ componentNodeIds: string[]; // components installed in this step
+ motion: Motion; // section 4
+ camera: CameraPose | null;
+ fastener: Fastener | null;
+};
+```
+
+The DB row behind this carries more authoring data than the viewer consumes:
+`assemblyInstructionStep` also has the typed-step fields mirrored from
+`jobOperationStep` (`type` `procedureStepType`, `description` tiptap JSON,
+`required`, `unitOfMeasureCode`, `minValue`/`maxValue`, `listValues`,
+`fileTypes`) so steps can eventually be copied into job operations, and
+BOM-part associations live in `assemblyInstructionStepMaterial`
+(`stepId` → `itemId` + optional quantity; stored by itemId so links survive
+make-method re-versioning).
+
+Playback semantics for step k (0-based): parts of steps < k are shown solid in final
+pose; parts of step k animate per `motion` (looping); parts of steps > k are hidden
+(or ghosted when the "x-ray" toggle is on). Parts in no step are always shown solid
+(base/fixture parts).
diff --git a/.ai/specs/2026-07-04-animated-work-instructions-design.md b/.ai/specs/2026-07-04-animated-work-instructions-design.md
new file mode 100644
index 0000000000..50ab21e071
--- /dev/null
+++ b/.ai/specs/2026-07-04-animated-work-instructions-design.md
@@ -0,0 +1,248 @@
+# Animated Work Instructions ("Assembly") — Design
+
+## Summary
+
+Automated assembly work instructions inside Carbon: upload a CAD assembly (STEP first),
+and Carbon automatically drafts step-by-step, animated 3D work instructions — build
+sequence, per-part insertion animations, grouped fastener steps, exploded views, camera
+framing, and step text — which an engineer then refines in an editor (reorder, group,
+add tools/torque/notes/quality checks) and publishes to MES for operator playback with
+cycle-time and quality capture. The system is deterministic geometry + physics
+heuristics (no generative model in the planning loop), with an LLM used only to phrase
+step text from structured step facts.
+
+Strategy: build it as a Carbon module with three deliberately decoupled layers —
+**geometry service** (Python/OCCT planner workers), **instruction schema + editor**
+(TypeScript, new tables), and **viewer** (`packages/viewer`, react-three-fiber) — so it
+can later ship as a standalone product (point solutions sell standalone; Carbon's advantage is
+native MES execution, but the standalone wedge "upload CAD → shareable animated
+instructions" must not depend on ERP internals).
+
+## Research
+
+From `.ai/research/animated-work-instructions.md`:
+
+- Commercial tools in this category automate ~80% (sequence, animations, text,
+ EBOM→MBOM) and leave ~20% to a human editor; revision propagation and subassembly
+ reuse are the differentiators; standalone tools must push run data into someone
+ else's MES — Carbon owns that loop natively.
+- The proven algorithmic core is **assembly-by-disassembly**: repeatedly find a part
+ removable without collision, reverse the order. A direction-sampled greedy planner
+ (6–26 candidate axes per part) + analytic helices for fasteners + physics drop-tests
+ for stability covers the bulk of real assemblies; OMPL/physics search is the
+ escalation tier (Assemble-Them-All is MIT-licensed reference code).
+- Mates don't survive STEP. Fastener detection = name regex + coaxial-cylinder
+ geometry heuristics; Onshape API (already integrated in Carbon) is the one source of
+ real mates.
+- Carbon already has: `modelUpload` on items/jobs/lines, an in-browser STEP viewer
+ (preview-only), an APS viewer, Onshape OAuth + BOM sync, Inngest jobs, Supabase
+ storage, methods/procedures/jobOperation, and an MES Model tab.
+- Server pipeline: Python + native OCCT (XCAF → tessellate → `RWGltf_CafWriter` GLB),
+ meshopt-compressed GLB with stable part IDs in node extras, react-three-fiber
+ playback with runtime-generated keyframe tracks from an editable JSON step plan.
+
+## Decisions
+
+### 1. Standalone product vs. Carbon module
+**Question:** Build inside Carbon ERP, or as a separate app?
+**Research:** point solutions are standalone and integrate outward via connectors; their weakness
+is not owning execution. Carbon's monorepo already has multi-tenant auth, storage,
+permissions, and two apps (ERP/MES) sharing packages.
+**Approach:** Carbon module first (`assembly` module in ERP + playback in MES), with
+hard boundaries: planner service speaks a JSON contract (no Carbon DB access except via
+API), viewer lives in `packages/viewer` with zero ERP imports, instruction tables keyed
+to `modelUpload`/`itemId` but not entangled with method internals. A standalone shell
+app (`apps/assemble`) becomes a later packaging exercise, not a rewrite.
+
+### 2. Geometry processing: where and with what
+**Question:** WASM in browser, TypeScript server, or Python workers? OCCT vs. commercial?
+**Research:** WASM OCCT hits a 4 GB ceiling and ~5× slowdown; OCCT native (LGPL +
+linking exception) extracts assembly hierarchy/transforms/names and writes glTF
+directly; all the planning libraries (trimesh, python-fcl, pybullet, OMPL,
+Assemble-Them-All) are Python/C++.
+**Approach:** New containerized **Python geometry service** (`services/geometry/`),
+deployed on ECS alongside the apps, with a small HTTP API + job queue semantics.
+Inngest functions orchestrate: upload event → enqueue convert → enqueue plan →
+write artifacts to Supabase storage → update DB rows. Browser keeps occt-import-js
+preview for instant feedback while the server pipeline runs. STEP only at first; APS
+Model Derivative as the native-format fallback later (viewer already integrated);
+Onshape direct glTF + mates for Onshape-connected tenants.
+
+### 3. Planner architecture
+**Question:** Research-grade physics planning (ASAP) or tiered heuristics?
+**Research:** the market norm is 80/20 automation with deterministic geometry + heuristics. Tiered
+approach resolves ~90% of steps in tiers costing milliseconds–seconds; physics-complete
+search costs minutes–hours and ASAP's code is unlicensed.
+**Approach:** Tiered deterministic pipeline, every tier emitting confidence + failure
+reasons so the editor can surface "couldn't sequence these 3 parts — drag them where
+you want":
+1. Fastener classification (name regex + coaxial-cylinder heuristic + duplicate
+ geometry clustering); fastener groups become single steps with analytic helix motions.
+2. Contact/blocking graph from mesh proximity.
+3. Greedy assembly-by-disassembly: candidate directions = 6 axis-aligned + part
+ principal axes + hole/mate axes; path-sampled collision checks (trimesh/FCL).
+4. Two-segment "L" motions for tier-3 failures.
+5. Physics-guided escape search (Assemble-Them-All approach, MIT) for stubborn parts,
+ budget-capped.
+6. pybullet drop-test stability gate per reversed step → hold/fixture warnings.
+7. Exploded views and per-step cameras derived from removal directions + viewpoint
+ scoring.
+CAD subassembly tree (XCAF) constrains the sequence by default (designers already
+encode modules); users can regroup in the editor.
+
+### 4. Data model: artifacts vs. rows
+**Question:** What lives in Postgres vs. storage?
+**Approach:** Geometry artifacts (GLB, assembly-graph JSON, plan JSON) live in Supabase
+storage, immutable per processing run. Postgres holds what users query and edit:
+instruction sets, steps, part metadata needed for lists/search, processing job status.
+Steps reference parts by stable node IDs that appear in both the GLB extras and the
+graph JSON.
+
+### 5. Relationship to existing methods/procedures
+**Question:** Extend `procedureStep`/`methodOperationStep`, or new tables?
+**Research:** Existing steps are flat rich-text/parameter records with no notion of 3D
+state, part sets, or motions; jamming animation data into them would contort both.
+**Approach:** New `assemblyInstruction` + `assemblyInstructionStep` tables (versioned,
+keyed to `itemId`/`modelUploadId`). Integration by reference: a `methodOperationStep`
+or `jobOperation` can link to an instruction (new nullable FK), and the MES operation
+view renders the player when present. EBOM→step mapping reuses Onshape/manual BOM rows
+where available.
+
+### 6. Step text generation
+**Approach:** Planner emits structured facts per step (verb class, part names,
+quantities, fastener spec, target, direction, warnings). A small Inngest task phrases
+them via the existing AI infrastructure, with deterministic template fallback. No LLM
+in the geometric loop.
+
+### 7. Revision propagation (the moat feature)
+**Approach:** Assembly-graph diff between two processed models (match nodes by name +
+geometry hash + position): unchanged parts keep their steps and user annotations;
+changed/added/removed parts flag affected steps for review. Ship in Phase 3; design the
+node-ID scheme for it from day one (content-addressed part hashes, not array indices).
+
+## Data Model
+
+All tables follow Carbon golden rules (composite PK with `companyId`, `id('prefix')`,
+audit columns, standard RLS policies).
+
+```
+modelUpload (existing — add columns)
+ + processedAt, glbPath, graphPath, partCount, processingStatus
+ ('idle'|'queued'|'processing'|'success'|'failed'), processingError
+
+assemblyPlanJob -- one row per planner run (convert / plan / replan)
+ id, companyId, modelUploadId FK, kind ('convert'|'plan'), status, tiersCompleted,
+ planPath (storage), stats JSONB (per-tier counts, timings), error, audit cols
+
+assemblyInstruction -- the editable, publishable instruction set
+ id, companyId, itemId FK?, modelUploadId FK, assemblyPlanJobId FK?,
+ name, status ('draft'|'published'|'archived'), version INT, publishedAt,
+ settings JSONB (units, default camera, branding), audit cols
+
+assemblyInstructionStep
+ id, companyId, assemblyInstructionId FK, sortOrder (fractional),
+ parentStepId FK? (subassembly grouping),
+ partNodeIds TEXT[] -- stable node IDs in GLB extras/graph JSON
+ motion JSONB -- {type:'linear'|'L'|'helix'|'path', vector, pitch, keyframes?}
+ camera JSONB -- {position, target, fov} | null = auto
+ explode JSONB? -- per-step exploded offsets
+ title, instructionText, notes JSON (rich text),
+ fastener JSONB? -- {spec:'M5 SHCS', count:4, torqueNm?, tool?}
+ toolIds TEXT[]?, durationSeconds?,
+ warnings JSONB -- planner stability/clearance flags
+ planConfidence ('high'|'low'|'manual'), audit cols
+
+jobOperation / methodOperationStep (existing)
+ + assemblyInstructionId FK? -- opt-in linkage for MES playback
+
+assemblyInstructionFeedback -- Phase 3: operator notes per step from MES
+ id, companyId, stepId FK, jobOperationId FK?, userId, type, body, audit cols
+```
+
+Storage layout (`private` bucket):
+```
+{companyId}/models/{modelUploadId}.step (existing upload convention)
+{companyId}/models/{modelUploadId}/{runId}/model.glb (meshopt-compressed)
+{companyId}/models/{modelUploadId}/{runId}/graph.json (tree, transforms, bboxes,
+ contacts, fastener classes,
+ part hashes)
+{companyId}/models/{modelUploadId}/{runId}/plan.json (raw planner output)
+```
+
+## Architecture
+
+```
+ERP route (upload/replan)
+ └─ Inngest event: assembly/model.process
+ └─ Inngest fn → POST services/geometry /convert (OCCT: STEP→GLB+graph.json)
+ └─ Inngest fn → POST services/geometry /plan (tiered planner → plan.json)
+ └─ writes artifacts to Supabase storage, updates modelUpload/assemblyPlanJob
+ └─ Inngest fn → step-text generation (AI, template fallback)
+ └─ creates draft assemblyInstruction + steps from plan.json
+
+packages/viewer (new)
+ AssemblyPlayer: loads GLB, builds KeyframeTracks at runtime from step motion JSON,
+ step scrubber, part highlight/ghost, exploded toggle. Used by:
+ - ERP editor route (x/assembly/...): timeline, reorder, regroup, annotate, publish
+ - MES operation view: read-only player synced to operation steps
+ - share+ route: public/customer link (standalone wedge)
+
+services/geometry (new, Python/FastAPI container on ECS)
+ /convert: OCP (OCCT) XCAF read → tessellate → RWGltf GLB → glTF-Transform meshopt
+ /plan: trimesh + python-fcl collision, greedy disassembly tiers, pybullet
+ stability, exploded offsets + camera scoring
+ Stateless; reads/writes storage via signed URLs passed in the job payload.
+```
+
+Permissions: new `assembly` module permission set (view/create/update/delete), wired
+into the standard module/permission system. MES playback requires only production view.
+
+## Workflows
+
+1. **Author:** Engineer opens an item revision → Model tab → "Generate instructions".
+ Status chips show convert/plan progress (Inngest). Draft opens in the editor:
+ left = step list (tree, drag-reorder, group), center = AssemblyPlayer, right = step
+ detail (text, fastener spec, torque, tools, warnings). Low-confidence steps are
+ flagged. Engineer edits, publishes → version N.
+2. **Execute (MES):** Operation links an instruction. Operator sees the player inline:
+ current step animation loops, parts-to-pick highlighted, fastener callouts ("4× M5
+ SHCS, 8 N·m"), next/prev synced with step completion; time per step captured on
+ existing jobOperation infrastructure.
+3. **Share:** Publish generates a `share+` link rendering the read-only player (PDF
+ export later via existing documents package).
+4. **Revise (Phase 3):** New model upload on the next item revision → graph diff →
+ steps remapped, changed steps flagged "needs review" → republish.
+
+## Edge Cases
+
+- **Dirty/huge CAD:** tessellation failures per-part shouldn't kill the run — degrade
+ to bbox proxies, flag the part. Cap planner budgets per part/assembly; >1000-part
+ assemblies get LOD meshes and coarser collision proxies.
+- **Unsequenceable parts** (press fits, flexible parts, interlocks beyond tier 5):
+ always emit them as manual steps at the end with a clear reason — never block the
+ draft. This is the 80/20 contract.
+- **Parts with no geometry role** (adhesive, grease, harnesses) and process-only steps
+ (cure, test, torque pattern): editor supports geometry-less steps.
+- **Fastener misclassification:** classification is a suggestion — editor can mark/
+ unmark a part group as fasteners and the plan re-derives.
+- **Single-part models** (most current Carbon uploads): pipeline still runs convert
+ (better viewer) and skips planning gracefully.
+- **Identical siblings** (4 identical brackets): stable node IDs must disambiguate by
+ position, not just geometry hash, or revision diff and step references break.
+- **Units/coordinate systems:** STEP is mm-typical but not guaranteed; normalize in
+ convert, store unit in graph.json.
+- **FTO:** before GA, review patents US 11,813,756 (disassembly-based planning),
+ US 9,053,258 / US 7,295,201 (auto-explode), and avoid the patent-pending swept-volume
+ method (use sampled discrete checks).
+
+## Phasing (summary — full plan in .ai/plans/2026-07-04-animated-work-instructions.md)
+
+- **Phase 0 — Foundations:** geometry service skeleton, STEP→GLB+graph pipeline,
+ schema, AssemblyPlayer with manual step authoring. Valuable alone: assembly-aware
+ viewer + manually-authored animated instructions in ERP/MES.
+- **Phase 1 — Auto-draft:** fastener detection, greedy disassembly planner, helix
+ motions, draft instruction generation, step text. The "3-minute demo".
+- **Phase 2 — Editor depth + MES:** grouping/subassemblies, exploded views, camera
+ auto-framing, stability warnings, MES operator playback + time capture, share links.
+- **Phase 3 — Moats:** revision propagation (graph diff), physics escalation tier,
+ Onshape mates, APS native-format ingest, operator feedback loop, PDF export.
diff --git a/.ai/specs/2026-07-04-assembly-editor-requirements.md b/.ai/specs/2026-07-04-assembly-editor-requirements.md
new file mode 100644
index 0000000000..a14279a098
--- /dev/null
+++ b/.ai/specs/2026-07-04-assembly-editor-requirements.md
@@ -0,0 +1,255 @@
+# Assembly Editor — Requirements
+
+Derived from competitor analysis (two screenshots: V8 engine turbo ~50 steps,
+centrifugal pump ~42 steps with context menu) and user feedback. These are the
+features needed to reach parity with the market leader and make the editor
+production-ready.
+
+---
+
+## 1. Bill of Materials Tree (derived from STEP file)
+
+The left panel must show a **Bill of Materials** section below the step/component
+list, derived entirely from the uploaded CAD model's assembly hierarchy.
+
+### Requirements
+
+- **BOM derived from graph.json**: walk the assembly tree extracted by the geometry
+ service and display every leaf part, grouped by geometry hash (identical parts),
+ with a count.
+- **Display format**: `part_name — count`, e.g. `clamping device washer_din_DIN 6340-13 — 14`.
+ Sort by count descending (most-used parts first) or alphabetically — user toggle.
+- **Gear icon per part**: clicking opens a detail popover (volume, bounding box
+ dimensions, color swatch, which steps reference this part).
+- **Click-to-highlight**: clicking a BOM row highlights all instances of that part
+ in the 3D viewer (emissive tint + camera orbit to frame them).
+- **Multi-select in BOM**: shift/cmd-click selects multiple part types; all instances
+ highlight in the viewer. Useful for "show me all the M8 bolts."
+- **Selected-parts context**: when parts are selected in the BOM, the context menu
+ (right-click or toolbar button) offers grouping actions (see section 5).
+- **BOM updates live**: if the user hides a part or marks it as a fixture (not
+ assembled), the BOM count adjusts.
+- **No manual BOM entry**: the BOM is always derived from the model. Users don't
+ type part names — they come from the STEP file's product names.
+
+---
+
+## 2. View Cube (3D orientation gizmo)
+
+The 3D viewer must include a view cube in the top-right corner for spatial
+orientation and quick view snapping.
+
+### Requirements
+
+- **Orientation display**: shows current camera orientation labeled with
+ Front/Back/Left/Right/Top/Bottom faces.
+- **Click-to-snap**: clicking a face, edge, or corner snaps the camera to that
+ standard view with a smooth animated transition.
+- **Axis arrows**: RGB axis arrows (X=red, Y=green, Z=blue) extending from the
+ cube's corner, matching CAD convention.
+- **Always visible**: rendered on top of the model, not occluded. Fixed position
+ in the top-right of the viewer canvas.
+- **Dark/light mode**: cube colors adapt to the current theme.
+
+### Implementation note
+
+drei provides `GizmoHelper` + `GizmoViewcube` which implements all of the above
+out of the box. The viewer package already depends on drei.
+
+---
+
+## 3. Requirements Pane (Tools, Notes, Standard Notes, Media)
+
+The right panel must support a tabbed "Requirements" (or "Supplements") view
+where authors attach process data to each step.
+
+### Requirements
+
+#### 3.1 Panel structure
+
+- **Tabs at the top**: Tools | Notes | Standard Notes | Media.
+ Each tab shows its section with a "Manage >" link for bulk editing.
+- **Per-step scope**: requirements are attached to the currently selected step.
+ Switching steps updates the panel.
+- **Empty states**: each section shows "No [tools/notes/media] to display" when
+ empty, with an inline "Add" action.
+
+#### 3.2 Tools
+
+- **Add tool references**: search Carbon's existing resource/tool catalog
+ (the `tool` item type and `methodOperationTool` pattern). Selecting a tool
+ links it to the step.
+- **Free-text tool entry**: if the tool isn't in the catalog, enter a name
+ (e.g., "4mm hex key") as a free-text tool reference.
+- **Display**: tool name, optional torque spec (from the step's `fastener.tool`
+ and `fastener.torqueNm` fields), optional image.
+- **Reorder**: drag to reorder tools within a step (order = sequence of tool use).
+
+#### 3.3 Notes
+
+- **Free-text notes**: rich-text or plain-text notes per step. Multiple notes
+ per step allowed.
+- **Warning/caution/info classification**: each note can be tagged as Info,
+ Caution, or Warning (renders with appropriate icon/color: blue/yellow/red).
+- **Display inline**: notes render in the MES playback view alongside the
+ animation.
+
+#### 3.4 Standard Notes
+
+- **Reusable templates**: company-level note templates (e.g., "Apply Loctite 242
+ to threads before insertion", "Verify torque with calibrated wrench").
+- **Manage library**: "Manage >" link opens a modal/page to CRUD standard notes
+ for the company.
+- **Insert into step**: selecting a standard note copies it into the step's notes
+ (one-click attachment, not a reference — so editing the template doesn't change
+ already-published instructions).
+
+#### 3.5 Media
+
+- **Attach images/videos**: upload photos or short videos to a step (e.g., a
+ photo of the real assembly at this stage, a video of a tricky technique).
+- **Storage**: files upload to Supabase storage under the instruction's path.
+- **Display in playback**: media thumbnails show in MES alongside the 3D
+ animation. Tapping opens a lightbox.
+- **Manage**: "Manage >" for bulk upload, reorder, delete.
+
+#### 3.6 Fixtures and Consumables
+
+- **Fixtures**: reference to jigs, fixtures, or workholding from the resource
+ catalog. Displayed as a list per step. Informs the operator what to set up
+ before starting.
+- **Consumables**: adhesives, lubricants, sealants, tape, etc. Free-text with
+ optional catalog link. Displayed per step.
+
+---
+
+## 4. Component Grouping (Clusters, Kits, Subassemblies)
+
+Authors must be able to group parts in the component tree for organization
+and step authoring.
+
+### Requirements
+
+#### 4.1 Context menu
+
+- **Right-click on selected parts** (in the component list, BOM, or 3D viewer)
+ shows a context menu with:
+ - **Create cluster**: group selected parts into a named cluster (visual
+ grouping only — parts appear as children of the cluster in the tree).
+ - **Create kit**: group selected parts into a kit — a set of parts that are
+ always picked/staged together (e.g., "M8 bolt kit: 4x bolt + 4x washer +
+ 4x nut"). Kits show as a single line in the step BOM with their contents
+ expandable.
+ - **Create combination**: merge selected parts into one logical unit for
+ step purposes (e.g., a pre-assembled cartridge treated as one part).
+ - **Create subassembly**: define selected parts as a subassembly with its
+ own internal build sequence. The parent instruction references the
+ subassembly as a single step ("Assemble pump head subassembly"), and the
+ subassembly has its own instructions.
+ - **Hide**: hide selected parts from the viewer (useful for fixtures, jigs,
+ or reference geometry that shouldn't appear in operator instructions).
+ - **Remove highlight**: clear the selection highlight.
+ - **Manage visibility**: submenu to show/hide/ghost individual parts.
+ - **Delete**: remove the selected parts from the instruction (not from the
+ model — just exclude them from the instruction scope).
+
+#### 4.2 Kit behavior
+
+- Kits are defined at the instruction level (not the item/BOM level).
+- A kit has a name, a list of constituent part nodeIds, and an optional
+ part number.
+- When a kit is added to a step, all its parts are included in the step's
+ `partNodeIds` and animate together.
+- Kits appear in the BOM section as a collapsible row: "M8 bolt kit — 4"
+ expanding to show "M8 bolt ×4, M8 washer ×4, M8 nut ×4".
+
+#### 4.3 Subassembly behavior
+
+- A subassembly creates a child `assemblyInstruction` linked via
+ `parentStepId` on the parent instruction's step.
+- The subassembly has its own step sequence, authored in a nested editor
+ view (drill-down navigation).
+- In the parent instruction's playback, the subassembly step shows the
+ subassembly animating as a unit (all its parts moving together from their
+ exploded state to their final pose).
+
+#### 4.4 Data model additions
+
+- **`assemblyGroup`** table: `(id, assemblyInstructionId, name, type
+ ['cluster'|'kit'|'combination'|'subassembly'], partNodeIds TEXT[],
+ childInstructionId? FK, companyId, audit)`.
+- Steps reference groups by including the group's partNodeIds in their own
+ `partNodeIds` (denormalized for playback simplicity) plus a
+ `groupIds TEXT[]` field for display purposes.
+
+---
+
+## 5. Viewer Enhancements (context transparency, nav arrows, timeline)
+
+### 5.1 Context transparency (default render mode)
+
+- Non-active parts render at ~30% opacity with their original color (not
+ wireframe). Active step's parts are fully opaque with a subtle emissive
+ highlight or distinct color.
+- Completed steps' parts are solid at full opacity.
+- This is the default mode (replaces hide-future-parts behavior).
+- A toggle switches between: Ghost (default) | Hidden | Solid (all parts
+ visible, no step context — the "Model" view).
+
+### 5.2 Overlay step navigation
+
+- Large translucent < > arrow buttons on the left and right edges of the
+ viewer, vertically centered. Clicking advances/retreats one step.
+- Arrows visually match the competitor (subtle, semi-transparent, appear
+ on hover or always visible on touch devices).
+
+### 5.3 Continuous animation timeline
+
+- All step animations stitched into one continuous sequence.
+- Footer shows elapsed/total time: "0:06 / 0:58".
+- Scrubber maps to the global timeline, with step boundaries visible as
+ tick marks on the scrubber track.
+- Play button plays through all steps continuously. Clicking a step in the
+ list seeks to that step's start time.
+
+### 5.4 Model / Instructions tabs
+
+- Tab bar at the top of the editor: "Model" | "Instructions".
+- Model tab: full assembly viewer with the BOM tree (section 1), no step
+ context. Explore parts, rotate, inspect.
+- Instructions tab: current step-based editor with playback.
+
+---
+
+## 6. Step auto-description and status
+
+### 6.1 Auto-generated step titles
+
+- When a step's `title` is empty, derive a display title from its parts:
+ verb + part names + fastener spec + quantities.
+- Verb rules: "Add" for single-part insertion, "Assemble" for multi-part
+ steps, "Install" for fastener-only steps.
+- Format: `"Add Seat Rail Clamp, M5 SHCS (×4)"`.
+- Part names come from graph.json node names matched by `partNodeIds`.
+
+### 6.2 Step status indicators
+
+- Each step shows a colored dot: red (has warnings or unresolved issues),
+ yellow (needs review — planner-generated, not yet validated), green
+ (author-validated).
+- Author can toggle a step between review/done states via click or
+ checkbox.
+
+---
+
+## Non-functional Requirements
+
+- **Performance**: BOM tree and step list must render smoothly for assemblies
+ up to 1000 parts. Virtualize the list if needed.
+- **Mobile/touch**: MES playback must work on tablets (gloved touch). Large
+ tap targets for step nav, no hover-dependent interactions.
+- **Offline capability**: not required for Phase 1, but the viewer package
+ should not assume network access during playback (all assets loaded
+ upfront).
+- **Accessibility**: step list and BOM are keyboard-navigable. Screen reader
+ labels on viewer controls.
diff --git a/.ai/specs/2026-07-06-geometry-service-deployment.md b/.ai/specs/2026-07-06-geometry-service-deployment.md
new file mode 100644
index 0000000000..eec3d9a923
--- /dev/null
+++ b/.ai/specs/2026-07-06-geometry-service-deployment.md
@@ -0,0 +1,377 @@
+# Geometry Service Deployment — Two SST Apps
+
+> Status: draft (design resolved, ready for /plan)
+> Author: Brad Barbin (design conversation with Claude)
+> Date: 2026-07-06
+
+## TLDR
+
+Deploy the Python geometry service (`services/geometry`) to production for both
+Carbon hosting flavors using **two separate SST apps**: (1) the existing
+`carbon` SST app (GovCloud/ITAR, per-workspace fan-out) gains a third Fargate
+service on the existing `CarbonCluster`, exposed like ERP/MES behind its own
+ALB + domain (subdomain of the workspace's `itar.carbon.ms`-style domain);
+(2) a new standalone **`carbon-geometry`** SST app at
+`services/geometry/sst.config.ts` deploys *only* the geometry service — its own
+VPC, cluster, and one public Fargate service at `geometry.carbon.ms` — as a
+shared multi-tenant backend for the Vercel-hosted build. Both flavors run the
+same ECR image `carbon/geometry:${sha}` built from the existing
+`services/geometry/Dockerfile`. This spec also **bundles externalizing the
+`/plan` in-memory job store to Redis**, so both flavors can autoscale beyond a
+single replica. Vercel Python functions were evaluated and ruled out.
+
+## Problem Statement
+
+The geometry service converts STEP files to GLB + `graph.json` and produces
+assembly plans. It is consumed server-side by the Inngest tasks
+`packages/jobs/src/inngest/functions/tasks/assembly-convert.ts` and
+`assembly-plan.ts` via `GEOMETRY_SERVICE_URL` / `GEOMETRY_SERVICE_API_KEY`
+(`packages/env/src/index.ts:195-198`). It has a production-ready multi-stage
+Dockerfile but **no production deployment path** — it only runs locally today.
+
+Carbon has two production builds:
+
+1. **Vercel-hosted** — the Node apps run serverless on Vercel. There is no AWS
+ stack to embed the geometry container into.
+2. **AWS GovCloud/ITAR via SST** — `sst.config.ts` deploys per-workspace
+ Fargate services (`CarbonERPService`, `CarbonMESService`) on
+ `CarbonCluster` inside `CarbonVpc2`, fanned out over the `workspaces` table
+ by `ci/src/deploy.ts`.
+
+**Vercel Python functions were evaluated and rejected** for the geometry
+service itself:
+
+- The `cadquery-ocp` (OCCT) wheel dynamically links system libraries
+ (`libgl1`, `libglu1-mesa`, `libxrender1`, `libfontconfig1`, …) that the
+ Dockerfile apt-installs; Vercel's Python runtime cannot install system
+ packages and does not run arbitrary containers.
+- Bundle size: the OCCT wheel (~70 MB) plus numpy/scipy/trimesh/python-fcl/
+ rtree is at best marginal against Vercel's 250 MB uncompressed limit, and
+ the meshopt pass shells out to a Node CLI (`gltf-transform`) from Python —
+ a cross-runtime pattern Vercel functions don't support.
+- `/plan` uses an **in-process job store** (`_plan_job_set` /
+ `_run_plan_job` background thread in `services/geometry/app/main.py`) with
+ status polling at `/plan/{jobId}`. Serverless invocations share no memory,
+ so polling would land on instances that never saw the job.
+- Tessellation is long-running CPU-bound work — a poor fit for function
+ duration limits and per-CPU-second billing.
+
+So the service stays a container in both builds, and each build needs a home
+for it. Separately, the in-memory `/plan` job store makes *any* deployment
+with more than one replica behind a load balancer incorrect — polling can hit
+a task that never saw the job — so this spec externalizes it.
+
+## Proposed Solution
+
+Two SST apps, one Docker image, Redis-backed `/plan` jobs.
+
+### Flavor A — `carbon` app (GovCloud/ITAR): third service, same pattern as ERP/MES
+
+Add a third service to the existing `sst.config.ts` `run()`, cloning the
+ERP/MES service shape (ALB + domain + cert, `dns: false`):
+
+```ts
+const geometry = cluster.addService("CarbonGeometryService", {
+ cpu: "2 vCPU",
+ memory: "4 GB",
+ image: `${process.env.AWS_ACCOUNT_ID}.dkr.ecr.${process.env.AWS_REGION}.amazonaws.com/carbon/geometry:${process.env.IMAGE_TAG}`,
+ loadBalancer: {
+ domain: {
+ name: process.env.URL_GEOMETRY ?? "govcloud.itar.carbon.ms",
+ dns: false,
+ cert: process.env.CERT_ARN_GEOMETRY,
+ },
+ health: { "8000/http": { path: "/health" } },
+ ports: [
+ { listen: "80/http", forward: "8000/http" },
+ { listen: "443/https", forward: "8000/http" },
+ ],
+ },
+ port: 8000,
+ environment: {
+ GEOMETRY_SERVICE_API_KEY: process.env.GEOMETRY_SERVICE_API_KEY,
+ REDIS_URL: process.env.REDIS_URL, // /plan job store (same per-workspace Redis as ERP/MES)
+ },
+ scaling: { min: 1, max: 4, cpuUtilization: 70, memoryUtilization: 80 },
+});
+```
+
+- Same exposure pattern as ERP/MES: public ALB, per-workspace domain + ACM
+ cert, `dns: false` (DNS/cert managed outside SST). Bearer key gates
+ `/convert` and `/plan`; the WAF ACL pattern (`AppAlbWebAcl`) applies —
+ association remains manual, per the existing gotcha.
+- ERP and MES service environments gain
+ `GEOMETRY_SERVICE_URL=https://${URL_GEOMETRY}` and
+ `GEOMETRY_SERVICE_API_KEY`.
+- `ci/src/deploy.ts` per-workspace env gains `URL_GEOMETRY`,
+ `CERT_ARN_GEOMETRY`, and `GEOMETRY_SERVICE_API_KEY` from three new
+ `workspaces` columns (see Data Model Changes). Missing values follow the
+ existing skip-and-log convention.
+- `/plan` jobs use the workspace's existing `redis_url` (the same Redis
+ ERP/MES already receive), namespaced under `geometry:plan:*`.
+
+### Flavor B — `carbon-geometry` app (standalone, serves the Vercel build)
+
+New SST app at `services/geometry/sst.config.ts`:
+
+```ts
+export default $config({
+ app(input) {
+ return {
+ name: "carbon-geometry",
+ home: "aws",
+ region: process.env.AWS_REGION,
+ removal: input?.stage === "prod" ? "retain" : "remove",
+ };
+ },
+ async run() {
+ const vpc = new sst.aws.Vpc("GeometryVpc");
+ const cluster = new sst.aws.Cluster("GeometryCluster", { vpc, forceUpgrade: "v2" });
+ cluster.addService("GeometryService", {
+ cpu: "2 vCPU",
+ memory: "4 GB",
+ image: `${process.env.AWS_ACCOUNT_ID}.dkr.ecr.${process.env.AWS_REGION}.amazonaws.com/carbon/geometry:${process.env.IMAGE_TAG}`,
+ loadBalancer: {
+ domain: {
+ name: process.env.URL_GEOMETRY ?? "geometry.carbon.ms",
+ dns: false,
+ cert: process.env.CERT_ARN_GEOMETRY,
+ },
+ health: { "8000/http": { path: "/health" } },
+ ports: [
+ { listen: "80/http", forward: "8000/http" },
+ { listen: "443/https", forward: "8000/http" },
+ ],
+ },
+ port: 8000,
+ environment: {
+ GEOMETRY_SERVICE_API_KEY: process.env.GEOMETRY_SERVICE_API_KEY,
+ REDIS_URL: process.env.REDIS_URL, // provisioned outside SST, passed as a secret
+ },
+ scaling: { min: 1, max: 4, cpuUtilization: 70, memoryUtilization: 80 },
+ });
+ },
+});
+```
+
+- **Why a second app, not a mode of the first:** SST/Pulumi state is per
+ app + stage. A geometry-only conditional inside the `carbon` app would
+ delete the ERP/MES resources from that stage's state on the next deploy.
+ A separate app has its own state and zero coupling; SST v3 resolves
+ `sst.config.ts` from the working directory, so two apps coexist in the
+ monorepo (deploy runs from `services/geometry/`).
+- **Public at `geometry.carbon.ms`:** the Vercel-hosted apps and their
+ Inngest functions call it over the internet. The ACM cert and DNS record
+ are provisioned manually (same `dns: false` convention);
+ `URL_GEOMETRY` / `CERT_ARN_GEOMETRY` land in GitHub secrets before the
+ first deploy. `GEOMETRY_SERVICE_API_KEY` (one shared key for v1) is the
+ auth gate — it lives only in server-side env (Vercel + GitHub secrets).
+- **Shared multi-tenant:** the service is stateless with respect to tenant
+ data — files flow through pre-signed URLs, nothing is stored; `/plan` job
+ records in Redis are transient and keyed by opaque job IDs. One deployment
+ serves all Vercel-hosted tenants (cost floor per instance ≈ ALB ~$20/mo +
+ min-1 2 vCPU/4 GB Fargate task ~$70/mo makes per-tenant stacks wasteful).
+- **Redis provisioned outside SST** and passed as `REDIS_URL`, consistent
+ with how the main stack consumes each workspace's `redis_url` — the SST
+ app stays a pure consumer of secrets.
+- **Not part of the workspace fan-out.** `ci/src/deploy.ts` is untouched by
+ this flavor; the standalone app deploys once per environment on its own
+ cadence.
+
+### `/plan` job store externalization (in scope)
+
+The in-memory dict + prune in `services/geometry/app/main.py`
+(`_plan_job_get` / `_plan_job_set` / `_plan_jobs_prune`) is replaced by a
+Redis-backed store so any replica can answer `/plan/{jobId}`:
+
+- New dependency `redis` (sync client) in `pyproject.toml`.
+- Job records stored as JSON at `geometry:plan:{jobId}` with a TTL matching
+ the current prune window — TTL replaces `_plan_jobs_prune()`.
+- `POST /plan` writes the initial record and still runs the conversion on a
+ background thread in the receiving task; the thread updates the Redis
+ record on progress/completion/failure. Status polling reads Redis, so it
+ is replica-independent.
+- **Fallback:** when `REDIS_URL` is unset, the store falls back to the
+ current in-memory implementation (local dev, tests, docker-compose) —
+ no behavior change for existing dev workflows. Deployed environments always
+ set `REDIS_URL`.
+- Wire contract unchanged: request/response shapes for `/plan` and
+ `/plan/{jobId}` stay exactly as defined in
+ `docs/specs/animated-work-instructions-contracts.md`.
+- Known limitation, accepted for v1: if a task is killed mid-job (deploy,
+ scale-in), the background thread dies and the job parks until its TTL;
+ the app-side recovery added in `fix(assembly): recover lost plan jobs`
+ already handles re-submission.
+
+### CI wiring
+
+- **Image build:** add `geometry` to the `deploy.yml` build matrix, with
+ `context: ./services/geometry` and `file: ./services/geometry/Dockerfile`
+ (the erp/mes entries keep the root Dockerfile + `APP` build-arg). Add
+ `services/geometry/**` to the workflow's `paths`. This guarantees
+ `carbon/geometry:${github.sha}` exists for every sha the `carbon` app's
+ `${IMAGE_TAG}` interpolation can reference — the main-app deploy never
+ points at a missing tag.
+- **Standalone deploy:** a new workflow (or job) triggered on
+ `services/geometry/**` pushes to `main`, which runs
+ `npx --yes [email protected] deploy --stage prod` from `services/geometry/` with
+ the standalone app's env (`AWS_*`, `IMAGE_TAG=${github.sha}`,
+ `URL_GEOMETRY`, `CERT_ARN_GEOMETRY`, `GEOMETRY_SERVICE_API_KEY`,
+ `REDIS_URL`). ERP/MES pushes never churn the geometry stack, and vice
+ versa. Pinned to the same `[email protected]` the CI deploy uses.
+- The GovCloud flavor picks the image up through the existing
+ `ci/src/deploy.ts` fan-out with the same `IMAGE_TAG`.
+
+### Consumer wiring (both flavors)
+
+No consumer-code changes. `GEOMETRY_SERVICE_URL` and
+`GEOMETRY_SERVICE_API_KEY` already exist in `@carbon/env` and are already
+consumed by the Inngest tasks. Deployment only supplies values:
+
+| Build | `GEOMETRY_SERVICE_URL` | `GEOMETRY_SERVICE_API_KEY` |
+|-------|------------------------|----------------------------|
+| GovCloud (`carbon` app) | `https://${URL_GEOMETRY}` (per-workspace subdomain, e.g. `govcloud.itar.carbon.ms`) | per-workspace secret (new `workspaces` column) |
+| Vercel-hosted | `https://geometry.carbon.ms` | one shared secret in Vercel env (v1) |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Host geometry on Vercel Python functions? | **No — container on AWS in both builds** | Native OCCT system libs, ~250 MB bundle ceiling, Python→Node CLI shell-out, in-memory `/plan` job state, long CPU-bound requests. |
+| One SST app with a geometry-only mode? | **No — two separate SST apps** | Pulumi state is per app+stage; conditionally omitting ERP/MES would delete them. Separate app = separate state, independent cadence. |
+| Standalone app location | `services/geometry/sst.config.ts` | Colocated with the service it deploys; SST resolves config from cwd, so it coexists with the root `sst.config.ts`. |
+| GovCloud exposure | **Public ALB + per-workspace domain/cert, same pattern as ERP/MES** (resolved OQ-1) | Uniform with the existing services; avoids the Cloud Map/Service Connect unknown entirely; bearer key + optional WAF gate it. |
+| Standalone exposure | **Public ALB at `geometry.carbon.ms` + ACM cert + bearer key** (resolved OQ-1) | Vercel functions call over the internet; `dns: false` + manually provisioned cert, matching the existing convention. |
+| Standalone tenancy | **One shared deployment, one shared API key for v1** (resolved OQ-4) | Stateless w.r.t. tenant data (pre-signed URLs); single-secret auth matches `app/auth.py`; per-tenant keys deferred until revocability is needed. |
+| GovCloud API-key source | **New `workspaces` columns** (resolved OQ-2) | Consistent with every other per-workspace secret; `deploy.ts` skip-and-log convention applies. |
+| `/plan` job store | **Externalize to Redis now, in this spec** (resolved OQ-3) | Enables autoscaling in both flavors from day one; TTL replaces pruning; in-memory fallback preserves local dev. |
+| Autoscaling | min 1 / max 4, 70% CPU / 80% mem | Allowed because job state is external; capped below ERP/MES's max 10 since each task is CPU-heavy and volume is lower. |
+| Image strategy | **Single image `carbon/geometry:${sha}`, built in the existing `deploy.yml` matrix** | Guarantees the tag exists for every sha the main app deploys; both flavors run identical bits. |
+| Config duplication between the two apps | **Accept ~40 lines of duplication** | The two service definitions differ for good reasons (env sources, domains); a shared construct across SST apps isn't worth the coupling. |
+| Service sizing | 2 vCPU / 4 GB (match ERP/MES) | Tessellation is CPU-bound; matches the proven baseline; tune later from metrics. |
+| Redis provisioning (standalone) | **Outside SST, passed as `REDIS_URL` secret** | Mirrors how the main stack consumes `redis_url`; keeps the SST app a pure consumer of secrets. |
+| Wire contracts | **Unchanged** | `/convert`, `/plan`, `graph.json` shapes are owned by `docs/specs/animated-work-instructions-contracts.md`; this spec changes deployment + job-store internals only. |
+
+Heuristics checklist (infra spec — most rows N/A):
+
+| # | Heuristic | Answer |
+|---|-----------|--------|
+| 1 | Multi-tenancy | No new app tables. The service holds no tenant data at rest; `/plan` Redis records are transient, opaque-ID-keyed. GovCloud isolation is per-workspace stacks. |
+| 2 | Service shape | N/A — no new `{module}.service.ts` functions; existing Inngest tasks unchanged. |
+| 3 | RLS coverage | N/A — no app-database surface. (New columns are on the CI `workspaces` table, which is service-role-only.) |
+| 4 | Permission scoping | N/A for routes; service-to-service auth is the existing bearer-key scheme in `services/geometry/app/auth.py`. |
+| 5 | Form pattern | N/A — no UI. |
+| 6 | Module layout | N/A — no ERP module changes. |
+| 7 | Backward compatibility | Wire contracts frozen per `docs/specs/animated-work-instructions-contracts.md`; job-store change is internal; env additions only. |
+
+## Data Model Changes
+
+No application-database changes. The CI **`workspaces`** table (the deploy
+fan-out control table, not an app table) gains three nullable columns,
+following its existing flat-secret convention:
+
+- `url_geometry` — per-workspace geometry hostname (e.g.
+ `govcloud.itar.carbon.ms`).
+- `cert_arn_geometry` — ACM cert ARN for that hostname.
+- `geometry_service_api_key` — per-workspace bearer secret.
+
+`ci/src/deploy.ts`'s `Workspace` type gains the same three fields; workspaces
+missing them are skipped with a log line, per the existing convention.
+
+## API / Service Changes
+
+- **`services/geometry`**: replace the in-memory `/plan` job store with the
+ Redis-backed store described above (`redis` dependency, `REDIS_URL` env,
+ TTL-based expiry, in-memory fallback when unset). Wire contracts unchanged.
+- **`sst.config.ts` (root)**: add `CarbonGeometryService`; add
+ `GEOMETRY_SERVICE_URL` / `GEOMETRY_SERVICE_API_KEY` to ERP and MES
+ `environment`.
+- **`services/geometry/sst.config.ts`**: new standalone app (sketch above).
+- **`.github/workflows/deploy.yml`**: `geometry` in the build matrix +
+ `services/geometry/**` in `paths`.
+- **New workflow** for the standalone deploy (path-filtered on
+ `services/geometry/**`).
+- **`ci/src/deploy.ts`**: three new `Workspace` fields passed into the
+ per-workspace SST env.
+- **`services/geometry/README.md`**: document both deploy paths and the
+ Redis job store.
+
+## UI Changes
+
+N/A — no user-facing surface; the viewer already consumes the outputs.
+
+## Acceptance Criteria
+
+- [ ] Push to `main` touching `services/geometry/**` builds and pushes
+ `carbon/geometry:${sha}` (and `:latest`) to ECR.
+- [ ] GovCloud: after `ci:deploy`, each fully-configured `aws === true`
+ workspace stack contains a running `CarbonGeometryService` behind its
+ own ALB; `https://${url_geometry}/health` returns `{ "ok": true, ... }`
+ and `POST /convert` without a bearer token returns 401.
+- [ ] GovCloud: a workspace missing any of the three new columns is skipped
+ with a log line and its ERP/MES deploy is unaffected.
+- [ ] GovCloud: uploading a STEP file to an assembly in a deployed workspace
+ completes the Inngest convert pipeline (GLB + `graph.json` land in
+ storage; viewer renders the model).
+- [ ] Standalone: `https://geometry.carbon.ms/health` returns 200 publicly;
+ `POST /convert` without a bearer token returns 401; with the correct
+ key it processes a STEP fixture end-to-end.
+- [ ] Standalone: an ERP/MES-only push to `main` does not trigger the
+ geometry deploy workflow, and a `services/geometry/**` push does not
+ redeploy ERP/MES.
+- [ ] `/plan` with `REDIS_URL` set: start a job, then poll `/plan/{jobId}`
+ against a **different** replica (or after a store round-trip in tests)
+ and receive correct status/result; job record expires after the TTL.
+- [ ] `/plan` without `REDIS_URL`: existing in-memory behavior and the
+ existing pytest suite pass unchanged.
+- [ ] `sst deploy` of the standalone app from `services/geometry/` does not
+ mutate any resource in the `carbon` app's stacks (verified via the
+ deploy diff).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Task killed mid-`/plan` job (deploy/scale-in) orphans the job until TTL | Med | Accepted for v1; app-side recovery (`recover lost plan jobs`) re-submits; record a `startedAt` so the app can detect stalls. |
+| Root-app deploy references a geometry image tag that was never built | Med | Geometry joins the same `deploy.yml` build matrix, so every deployed sha has a geometry image. |
+| Public endpoints abuse (both flavors) | Med | Bearer key required for all non-`/health` routes; WAF rate-limit ACL available (association is manual, same as `AppAlbWebAcl`). |
+| Redis unavailable at runtime | Med | `/plan` returns a 5xx with the existing error envelope rather than silently falling back to memory in deployed envs (fallback is dev-only, gated on `REDIS_URL` unset). |
+| Two `sst.config.ts` files → deploying from the wrong cwd | Low | Deploys only run via CI workflows with fixed working directories; document in `services/geometry/README.md`. |
+| SST version drift between the two apps | Low | Pin the standalone deploy to the same `[email protected]` the CI deploy uses. |
+| Per-workspace ALB cost for geometry (GovCloud) | Low | Accepted — consistency with ERP/MES chosen over cost; ~$20/mo/workspace. |
+
+## Open Questions
+
+> 🛑 HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] **OQ-1: Standalone + GovCloud hostnames.** — **Answer:** GovCloud
+ geometry serves per-workspace at `govcloud.itar.carbon.ms` (stored in
+ the new `url_geometry` column; public ALB + cert, same pattern as
+ ERP/MES — this supersedes the earlier internal-only lean). Standalone
+ serves at `geometry.carbon.ms`. Certs/DNS provisioned manually per the
+ `dns: false` convention. *(Resolved by Brad, 2026-07-06.)*
+- [x] **OQ-2: GovCloud API-key source.** — **Answer:** new
+ `geometry_service_api_key` column on the CI `workspaces` table (plus
+ `url_geometry`, `cert_arn_geometry`), consistent with every other
+ per-workspace secret; `deploy.ts` skip-and-log convention applies.
+ *(Resolved by Brad, 2026-07-06.)*
+- [x] **OQ-3: `/plan` job-state externalization.** — **Answer:** bundled into
+ this spec — Redis-backed job store with TTL expiry and dev-only
+ in-memory fallback; autoscaling (max 4) enabled in both flavors.
+ *(Resolved by Brad, 2026-07-06.)*
+- [x] **OQ-4: Standalone key granularity.** — **Answer:** one shared
+ `GEOMETRY_SERVICE_API_KEY` for all Vercel-hosted tenants in v1
+ (matches single-secret auth in `app/auth.py`); per-tenant keys deferred.
+ *(Resolved by Brad, 2026-07-06.)*
+- [x] **OQ-5: Internal discovery mechanism.** — **Answer:** moot — OQ-1's
+ resolution puts GovCloud geometry behind an ALB + domain like ERP/MES,
+ so `GEOMETRY_SERVICE_URL` is a plain https URL; no Cloud Map/Service
+ Connect dependency. *(Resolved as a consequence of OQ-1, 2026-07-06.)*
+
+## Changelog
+
+- 2026-07-06: Created from deployment design conversation (Vercel Python
+ functions ruled out; two-SST-app split agreed).
+- 2026-07-06: All open questions resolved via grill. GovCloud flavor changed
+ from internal-only to public ALB + per-workspace domain (OQ-1); `/plan`
+ Redis job store pulled into scope (OQ-3); autoscaling max 4 enabled.
diff --git a/.ai/specs/2026-07-06-sealed-enclosure-insertion-problem.md b/.ai/specs/2026-07-06-sealed-enclosure-insertion-problem.md
new file mode 100644
index 0000000000..358d74a22e
--- /dev/null
+++ b/.ai/specs/2026-07-06-sealed-enclosure-insertion-problem.md
@@ -0,0 +1,87 @@
+# Decision needed: sealed-enclosure insertion order (SA-BCU)
+
+Status: **open — needs a design call before more planner work**
+Date: 2026-07-06
+
+## The gap
+
+Brad authored the correct SA-BCU order in the app (12 steps):
+
+box → PCB → 4×4mm screws → connector → 4×2.5mm screws → seal → lid →
+4×4mm screws → TPF119 ×4 (each its own step).
+
+After tonight's ordering principles (dependency spine, securing jump,
+sandwich, weakly-secured-last, corridor steps) **plus** clean units (R1 mapping
+subtraction + R2 joint ejection), the planner still does **not** reproduce it.
+Current output flags the box, both screw sets, and the clips; the 409-solid
+merged PCB body single-blocker-merges into the box.
+
+This is NOT another ordering heuristic to add. The ordering rules are right. The
+blocker is upstream, and it splits into two distinct problems.
+
+## Problem 1 (the real one): merged-unit collision fidelity
+
+The planner collapses the 409-solid PCB into ONE concatenated collision mesh.
+That merged mesh interpenetrates the enclosure's interior bosses/walls beyond
+tolerance (component overhangs + tessellation artifacts). So greedy disassembly
+can't find a collision-free removal for it → it flags → single-blocker merge
+into the box → and every interior part that depended on the box being open
+(screws, connector) flags in cascade.
+
+The *physical* truth is simple: once the lid and seal are off, the PCB lifts
+straight up. Reverse-disassembly already models "lid comes off first," so the
+sequence logic is sound — it's the **collision geometry of the merged body**
+that lies.
+
+Options (each a real tradeoff, none free):
+
+- **A. Representative-solid proxy** — plan the unit against its hub solid (the
+ bare board) as the collision body, not the 409-mesh concatenation; the tiny
+ components ride along for display and never independently collide. Principled
+ (the board is what actually inserts), cheap, avoids phantom interpenetration.
+ Risk: a unit whose *envelope* (not just its board) collides — e.g. a tall
+ connector on the board hitting the lid — is under-modeled. Mitigate: proxy =
+ convex hull of the unit, not just the hub.
+- **B. Decimate/repair the merged mesh** before collision. Reduces artifacts,
+ keeps concavity. Cost: mesh processing per unit; doesn't fully fix real
+ component overhang.
+- **C. Widen tolerance for merged units.** Rejected — this is the fail-open
+ trap the sandwich regression already taught us; corrupts collision truth.
+- **D. Author the order.** The escape hatch that already exists and that Brad
+ used. Accept that deeply-enclosed multi-body units may need human authoring
+ and make that ergonomic (it already is — authored steps are preserved).
+
+Leaning **A (convex-hull proxy for merged units)** as the principled fix, with
+**D** as the permanent fallback. A is a contained change to `_merge_units`
+(swap the concatenated mesh for a hull) + the acceptance runner as the gate.
+
+## Problem 2 (smaller): open-cavity insertion is only collision-free against the OPEN sub-assembly
+
+Parts inserted into a cavity that a later part closes (PCB into the box before
+the lid) are collision-free only against the sub-assembly *as it exists at that
+step*, not against the finished closed model. The planner already gets this
+right via reverse-disassembly (remove the closing part first, then the interior
+is exposed). So Problem 2 is **already handled** — it only *appears* broken
+because Problem 1 makes the interior body un-removable in the first place. Fix
+Problem 1 and this resolves with it. No separate work expected; flagged here so
+we don't mistake the cascade for two bugs.
+
+## What is already done and NOT in question
+
+- R1 (mapping subtraction) — a unit can't contain another BOM line's parts.
+- R2 (joint ejection) — an outside fastener's clamped member leaves the unit
+ (connector, LQFP, PCB board eject from the over-inclusive authored Board unit).
+- All ordering principles. The seat rail is byte-stable and correct.
+
+## Recommendation
+
+1. Prototype option A (hull proxy) behind the acceptance runner
+ (`.ai/scratch/geometry-bcu-acceptance.py`) — one contained change, measurable
+ against the authored 12 steps.
+2. If A doesn't clear the flags, fall back to D (authoring) as the shipped
+ answer for enclosure-class assemblies and move on — not every finished-solid
+ model can yield its build order from geometry alone, and that's an honest
+ product boundary, not a planner bug.
+
+Do NOT keep tuning ordering heuristics against this model — the order is not the
+problem.
diff --git a/.github/workflows/geometry.yml b/.github/workflows/geometry.yml
new file mode 100644
index 0000000000..48d9225a52
--- /dev/null
+++ b/.github/workflows/geometry.yml
@@ -0,0 +1,51 @@
+name: Geometry Service
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - "services/geometry/**"
+ - ".github/workflows/geometry.yml"
+ push:
+ branches: [main]
+ paths:
+ - "services/geometry/**"
+ - ".github/workflows/geometry.yml"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ name: Test
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: services/geometry
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+ cache: pip
+ cache-dependency-path: services/geometry/pyproject.toml
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - run: npm install -g @gltf-transform/[email protected]
+ - run: pip install -e ".[dev]"
+ - run: pytest -q
+
+ docker:
+ name: Docker Build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: docker/setup-buildx-action@v3
+ - uses: docker/build-push-action@v6
+ with:
+ context: services/geometry
+ push: false
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
diff --git a/README.md b/README.md
index b749d14bad..e2fbbfdf89 100644
--- a/README.md
+++ b/README.md
@@ -345,22 +345,28 @@ To run a command against a single workspace, use `pnpm --filter`:
$ pnpm --filter @carbon/react test
```
-To restore a production database snapshot locally:
+To restore a production database snapshot locally, use the `scripts/restore-database.sh` script. It handles both plain-text `.backup` and custom-format `.dump` archives, drops and rebuilds the public schema, realigns internal sequences, and resets storage metadata.
1. Export a backup from your production Supabase project (`pg_dump` or Supabase Dashboard → Database → Backups).
2. Boot the stack **without applying migrations** so they don't fight the dump's schema state:
```bash
$ crbn up --no-migrate
```
-3. Find the live Postgres port (`crbn status` shows it; or read `PORT_DB` from `.env.local`).
-4. Pipe the backup into the local DB as the superuser (`supabase_admin` for plain-text dumps, or use `pg_restore` for `.dump` archives):
+3. Run the restore script from your worktree root, passing the path to the backup file:
```bash
- $ source .env.local
- $ PGPASSWORD=postgres psql -h localhost -p "$PORT_DB" -U supabase_admin -d postgres < /path/to/backup.sql
+ $ ./scripts/restore-database.sh /path/to/db_cluster.backup
# …or for .dump archives:
- $ PGPASSWORD=postgres pg_restore -h localhost -p "$PORT_DB" -U supabase_admin -d postgres /path/to/backup.dump
+ $ ./scripts/restore-database.sh /path/to/postgres_YYYYMMDD.dump
```
-5. Regenerate types so app code reflects the restored schema:
+ To also get local admin access, set `ADMIN_EMAIL` to your production email. The script will upgrade your account to Admin in all companies you already belong to and reset your password locally:
+ ```bash
+ $ [email protected] ./scripts/restore-database.sh /path/to/backup.backup
+ # Optional: set a custom local password (default: localpass)
+ $ [email protected] ADMIN_PASSWORD=mypass ./scripts/restore-database.sh /path/to/backup.backup
+ ```
+ > **Note:** Emails are not scrubbed — real production addresses will be present in the local DB. Ensure local email sending is disabled or pointed at a sandbox (e.g. Mailpit) before triggering any email flows.
+
+4. Regenerate types so app code reflects the restored schema:
```bash
$ pnpm db:types
```
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index cd058d8f73..704ba81ea6 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -324,16 +324,18 @@ const CadModelUpload = ({
)}
>
<input {...getInputProps()} name="file" className="sr-only" />
- <div className="flex flex-col h-full w-full p-4">
- <CardHeader>
- <CardTitle>{title}</CardTitle>
- </CardHeader>
+ <div className="relative flex flex-col flex-1 min-h-0 w-full p-4">
+ {title && (
+ <CardHeader className="absolute top-0 left-0 z-10">
+ <CardTitle>{title}</CardTitle>
+ </CardHeader>
+ )}
<div className="flex flex-col flex-grow items-center justify-center gap-2 p-6">
- {file && <Spinner className={cn("h-16 w-16", title && "-mt-16")} />}
+ {file && <Spinner className="h-16 w-16" />}
{file && (
<>
- <p className="text-lg text-card-foreground mt-8">{file.name}</p>
+ <p className="text-lg text-card-foreground">{file.name}</p>
<p className="text-muted-foreground group-hover:text-foreground">
{convertKbToString(Math.ceil(file.size / 1024))}
</p>
@@ -341,15 +343,10 @@ const CadModelUpload = ({
)}
{!file && (
<>
- <div
- className={cn(
- "p-4 bg-accent rounded-full group-hover:bg-primary",
- title ? "-mt-16" : "-mt-6"
- )}
- >
+ <div className="p-4 bg-accent rounded-full group-hover:bg-primary">
<LuCloudUpload className="mx-auto h-12 w-12 text-muted-foreground group-hover:text-primary-foreground" />
</div>
- <p className="text-base text-muted-foreground group-hover:text-foreground mt-8">
+ <p className="text-base text-muted-foreground group-hover:text-foreground">
Choose file to upload or drag and drop
</p>
<p className="text-xs text-muted-foreground group-hover:text-foreground">
diff --git a/apps/erp/app/components/SortableList.tsx b/apps/erp/app/components/SortableList.tsx
index 40528726bb..10a9dc2986 100644
--- a/apps/erp/app/components/SortableList.tsx
+++ b/apps/erp/app/components/SortableList.tsx
@@ -86,7 +86,7 @@ function SortableListItem<T>({
value={item}
className={cn(
"relative z-auto grow",
- "h-full rounded-md bg-muted/40",
+ "h-full rounded-md bg-accent/30 dark:bg-background/40",
"border border-border rounded-lg ",
!isExpanded && !isReadOnly && "cursor-grab",
isHighlighted && "border-2 border-primary",
@@ -257,7 +257,7 @@ function SortableList<T extends Item>({
values={items}
// biome-ignore lint/suspicious/noEmptyBlockStatements: suppressed due to migration
onReorder={isReadOnly ? () => {} : onReorder}
- className="flex flex-col"
+ className="flex flex-col gap-2"
>
{items?.map((item, index) =>
renderItem({
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts
index c59e0f1a0e..d7f8e82949 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/usePurchaseInvoiceAutoFill.ts
@@ -113,11 +113,10 @@ export function usePurchaseInvoiceAutoFill(
});
const [supplierDetails, paymentTermData] = await Promise.all([
- // @ts-expect-error Supabase composite key issue
carbon
.from("supplier")
.select(
- "currencyCode, purchasingContactId, supplierShipping!supplierId(shippingSupplierLocationId)"
+ "currencyCode, purchasingContactId, supplierShipping!supplierShipping_supplierId_fkey(shippingSupplierLocationId)"
)
.eq("id", resolvedSupplierId)
.single(),
@@ -142,7 +141,8 @@ export function usePurchaseInvoiceAutoFill(
finalLocationId =
resolvedLocationId ??
paymentTermData.data.invoiceSupplierLocationId ??
- supplierDetails.data.supplierShipping?.shippingSupplierLocationId ??
+ supplierDetails.data.supplierShipping?.[0]
+ ?.shippingSupplierLocationId ??
undefined;
resolvedCurrencyCode =
@@ -240,7 +240,7 @@ export function usePurchaseInvoiceAutoFill(
carbon
.from("supplier")
.select(
- "currencyCode, purchasingContactId, supplierShipping!supplierId(shippingSupplierLocationId)"
+ "currencyCode, purchasingContactId, supplierShipping!supplierShipping_supplierId_fkey(shippingSupplierLocationId)"
)
.eq("id", newValue.value)
.single(),
@@ -263,7 +263,8 @@ export function usePurchaseInvoiceAutoFill(
undefined,
invoiceSupplierLocationId:
paymentTermData.data.invoiceSupplierLocationId ??
- supplierData.data.supplierShipping?.shippingSupplierLocationId ??
+ supplierData.data.supplierShipping?.[0]
+ ?.shippingSupplierLocationId ??
undefined,
currencyCode: supplierData.data.currencyCode ?? undefined,
paymentTermId: paymentTermData.data.paymentTermId ?? undefined
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
index 14ea110d77..99c5746c13 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx
@@ -109,7 +109,7 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {
carbon
?.from("customer")
.select(
- "currencyCode, salesContactId, customerShipping!customerId(shippingCustomerLocationId)"
+ "currencyCode, salesContactId, customerShipping!customerShipping_customerId_fkey(shippingCustomerLocationId)"
)
.eq("id", newValue.value)
.single(),
@@ -132,7 +132,8 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {
undefined,
invoiceCustomerLocationId:
paymentTermData.data.invoiceCustomerLocationId ??
- customerData.data.customerShipping?.shippingCustomerLocationId ??
+ customerData.data.customerShipping?.[0]
+ ?.shippingCustomerLocationId ??
undefined,
currencyCode: customerData.data.currencyCode ?? undefined,
paymentTermId: paymentTermData.data.paymentTermId ?? undefined
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index e6babd236f..4c19493302 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1698,6 +1698,7 @@ export async function getPartUsedIn(
salesOrderLines,
shipmentLines,
supplierQuotes,
+ assemblyInstructions,
jobMaterialUsage
] = await Promise.all([
client
@@ -1799,6 +1800,13 @@ export async function getPartUsedIn(
.eq("itemId", itemId)
.eq("companyId", companyId)
.limit(100),
+ client
+ .from("assemblyInstruction")
+ .select("id, documentReadableId:name, version")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ .limit(100)
+ .order("createdAt", { ascending: false }),
getJobMaterialUsageForItem(client, { itemId, companyId })
]);
@@ -1815,6 +1823,7 @@ export async function getPartUsedIn(
salesOrderLines: salesOrderLines.data ?? [],
shipmentLines: shipmentLines.data ?? [],
supplierQuotes: supplierQuotes.data ?? [],
+ assemblyInstructions: assemblyInstructions.data ?? [],
jobMaterialUsage
};
}
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index a16ac3f2f1..5900c57dc8 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -382,7 +382,6 @@ const BillOfMaterial = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
- className="my-2 "
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 670af24e56..4375465853 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -711,7 +711,6 @@ const BillOfProcess = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={() => setSelectedItemId(null)}
- className="my-2"
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
index bf473104d6..046729d41f 100644
--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
@@ -58,6 +58,7 @@ export function UsedInSkeleton() {
export type UsedInKey =
| Database["public"]["Enums"]["itemType"]
+ | "assemblyInstructions"
| "issues"
| "jobMaterials"
| "jobs"
@@ -513,6 +514,8 @@ function getUseInLink(
itemReadableIdWithRevision: string
) {
switch (key) {
+ case "assemblyInstructions":
+ return path.to.assemblyInstruction(child.id);
case "Part":
return path.to.partDetails(child.id);
case "Material":
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 1308d704fa..78e24e0a84 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -11,6 +11,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.
- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.
- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.
+- **Assembly Instructions are internal-only** (feature flag) while the module matures: the nav entry is in `internalOnlyRoutes` (`useProductionSubmodules.tsx`, via `useFlags().isInternal`), and `requireAssembliesInternal` (`production.server.ts`) redirects non-internal users out of `production/assemblies`, `production/assemblies/new`, and every `x+/assembly+` route (layout loader). Mirrors the settings backups gate; drop the gates to ship publicly.
- **Maintenance Dispatch** — reactive/scheduled repair for work centers with comments, events, items, and linked work centers.
- **Scheduling** — infinite-capacity backward scheduling via `schedule` edge function. MUST use `triggerJobSchedule` to reschedule, never direct date writes.
@@ -53,6 +54,10 @@ pnpm --filter @carbon/erp test
| `productionEvent` | Time tracking: type (Labor/Machine/Setup), start/end, employee |
| `productionQuantity` | Output: type (Production/Scrap/Rework), quantity, scrapReason |
| `procedure` / `procedureStep` / `procedureParameter` | Versioned work instructions |
+| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer AND the typed-step fields mirrored from `jobOperationStep` (`type` `procedureStepType`, tiptap `description` with derived `instructionText`, `required`, UoM/min/max, `listValues`) for eventual copy into job operations. `motion`/`camera` are authored directly in the 3D viewer (drag the red waypoint path → relative `linear`/`L` motion; "Set view" captures the camera pose), autosaved via `updateAssemblyStepMotion` / the `steps/motion/$stepId` route — separate from the step form's `upsertAssemblyInstructionStep` (which rewrites `title`/typed fields). There is no numeric motion editor. Playback visibility is presence-based (`@carbon/viewer` `visualForComponent`): a component exists on the canvas only once its step has run; components no step installs render like future-step ones (hidden during playback, future-components toggle while paused). AABB fallback motions for `"none"`-motion steps consider only PRIOR-step components as obstacles and fade in when no collision-free path exists or when the component interpenetrates a present component (mated parts — sliders on rails, fasteners in bores — never get fabricated paths; the planner is the only authority for those) |
+| `assemblyInstructionStepMaterial` | BOM parts consumed at a step (`stepId` → `itemId` + optional quantity; stored by itemId so links survive make-method re-versioning; picker limited to the item's make-method BOM; UNIQUE `(stepId, itemId)`). Auto-populated from `assemblyComponentMapping` via `syncAssemblyStepMaterialsFromMappings` — additive only (manual quantities/deletions survive), triggered on step generation, component add, mapping create, and "Match BOM" |
+| `assemblyInstructionStepRequirement` / `assemblyStandardNote` | Per-step tools/fixtures/consumables/notes/media; reusable note templates |
+| `assemblyComponentMapping` / `assemblyUnit` / `assemblyPlanJob` | Geometry↔BOM item mapping, authored planner units (model-scoped "plan as one component" overrides), and geometry-service plan/convert job tracking. Planning is LAZY — conversion does not chain a plan run; the first "Generate Steps" click (or an explicit re-plan) starts it, pre-creating a Queued `assemblyPlanJob` row the worker adopts via `planJobId`. The clicking tab polls and auto-generates the steps when the plan lands |
| `maintenanceDispatch` / `maintenanceSchedule` | Equipment maintenance tracking |
| `demandForecast` / `demandProjection` | Demand planning data |
| `scrapReason` / `maintenanceFailureMode` | Reference data for production and maintenance |
@@ -71,6 +76,13 @@ pnpm --filter @carbon/erp test
- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`)
- `getProductionPlanning` — MRP-driven production planning (RPC `get_production_planning`)
- `upsertMaintenanceDispatch` / `upsertMaintenanceSchedule` — maintenance management
+- `getAssemblyInstruction(s)` / `upsertAssemblyInstructionStep` / `getAssemblyInstructionStepMaterials` — assembly instruction authoring; the step upsert derives `instructionText` from the tiptap `description` (viewer/MES consume the plain text)
+- `updateAssemblyStepMotion` — partial `motion`/`camera` patch for one step, used by the 3D path/camera editor's autosave (never touches `title`/typed fields); `camera: null` clears the pose (return to auto-framing). Deleting an instruction also drops the model's cached plan via `deleteAssemblyInstruction` → `invalidateAssemblyPlanCache`
+- `generateAssemblyStepsFromPlan` — plan.json → draft steps via `buildAssemblyStepGroups` (`@carbon/viewer`): sequence order, consecutive identical components merged, subassembly `groups` one step (titled by the unit `name`), `mergedInto` components riding their host's step; planner-flagged components (blockedBy / failed verification) store motion "none" + `warnings: { flagged, blockedBy }` (the viewer fades them in — no fabricated paths); `mode: "regenerate"` replaces existing steps, refused while any step is `planConfidence: "manual"` or status `Done`. Also seeds each step's materials from the component→BOM mappings (best-effort)
+- `syncAssemblyStepMaterialsFromMappings` — adds mapped BOM items (`assemblyComponentMapping`) to steps' materials from their `componentNodeIds` (quantity = instance count in the step); additive + best-effort, never updates or removes rows; scopable by `stepIds` / `geometryHashes` / `onlyComponentNodeIds`. Called from the step-components autosave route (newly added nodes only), the mapping-create route (that hash only), and the "Match BOM" route (full backfill)
+- `getAssemblyUnits` / `upsertAssemblyUnit` / `deleteAssemblyUnit` — model-scoped "plan as one component" overrides (`assemblyUnit`: `componentNodeIds[]` + optional `itemId`), authored from the BOM tree
+- **Unit derivation** (`deriveAssemblyUnits`, `@carbon/utils`, pure): CAD exports are usually FLAT, so the planner's rigid bodies come from BOM membership, not tree position — an LLM (`assignComponentsToBom`, gpt-4o-mini, `@carbon/jobs`) assigns each distinct component name to a BOM line (electronic footprints → the PCB line), leaves group by line, and a line collapses into one body only at quantity ≤ 1 with ≥ 2 leaves. Authored `assemblyUnit` rows always collapse. The `assembly-plan` worker (`loadPlanUnits`) derives these and sends multi-leaf units as `options.units` to the geometry `/plan` endpoint, which merges them for planning and expands them back to member leaves
+- `getFlattenedBomMaterials` — the item's engineering BOM flattened through Make subassemblies; feeds the assembly BOM tree and the per-step material picker
## Key Exports
diff --git a/apps/erp/app/modules/production/assembly-debug.server.ts b/apps/erp/app/modules/production/assembly-debug.server.ts
new file mode 100644
index 0000000000..7c7654a446
--- /dev/null
+++ b/apps/erp/app/modules/production/assembly-debug.server.ts
@@ -0,0 +1,38 @@
+import { appendFileSync } from "node:fs";
+
+// TEMPORARY debugging instrumentation for the assembly step save/motion bug.
+// Writes one JSON line per server action hit so we can see exactly which route
+// fires (new vs update vs motion) and with what payload. Remove once resolved.
+const LOG_PATH =
+ "/Users/barbinbrad/Code/carbon-claude-confident-maxwell-dy4fvr/.ai/scratch/e2e/assembly-step-debug.jsonl";
+
+export function logAssemblyStep(
+ event: string,
+ payload: Record<string, unknown>
+) {
+ try {
+ appendFileSync(
+ LOG_PATH,
+ `${JSON.stringify({ at: new Date().toISOString(), event, ...payload })}\n`
+ );
+ } catch {
+ // best-effort; never break the request
+ }
+}
+
+/** Read a request's form data and return both the entries (for logging) and a
+ * re-usable FormData clone the validator can consume. */
+export async function readAndLogFormData(request: Request, event: string) {
+ const formData = await request.formData();
+ const entries: Record<string, string> = {};
+ for (const [key, value] of formData.entries()) {
+ entries[key] =
+ typeof value === "string"
+ ? value.length > 300
+ ? `${value.slice(0, 300)}…`
+ : value
+ : "[file]";
+ }
+ logAssemblyStep(event, { url: request.url, entries });
+ return formData;
+}
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 85a3c4538d..0d9a7724a5 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1,4 +1,5 @@
import type { Database } from "@carbon/database";
+import { textToTiptap } from "@carbon/utils";
import { z } from "zod";
import { zfd } from "zod-form-data";
import {
@@ -74,6 +75,28 @@ export function isJobLocked(status: string | null | undefined): boolean {
);
}
+/**
+ * A Queued assemblyPlanJob older than this never got picked up by the worker
+ * (pickup normally takes seconds) — treat it as dead rather than blocking the
+ * UI and re-runs forever. Processing rows are alive regardless of age: large
+ * models legitimately plan for many minutes, and the worker's onFailure flips
+ * them to Failed.
+ */
+const ASSEMBLY_PLAN_QUEUED_STALE_MS = 2 * 60 * 1000;
+
+/** Whether a motion-planning run is live (drives badges, polling, re-run guards). */
+export function isAssemblyPlanRunning(
+ job: { status: string; createdAt: string } | null | undefined
+): boolean {
+ if (!job) return false;
+ if (job.status === "Processing") return true;
+ return (
+ job.status === "Queued" &&
+ Date.now() - new Date(job.createdAt).getTime() <
+ ASSEMBLY_PLAN_QUEUED_STALE_MS
+ );
+}
+
export const jobOperationStatus = [
"Todo",
"Ready",
@@ -1027,6 +1050,360 @@ export const demandProjectionValidator = z.object({
)
});
+// --- Assembly Instructions ---------------------------------------------
+
+export const assemblyInstructionStatuses = [
+ "Draft",
+ "Published",
+ "Archived"
+] as const;
+
+export const planConfidences = ["high", "low", "manual"] as const;
+
+export const assemblyStepStatuses = ["Todo", "Review", "Done"] as const;
+
+export const assemblyRequirementTypes = [
+ "Tool",
+ "Fixture",
+ "Consumable",
+ "Note",
+ "Media"
+] as const;
+
+export const assemblyNoteSeverities = ["Info", "Caution", "Warning"] as const;
+
+const vector3 = z.tuple([z.number(), z.number(), z.number()]);
+const quaternion = z.tuple([z.number(), z.number(), z.number(), z.number()]);
+
+/**
+ * Insertion motion of a step's parts. See
+ * docs/specs/animated-work-instructions-contracts.md §4.
+ */
+export const motionSchema = z.discriminatedUnion("type", [
+ z.object({
+ type: z.literal("linear"),
+ direction: vector3,
+ distance: z.number().positive()
+ }),
+ z.object({
+ type: z.literal("L"),
+ // 2+ segments: the tier-3 escape planner emits up to 3 (e.g. slide out
+ // of a blind slot, lift, exit); the viewer interpolates any count
+ segments: z
+ .array(
+ z.object({
+ direction: vector3,
+ distance: z.number().positive()
+ })
+ )
+ .min(2)
+ }),
+ z.object({
+ type: z.literal("helix"),
+ axis: vector3,
+ origin: vector3,
+ pitch: z.number().positive(),
+ turns: z.number().positive(),
+ approach: z.number().nonnegative()
+ }),
+ z.object({
+ type: z.literal("path"),
+ keyframes: z
+ .array(
+ z.object({
+ t: z.number().min(0).max(1),
+ position: vector3,
+ quaternion
+ })
+ )
+ .min(2)
+ }),
+ z.object({ type: z.literal("none") })
+]);
+
+export const cameraSchema = z.object({
+ position: vector3,
+ target: vector3,
+ fov: z.number().positive()
+});
+
+export const fastenerSchema = z.object({
+ spec: z.string().optional(),
+ count: z.number().int().positive().optional(),
+ torqueNm: z.number().positive().optional(),
+ tool: z.string().optional()
+});
+
+/**
+ * Planner flags persisted on assemblyInstructionStep.warnings (jsonb).
+ * `flagged` marks steps whose parts have no proven collision-free path —
+ * the viewer fades them in at the seated pose instead of animating a
+ * fabricated motion. `blockedBy` records the obstructing nodeIds from
+ * plan.json so the editor can name the blockers.
+ */
+export const stepPlanWarningsSchema = z.object({
+ flagged: z.boolean().optional(),
+ blockedBy: z.array(z.string()).optional()
+});
+
+const jsonField = <T extends z.ZodTypeAny>(schema: T) =>
+ z.preprocess((raw) => {
+ if (typeof raw !== "string") return raw;
+ if (raw.trim() === "") return undefined;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+ }, schema);
+
+export const assemblyInstructionValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ modelUploadId: z.string().min(1, { message: "Model is required" }),
+ itemId: zfd.text(z.string().optional())
+});
+
+export type AssemblyModelState =
+ | "converted" // GLB + graph artifacts exist — ready for the viewer
+ | "processing" // conversion job is queued or running
+ | "failed" // last conversion failed — retriable
+ | "convertible" // STEP file present but never converted (lazy conversion)
+ | "none"; // no model, or a format the geometry service can't convert
+
+export function getAssemblyModelState(
+ model: {
+ modelPath: string | null;
+ processingStatus: Database["public"]["Enums"]["modelProcessingStatus"];
+ glbPath: string | null;
+ graphPath: string | null;
+ } | null
+): AssemblyModelState {
+ if (!model) return "none";
+ if (
+ model.processingStatus === "Success" &&
+ model.glbPath &&
+ model.graphPath
+ ) {
+ return "converted";
+ }
+ const isStep = [".step", ".stp"].some((ext) =>
+ (model.modelPath ?? "").toLowerCase().endsWith(ext)
+ );
+ if (!isStep) return "none";
+ if (
+ model.processingStatus === "Queued" ||
+ model.processingStatus === "Processing"
+ ) {
+ return "processing";
+ }
+ if (model.processingStatus === "Failed") return "failed";
+ return "convertible";
+}
+
+/**
+ * Creating an instruction starts from a made item; the instruction name and
+ * model are derived server-side (the name from the item, the model from the
+ * item's CAD files, converted lazily if needed). An explicit modelUploadId
+ * (e.g. from the part details page) takes precedence.
+ */
+export const assemblyInstructionFromItemValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ modelUploadId: zfd.text(z.string().optional())
+});
+
+export const assemblyInstructionStatusValidator = z.object({
+ status: z.enum(assemblyInstructionStatuses)
+});
+
+/**
+ * Optional tiptap-doc transform: same coercion as the shared
+ * operationStepValidator description, but optional because "Add Step" posts
+ * only assemblyInstructionId + motion. Returns `any` for the same reason —
+ * the doc is consumed both as a DB Json value and as editor JSONContent.
+ */
+const optionalTiptapDescription = zfd
+ .text(z.string().optional())
+ .transform((val): any => {
+ if (val === undefined || val === "") return undefined;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(val);
+ } catch {
+ parsed = val;
+ }
+ // Always store a tiptap doc object, never a scalar string (jsonb scalar
+ // strings break method copies) and never silently drop content to {}.
+ if (typeof parsed === "string") return textToTiptap(parsed);
+ if (parsed && typeof parsed === "object") return parsed;
+ return textToTiptap(String(val));
+ });
+
+export const assemblyInstructionStepValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ assemblyInstructionId: z.string().min(1),
+ title: zfd.text(z.string().optional()),
+ // Typed-step fields mirror jobOperationStep so steps can eventually be
+ // copied into job operations
+ type: zfd.text(z.enum(procedureStepType).optional()),
+ description: optionalTiptapDescription,
+ required: zfd.checkbox(),
+ unitOfMeasureCode: zfd.text(z.string().optional()),
+ minValue: zfd.numeric(z.number().min(0).optional()),
+ maxValue: zfd.numeric(z.number().min(0).optional()),
+ listValues: z.array(z.string()).optional(),
+ componentNodeIds: jsonField(z.array(z.string()).optional()),
+ motion: jsonField(motionSchema.optional()),
+ camera: jsonField(cameraSchema.nullable().optional()),
+ fastener: jsonField(fastenerSchema.nullable().optional()),
+ durationSeconds: zfd.numeric(z.number().positive().optional())
+ })
+ .superRefine((data, ctx) => {
+ if (data.type === "Measurement" && !data.unitOfMeasureCode) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["unitOfMeasureCode"],
+ message: "Unit of measure is required"
+ });
+ }
+ if (
+ data.type === "List" &&
+ !(
+ Array.isArray(data.listValues) &&
+ data.listValues.length > 0 &&
+ data.listValues.every((option) => option.trim() !== "")
+ )
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["listValues"],
+ message: "List options are required"
+ });
+ }
+ if (
+ data.minValue != null &&
+ data.maxValue != null &&
+ data.maxValue < data.minValue
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["maxValue"],
+ message: "Maximum value must be greater than or equal to minimum value"
+ });
+ }
+ });
+
+/**
+ * Partial update for a step's viewer-authored motion path and/or camera pose,
+ * saved directly from the 3D editor (drag autosave, "Set view" button) without
+ * round-tripping the whole step form. `camera: null` clears it (auto-frame).
+ */
+export const assemblyInstructionStepMotionValidator = z.object({
+ motion: jsonField(motionSchema.optional()),
+ camera: jsonField(cameraSchema.nullable().optional())
+});
+
+/**
+ * Partial update for a step's assigned components, saved directly from the
+ * Details panel's Add/remove controls without round-tripping the whole step
+ * form. An empty array is valid — a process-only step with no components.
+ */
+export const assemblyInstructionStepComponentsValidator = z.object({
+ componentNodeIds: jsonField(z.array(z.string()))
+});
+
+export const assemblyInstructionStepStatusValidator = z.object({
+ status: z.enum(assemblyStepStatuses)
+});
+
+export const assemblyInstructionStepOrderValidator = z.object({
+ updates: z
+ .array(
+ z.object({
+ id: z.string().min(1),
+ sortOrder: z.number()
+ })
+ )
+ .min(1)
+});
+
+/**
+ * Bill-of-material parts consumed at a step. Stores itemId (not a
+ * methodMaterial FK) so associations survive make-method re-versioning; the
+ * UI picker is limited to items on the instruction item's make-method BOM.
+ */
+export const assemblyStepMaterialValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ stepId: z.string().min(1),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ quantity: zfd.numeric(z.number().min(0).optional()),
+ sortOrder: zfd.numeric(z.number().min(0).optional())
+});
+
+export const assemblyStepRequirementValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ stepId: z.string().min(1),
+ type: z.enum(assemblyRequirementTypes),
+ itemId: zfd.text(z.string().optional()),
+ name: zfd.text(z.string().optional()),
+ text: zfd.text(z.string().optional()),
+ severity: zfd.text(z.enum(assemblyNoteSeverities).optional()),
+ filePath: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(z.number().int().positive().optional())
+ })
+ .superRefine((data, ctx) => {
+ if (data.type === "Note" && !data.text?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["text"],
+ message: "Note text is required"
+ });
+ }
+ if (data.type === "Media" && !data.filePath?.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["filePath"],
+ message: "A file is required"
+ });
+ }
+ if (
+ ["Tool", "Fixture", "Consumable"].includes(data.type) &&
+ !data.itemId?.trim() &&
+ !data.name?.trim()
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["name"],
+ message: "Pick a catalog item or enter a name"
+ });
+ }
+ });
+
+export const assemblyStandardNoteValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ content: z.string().min(1, { message: "Content is required" }),
+ severity: z.enum(assemblyNoteSeverities)
+});
+
+// An assembly unit: model leaf nodes the planner treats as one rigid body — a
+// user override on the automatic BOM-driven derivation. Scoped to the model
+// upload so it survives instruction delete/recreate (like component mappings).
+export const assemblyUnitValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ modelUploadId: z.string().min(1),
+ name: z.string().min(1, { message: "Name is required" }),
+ componentNodeIds: jsonField(z.array(z.string()).min(1)),
+ itemId: zfd.text(z.string().optional())
+});
+
+export type Motion = z.infer<typeof motionSchema>;
+export type CameraPose = z.infer<typeof cameraSchema>;
+export type Fastener = z.infer<typeof fastenerSchema>;
+
// Must match the demand window in get_job_quantity_on_hand and the scheduling
// sequence.
export const ACTIVE_JOB_STATUSES: Database["public"]["Enums"]["jobStatus"][] = [
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index 89ff3069a2..a6e5552d1f 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -1,4 +1,17 @@
import { trigger } from "@carbon/jobs";
+import { isInternalEmail } from "@carbon/utils";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+/**
+ * Assemblies (animated work instructions) are internal-only while the module
+ * matures. Mirrors the backups gate in settings.
+ */
+export function requireAssembliesInternal(email: string | null) {
+ if (!isInternalEmail(email)) {
+ throw redirect(path.to.production);
+ }
+}
/**
* Triggers a job scheduling task via inngest.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index e8757c707f..32fc0f0552 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,7 +1,22 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
+import { nameSimilarity, tiptapToText } from "@carbon/utils";
+import type {
+ AssemblyGraph,
+ AssemblyGraphIndex,
+ AssemblyPlan,
+ AssemblyStep
+} from "@carbon/viewer";
+import {
+ buildAssemblyStepGroups,
+ CURRENT_PLAN_VERSION,
+ computeStepCameras,
+ groupComponentNodeIds,
+ indexAssemblyGraph
+} from "@carbon/viewer";
import { parseDate } from "@internationalized/date";
import type { FileObject, StorageError } from "@supabase/storage-js";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
@@ -19,6 +34,10 @@ import type {
operationToolValidator
} from "../shared";
import type {
+ assemblyInstructionStatuses,
+ assemblyNoteSeverities,
+ assemblyRequirementTypes,
+ assemblyStepStatuses,
deadlineTypes,
failureModeValidator,
jobMaterialValidator,
@@ -42,11 +61,17 @@ import type {
} from "./production.models";
import {
ACTIVE_JOB_STATUSES,
+ cameraSchema,
+ fastenerSchema,
+ getAssemblyModelState,
isJobOrderStatusHidden,
JOB_SUPPLY_STATUS_PRIORITY,
- PO_STATUS_PRIORITY
+ motionSchema,
+ PO_STATUS_PRIORITY,
+ stepPlanWarningsSchema
} from "./production.models";
import type {
+ AssemblyInstructionStepRow,
ItemOrderStatus,
ItemShortfall,
Job,
@@ -3777,6 +3802,1544 @@ export async function triggerJobSchedule(
return { success: true };
}
+// --- Assembly Instructions ---------------------------------------------
+
+export async function getAssemblyInstruction(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("assemblyInstruction")
+ .select(
+ "*, modelUpload(id, name, modelPath, glbPath, graphPath, componentCount, processingStatus, processingError)"
+ )
+ .eq("id", id)
+ .single();
+}
+
+export async function getAssemblyInstructions(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ search?: string;
+ status?: (typeof assemblyInstructionStatuses)[number];
+ itemId?: string;
+ limit?: number;
+ offset?: number;
+ }
+) {
+ let query = client
+ .from("assemblyInstruction")
+ .select("*, modelUpload(id, name, componentCount, processingStatus)", {
+ count: "exact"
+ })
+ .eq("companyId", args.companyId);
+
+ if (args.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+ if (args.status) {
+ query = query.eq("status", args.status);
+ }
+ if (args.itemId) {
+ query = query.eq("itemId", args.itemId);
+ }
+ if (args.limit) {
+ query = query.limit(args.limit);
+ }
+ if (args.offset) {
+ query = query.range(args.offset, args.offset + (args.limit ?? 25) - 1);
+ }
+
+ return query.order("updatedAt", { ascending: false, nullsFirst: false });
+}
+
+/**
+ * Resolves a made item's CAD model for assembly instructions. Items link to
+ * their model via item.modelUploadId. Conversion to viewer artifacts (GLB +
+ * graph) is lazy — `modelState` tells the caller whether the model is ready,
+ * convertible on demand, or unusable.
+ */
+export async function getModelForItem(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+) {
+ const item = await client
+ .from("item")
+ .select("id, name, modelUploadId")
+ .eq("id", itemId)
+ .eq("companyId", companyId)
+ .single();
+ if (item.error) {
+ return { item: null, model: null, modelState: "none" as const };
+ }
+
+ if (!item.data.modelUploadId) {
+ return { item: item.data, model: null, modelState: "none" as const };
+ }
+
+ const model = await client
+ .from("modelUpload")
+ .select(
+ "id, name, componentCount, processingStatus, processingError, glbPath, graphPath, modelPath"
+ )
+ .eq("id", item.data.modelUploadId)
+ .maybeSingle();
+
+ return {
+ item: item.data,
+ model: model.data ?? null,
+ modelState: getAssemblyModelState(model.data ?? null)
+ };
+}
+
+export async function getAssemblyInstructionSteps(
+ client: SupabaseClient<Database>,
+ assemblyInstructionId: string
+) {
+ return client
+ .from("assemblyInstructionStep")
+ .select("*")
+ .eq("assemblyInstructionId", assemblyInstructionId)
+ .order("sortOrder", { ascending: true });
+}
+
+export async function upsertAssemblyInstruction(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ name: string;
+ modelUploadId: string;
+ itemId?: string | null;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ if (data.id) {
+ return client
+ .from("assemblyInstruction")
+ .update({
+ name: data.name,
+ itemId: data.itemId ?? null,
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyInstruction")
+ .insert({
+ name: data.name,
+ modelUploadId: data.modelUploadId,
+ itemId: data.itemId ?? null,
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+export async function updateAssemblyInstructionStatus(
+ client: SupabaseClient<Database>,
+ id: string,
+ data: {
+ status: (typeof assemblyInstructionStatuses)[number];
+ updatedBy: string;
+ }
+) {
+ // Each publish bumps the version ("Edit N" in the header)
+ let version: number | undefined;
+ if (data.status === "Published") {
+ const current = await client
+ .from("assemblyInstruction")
+ .select("version")
+ .eq("id", id)
+ .single();
+ version = (current.data?.version ?? 0) + 1;
+ }
+
+ return client
+ .from("assemblyInstruction")
+ .update({
+ status: data.status,
+ publishedAt:
+ data.status === "Published" ? new Date().toISOString() : undefined,
+ ...(version !== undefined ? { version } : {}),
+ updatedBy: data.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", id)
+ .select("id")
+ .single();
+}
+
+export async function deleteAssemblyInstruction(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ // Remember which model this instruction was authored against before we drop
+ // it — the cached motion plan is keyed to the modelUpload, not the
+ // instruction, so it survives delete/recreate and would otherwise resurrect a
+ // stale plan for a fresh instruction (defeating any planner improvement).
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("modelUploadId")
+ .eq("id", id)
+ .maybeSingle();
+
+ const deletion = await client
+ .from("assemblyInstruction")
+ .delete()
+ .eq("id", id);
+ if (deletion.error) return deletion;
+
+ const modelUploadId = instruction.data?.modelUploadId;
+ if (modelUploadId) {
+ await invalidateAssemblyPlanCache(client, modelUploadId);
+ }
+
+ return deletion;
+}
+
+/**
+ * Drops the cached motion plan for a model so the next instruction re-plans from
+ * scratch (with the current algorithm). Leaves the expensive conversion output
+ * (glb/graph on the modelUpload) intact — conversion isn't what a planner change
+ * affects. No-op while another instruction still authors against the same model
+ * (one item → one modelUpload, potentially several instructions).
+ */
+async function invalidateAssemblyPlanCache(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+) {
+ const others = await client
+ .from("assemblyInstruction")
+ .select("id")
+ .eq("modelUploadId", modelUploadId)
+ .limit(1);
+ if (others.error || (others.data?.length ?? 0) > 0) return;
+
+ const planJobs = await client
+ .from("assemblyPlanJob")
+ .select("planPath")
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "plan");
+
+ const planPaths = (planJobs.data ?? [])
+ .map((job) => job.planPath)
+ .filter((planPath): planPath is string => Boolean(planPath));
+ if (planPaths.length > 0) {
+ // Best-effort artifact cleanup; deleting the rows below is what actually
+ // invalidates the cache (getLatestAssemblyPlan then finds nothing).
+ await client.storage.from("private").remove(planPaths);
+ }
+
+ await client
+ .from("assemblyPlanJob")
+ .delete()
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "plan");
+}
+
+export async function upsertAssemblyInstructionStep(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ assemblyInstructionId: string;
+ title?: string | null;
+ type?: Database["public"]["Enums"]["procedureStepType"];
+ description?: Json;
+ required?: boolean;
+ unitOfMeasureCode?: string | null;
+ minValue?: number | null;
+ maxValue?: number | null;
+ listValues?: string[] | null;
+ componentNodeIds?: string[];
+ motion?: z.infer<typeof motionSchema>;
+ camera?: z.infer<typeof cameraSchema> | null;
+ fastener?: z.infer<typeof fastenerSchema> | null;
+ durationSeconds?: number | null;
+ sortOrder?: number;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ // instructionText is a derived plain-text snapshot of the tiptap
+ // description, consumed by the viewer overlay, MES playback, and search
+ const derivedInstructionText =
+ data.description !== undefined
+ ? {
+ instructionText: tiptapToText(data.description as JSONContent) || null
+ }
+ : {};
+
+ // When a type is posted, clear the value fields that don't apply to it so
+ // switching type never leaves stale constraints behind
+ const typedFields = data.type
+ ? {
+ type: data.type,
+ unitOfMeasureCode:
+ data.type === "Measurement" ? (data.unitOfMeasureCode ?? null) : null,
+ minValue: data.type === "Measurement" ? (data.minValue ?? null) : null,
+ maxValue: data.type === "Measurement" ? (data.maxValue ?? null) : null,
+ listValues: data.type === "List" ? (data.listValues ?? null) : null
+ }
+ : {};
+
+ if (data.id) {
+ return client
+ .from("assemblyInstructionStep")
+ .update({
+ title: data.title ?? null,
+ ...typedFields,
+ ...(data.description !== undefined
+ ? { description: data.description }
+ : {}),
+ ...derivedInstructionText,
+ ...(data.required !== undefined ? { required: data.required } : {}),
+ ...(data.componentNodeIds
+ ? { componentNodeIds: data.componentNodeIds }
+ : {}),
+ ...(data.motion ? { motion: data.motion as Json } : {}),
+ ...(data.camera !== undefined
+ ? { camera: data.camera as Json | null }
+ : {}),
+ ...(data.fastener !== undefined
+ ? { fastener: data.fastener as Json | null }
+ : {}),
+ ...(data.durationSeconds !== undefined
+ ? { durationSeconds: data.durationSeconds }
+ : {}),
+ ...(data.sortOrder !== undefined ? { sortOrder: data.sortOrder } : {}),
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyInstructionStep")
+ .insert({
+ assemblyInstructionId: data.assemblyInstructionId,
+ title: data.title ?? null,
+ type: data.type ?? "Task",
+ description: data.description ?? {},
+ instructionText:
+ data.description !== undefined
+ ? tiptapToText(data.description as JSONContent) || null
+ : null,
+ required: data.required ?? false,
+ unitOfMeasureCode:
+ data.type === "Measurement" ? (data.unitOfMeasureCode ?? null) : null,
+ minValue: data.type === "Measurement" ? (data.minValue ?? null) : null,
+ maxValue: data.type === "Measurement" ? (data.maxValue ?? null) : null,
+ listValues: data.type === "List" ? (data.listValues ?? null) : null,
+ componentNodeIds: data.componentNodeIds ?? [],
+ motion: (data.motion ?? { type: "none" }) as Json,
+ camera: (data.camera ?? null) as Json | null,
+ fastener: (data.fastener ?? null) as Json | null,
+ durationSeconds: data.durationSeconds ?? null,
+ sortOrder: data.sortOrder ?? (await getNextStepSortOrder(client, data)),
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+/**
+ * Partial update of a step's viewer-authored motion path and/or camera pose.
+ * Kept separate from `upsertAssemblyInstructionStep` (which always rewrites
+ * `title` and the typed-step fields) so the 3D editor can autosave a drag or a
+ * "Set view" click without touching the rest of the step. `camera: null` clears
+ * the pose (return to auto-framing); omitting a field leaves it untouched.
+ */
+export async function updateAssemblyStepMotion(
+ client: SupabaseClient<Database>,
+ data: {
+ id: string;
+ motion?: z.infer<typeof motionSchema>;
+ camera?: z.infer<typeof cameraSchema> | null;
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("assemblyInstructionStep")
+ .update({
+ ...(data.motion !== undefined ? { motion: data.motion as Json } : {}),
+ ...(data.camera !== undefined
+ ? { camera: data.camera as Json | null }
+ : {}),
+ updatedBy: data.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+}
+
+// Autosave target for the Details panel's Add/remove component controls: patches
+// only the step's assigned components, leaving the title/typed fields and motion
+// untouched.
+export async function updateAssemblyStepComponents(
+ client: SupabaseClient<Database>,
+ data: {
+ id: string;
+ componentNodeIds: string[];
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("assemblyInstructionStep")
+ .update({
+ componentNodeIds: data.componentNodeIds,
+ updatedBy: data.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+}
+
+async function getNextStepSortOrder(
+ client: SupabaseClient<Database>,
+ data: { assemblyInstructionId: string }
+) {
+ const lastStep = await client
+ .from("assemblyInstructionStep")
+ .select("sortOrder")
+ .eq("assemblyInstructionId", data.assemblyInstructionId)
+ .order("sortOrder", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ return (lastStep.data?.sortOrder ?? 0) + 1;
+}
+
+export async function updateAssemblyInstructionStepStatus(
+ client: SupabaseClient<Database>,
+ id: string,
+ data: {
+ status: (typeof assemblyStepStatuses)[number];
+ updatedBy: string;
+ }
+) {
+ return client
+ .from("assemblyInstructionStep")
+ .update({
+ status: data.status,
+ updatedBy: data.updatedBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", id)
+ .select("id")
+ .single();
+}
+
+export async function updateAssemblyInstructionStepOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("assemblyInstructionStep")
+ .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
+export async function deleteAssemblyInstructionStep(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyInstructionStep").delete().eq("id", id);
+}
+
+export async function getAssemblyInstructionStepRequirements(
+ client: SupabaseClient<Database>,
+ stepIds: string[]
+) {
+ if (stepIds.length === 0) {
+ return { data: [], error: null };
+ }
+ return client
+ .from("assemblyInstructionStepRequirement")
+ .select("*, item(id, name, readableIdWithRevision)")
+ .in("stepId", stepIds)
+ .order("sortOrder", { ascending: true });
+}
+
+export async function upsertAssemblyInstructionStepRequirement(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ stepId: string;
+ type: (typeof assemblyRequirementTypes)[number];
+ itemId?: string | null;
+ name?: string | null;
+ text?: string | null;
+ severity?: (typeof assemblyNoteSeverities)[number] | null;
+ filePath?: string | null;
+ quantity?: number;
+ sortOrder?: number;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ // Snapshot the catalog item name so display never needs a join and
+ // survives item deletion
+ let name = data.name ?? null;
+ if (!name && data.itemId) {
+ const item = await client
+ .from("item")
+ .select("name")
+ .eq("id", data.itemId)
+ .single();
+ name = item.data?.name ?? null;
+ }
+
+ if (data.id) {
+ return client
+ .from("assemblyInstructionStepRequirement")
+ .update({
+ itemId: data.itemId ?? null,
+ name,
+ text: data.text ?? null,
+ severity: data.severity ?? null,
+ ...(data.filePath !== undefined ? { filePath: data.filePath } : {}),
+ ...(data.quantity !== undefined ? { quantity: data.quantity } : {}),
+ ...(data.sortOrder !== undefined ? { sortOrder: data.sortOrder } : {}),
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyInstructionStepRequirement")
+ .insert({
+ stepId: data.stepId,
+ type: data.type,
+ itemId: data.itemId ?? null,
+ name,
+ text: data.text ?? null,
+ severity: data.severity ?? null,
+ filePath: data.filePath ?? null,
+ quantity: data.quantity ?? 1,
+ sortOrder:
+ data.sortOrder ?? (await getNextRequirementSortOrder(client, data)),
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+async function getNextRequirementSortOrder(
+ client: SupabaseClient<Database>,
+ data: { stepId: string; type: (typeof assemblyRequirementTypes)[number] }
+) {
+ const last = await client
+ .from("assemblyInstructionStepRequirement")
+ .select("sortOrder")
+ .eq("stepId", data.stepId)
+ .eq("type", data.type)
+ .order("sortOrder", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ return (last.data?.sortOrder ?? 0) + 1;
+}
+
+export async function getAssemblyInstructionStepRequirement(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("assemblyInstructionStepRequirement")
+ .select("*")
+ .eq("id", id)
+ .single();
+}
+
+export async function updateAssemblyInstructionStepRequirementOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("assemblyInstructionStepRequirement")
+ .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
+export async function deleteAssemblyInstructionStepRequirement(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client
+ .from("assemblyInstructionStepRequirement")
+ .delete()
+ .eq("id", id);
+}
+
+export async function getAssemblyInstructionStepMaterials(
+ client: SupabaseClient<Database>,
+ stepIds: string[]
+) {
+ if (stepIds.length === 0) {
+ return { data: [], error: null };
+ }
+ return client
+ .from("assemblyInstructionStepMaterial")
+ .select("*, item(id, name, readableIdWithRevision)")
+ .in("stepId", stepIds)
+ .order("sortOrder", { ascending: true });
+}
+
+export async function upsertAssemblyInstructionStepMaterial(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ stepId: string;
+ itemId: string;
+ quantity?: number | null;
+ sortOrder?: number;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ if (data.id) {
+ return client
+ .from("assemblyInstructionStepMaterial")
+ .update({
+ itemId: data.itemId,
+ quantity: data.quantity ?? null,
+ ...(data.sortOrder !== undefined ? { sortOrder: data.sortOrder } : {}),
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyInstructionStepMaterial")
+ .insert({
+ stepId: data.stepId,
+ itemId: data.itemId,
+ quantity: data.quantity ?? null,
+ sortOrder:
+ data.sortOrder ?? (await getNextStepMaterialSortOrder(client, data)),
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+async function getNextStepMaterialSortOrder(
+ client: SupabaseClient<Database>,
+ data: { stepId: string }
+) {
+ const last = await client
+ .from("assemblyInstructionStepMaterial")
+ .select("sortOrder")
+ .eq("stepId", data.stepId)
+ .order("sortOrder", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ return (last.data?.sortOrder ?? 0) + 1;
+}
+
+export async function updateAssemblyInstructionStepMaterialOrder(
+ db: Kysely<KyselyDatabase>,
+ updates: { id: string; sortOrder: number; updatedBy: string }[]
+) {
+ return db.transaction().execute(async (trx) => {
+ for (const { id, sortOrder, updatedBy } of updates) {
+ await trx
+ .updateTable("assemblyInstructionStepMaterial")
+ .set({ sortOrder, updatedBy, updatedAt: new Date().toISOString() })
+ .where("id", "=", id)
+ .execute();
+ }
+ });
+}
+
+export async function deleteAssemblyInstructionStepMaterial(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyInstructionStepMaterial").delete().eq("id", id);
+}
+
+type AssemblyStepMaterialSeed = {
+ stepId: string;
+ itemId: string;
+ quantity: number;
+ sortOrder: number;
+};
+
+/**
+ * The step-material rows implied by each step's components: groups a step's
+ * componentNodeIds by geometry, resolves each group through the model's
+ * component→BOM mappings, and returns rows for matches the step doesn't
+ * already have. Quantity is the component's instance count within the step.
+ */
+function deriveAssemblyStepMaterialSeeds(args: {
+ steps: { id: string; componentNodeIds: string[] | null }[];
+ graphIndex: AssemblyGraphIndex;
+ itemIdByGeometryHash: Map<string, string>;
+ /** stepId → already-linked itemIds; never re-added, so manual edits win */
+ existingItemIds?: Map<string, Set<string>>;
+ /** stepId → sortOrder to start appending at */
+ nextSortOrder?: Map<string, number>;
+ /** Restrict to component groups containing one of these instances */
+ onlyComponentNodeIds?: Set<string>;
+}): AssemblyStepMaterialSeed[] {
+ const only = args.onlyComponentNodeIds;
+ const seeds: AssemblyStepMaterialSeed[] = [];
+ for (const step of args.steps) {
+ const groups = groupComponentNodeIds(
+ step.componentNodeIds ?? [],
+ args.graphIndex
+ );
+ const used = args.existingItemIds?.get(step.id);
+ // Two geometries can map to the same BOM item — aggregate their counts
+ const quantities = new Map<string, number>();
+ for (const group of groups) {
+ if (only && !group.nodeIds.some((nodeId) => only.has(nodeId))) {
+ continue;
+ }
+ const itemId = args.itemIdByGeometryHash.get(group.key);
+ if (!itemId || used?.has(itemId)) continue;
+ quantities.set(itemId, (quantities.get(itemId) ?? 0) + group.count);
+ }
+ let sortOrder = args.nextSortOrder?.get(step.id) ?? 1;
+ for (const [itemId, quantity] of quantities) {
+ seeds.push({ stepId: step.id, itemId, quantity, sortOrder: sortOrder++ });
+ }
+ }
+ return seeds;
+}
+
+function insertAssemblyStepMaterialSeeds(
+ client: SupabaseClient<Database>,
+ seeds: AssemblyStepMaterialSeed[],
+ args: { companyId: string; userId: string }
+) {
+ // ignoreDuplicates makes concurrent syncs race-safe on (stepId, itemId)
+ return client.from("assemblyInstructionStepMaterial").upsert(
+ seeds.map((seed) => ({
+ ...seed,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })),
+ { onConflict: "stepId,itemId", ignoreDuplicates: true }
+ );
+}
+
+/**
+ * Adds the BOM items matched to each step's components (via
+ * assemblyComponentMapping) as step materials. Additive and best-effort:
+ * existing rows are never updated or removed — manual quantities and
+ * deliberate deletions survive — and failures never block the caller.
+ */
+export async function syncAssemblyStepMaterialsFromMappings(
+ client: SupabaseClient<Database>,
+ args: {
+ assemblyInstructionId: string;
+ companyId: string;
+ userId: string;
+ /** Limit to these steps (default: every step of the instruction) */
+ stepIds?: string[];
+ /** Limit to these mappings (e.g. one just created) */
+ geometryHashes?: string[];
+ /** Limit to component groups containing one of these instances */
+ onlyComponentNodeIds?: string[];
+ }
+): Promise<{ created: number }> {
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("id, modelUploadId, modelUpload(graphPath)")
+ .eq("id", args.assemblyInstructionId)
+ .single();
+ const modelUploadId = instruction.data?.modelUploadId;
+ const graphPath = instruction.data?.modelUpload?.graphPath;
+ if (instruction.error || !modelUploadId || !graphPath) {
+ return { created: 0 };
+ }
+
+ const mappings = await getAssemblyComponentMappings(client, modelUploadId);
+ const hashFilter = args.geometryHashes ? new Set(args.geometryHashes) : null;
+ const itemIdByGeometryHash = new Map<string, string>();
+ for (const mapping of mappings.data ?? []) {
+ if (hashFilter && !hashFilter.has(mapping.geometryHash)) continue;
+ itemIdByGeometryHash.set(mapping.geometryHash, mapping.itemId);
+ }
+ if (itemIdByGeometryHash.size === 0) return { created: 0 };
+
+ let stepsQuery = client
+ .from("assemblyInstructionStep")
+ .select("id, componentNodeIds")
+ .eq("assemblyInstructionId", args.assemblyInstructionId);
+ if (args.stepIds?.length) {
+ stepsQuery = stepsQuery.in("id", args.stepIds);
+ }
+ const steps = await stepsQuery;
+ if (!steps.data?.length) return { created: 0 };
+
+ const graphFile = await client.storage.from("private").download(graphPath);
+ if (graphFile.error || !graphFile.data) return { created: 0 };
+ let graphIndex: AssemblyGraphIndex;
+ try {
+ graphIndex = indexAssemblyGraph(
+ JSON.parse(await graphFile.data.text()) as AssemblyGraph
+ );
+ } catch {
+ return { created: 0 };
+ }
+
+ const existing = await client
+ .from("assemblyInstructionStepMaterial")
+ .select("stepId, itemId, sortOrder")
+ .in(
+ "stepId",
+ steps.data.map((step) => step.id)
+ );
+ const existingItemIds = new Map<string, Set<string>>();
+ const nextSortOrder = new Map<string, number>();
+ for (const row of existing.data ?? []) {
+ const itemIds = existingItemIds.get(row.stepId) ?? new Set<string>();
+ itemIds.add(row.itemId);
+ existingItemIds.set(row.stepId, itemIds);
+ nextSortOrder.set(
+ row.stepId,
+ Math.max(nextSortOrder.get(row.stepId) ?? 1, row.sortOrder + 1)
+ );
+ }
+
+ const seeds = deriveAssemblyStepMaterialSeeds({
+ steps: steps.data,
+ graphIndex,
+ itemIdByGeometryHash,
+ existingItemIds,
+ nextSortOrder,
+ onlyComponentNodeIds: args.onlyComponentNodeIds
+ ? new Set(args.onlyComponentNodeIds)
+ : undefined
+ });
+ if (seeds.length === 0) return { created: 0 };
+
+ const insert = await insertAssemblyStepMaterialSeeds(client, seeds, args);
+ return { created: insert.error ? 0 : seeds.length };
+}
+
+export async function getAssemblyStandardNotes(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("assemblyStandardNote")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("name", { ascending: true });
+}
+
+export async function upsertAssemblyStandardNote(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ name: string;
+ content: string;
+ severity: (typeof assemblyNoteSeverities)[number];
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ if (data.id) {
+ return client
+ .from("assemblyStandardNote")
+ .update({
+ name: data.name,
+ content: data.content,
+ severity: data.severity,
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyStandardNote")
+ .insert({
+ name: data.name,
+ content: data.content,
+ severity: data.severity,
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+export async function deleteAssemblyStandardNote(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyStandardNote").delete().eq("id", id);
+}
+
+export async function getAssemblyUnits(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+) {
+ return client
+ .from("assemblyUnit")
+ .select("*")
+ .eq("modelUploadId", modelUploadId)
+ .order("name");
+}
+
+export async function upsertAssemblyUnit(
+ client: SupabaseClient<Database>,
+ data: {
+ id?: string;
+ modelUploadId: string;
+ name: string;
+ componentNodeIds: string[];
+ itemId?: string | null;
+ companyId: string;
+ createdBy: string;
+ updatedBy?: string;
+ }
+) {
+ if (data.id) {
+ return client
+ .from("assemblyUnit")
+ .update({
+ name: data.name,
+ componentNodeIds: data.componentNodeIds,
+ itemId: data.itemId ?? null,
+ updatedBy: data.updatedBy ?? data.createdBy,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", data.id)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("assemblyUnit")
+ .insert({
+ modelUploadId: data.modelUploadId,
+ name: data.name,
+ componentNodeIds: data.componentNodeIds,
+ itemId: data.itemId ?? null,
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+export async function deleteAssemblyUnit(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyUnit").delete().eq("id", id);
+}
+
+/**
+ * Latest successful motion plan for a model. The editor uses plan.json to
+ * auto-fill step motions and to generate draft step sequences.
+ */
+export async function getLatestAssemblyPlan(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+) {
+ return client
+ .from("assemblyPlanJob")
+ .select("id, planPath, stats, createdAt")
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "plan")
+ .eq("status", "Success")
+ .not("planPath", "is", null)
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+}
+
+/**
+ * Latest plan job in any state — used to tell "planning is running" apart
+ * from "planning failed" and to avoid enqueueing duplicate plan runs.
+ */
+export async function getLatestAssemblyPlanJob(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+) {
+ return client
+ .from("assemblyPlanJob")
+ .select("id, status, error, planPath, createdAt")
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "plan")
+ .order("createdAt", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+}
+
+/**
+ * Pre-creates the Queued plan job row BEFORE the `assembly-plan` event is
+ * sent, so the very next loader read sees a live run (badge, disabled button,
+ * polling). The worker adopts the row via the event's `planJobId` and flips
+ * it to Processing; without this the row only exists after event pickup, and
+ * the post-action revalidation lands in that gap — nothing polls, and the run
+ * (and its finished motions) never surface without a manual reload.
+ */
+export async function createAssemblyPlanJob(
+ client: SupabaseClient<Database>,
+ args: { modelUploadId: string; companyId: string; userId: string }
+) {
+ return client
+ .from("assemblyPlanJob")
+ .insert({
+ modelUploadId: args.modelUploadId,
+ kind: "plan",
+ status: "Queued",
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .select("id")
+ .single();
+}
+
+/** Downloads and parses plan.json for a model's latest successful plan.
+
+ * Plans written by an older planner *version* are treated as ABSENT: the
+ * stored artifact is keyed to the model upload, so without this gate a
+ * format-stale plan could silently resurrect old motions. (Deleting an
+ * instruction now also invalidates the plan for its model — see
+ * invalidateAssemblyPlanCache — but this gate still guards the shared-model
+ * case and same-version format drift.) Absence flows into the existing
+ * no-plan path, which triggers a fresh planner run and auto-generates steps
+ * when it lands.
+ */
+export async function getAssemblyPlanJson(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+): Promise<AssemblyPlan | null> {
+ const job = await getLatestAssemblyPlan(client, modelUploadId);
+ if (!job.data?.planPath) return null;
+
+ const file = await client.storage.from("private").download(job.data.planPath);
+ if (file.error || !file.data) return null;
+
+ try {
+ const plan = JSON.parse(await file.data.text()) as AssemblyPlan;
+ if ((plan.version ?? 1) < CURRENT_PLAN_VERSION) return null;
+ return plan;
+ } catch {
+ return null;
+ }
+}
+
+// --- Model component ↔ engineering BOM mappings --------------------------
+
+/** Mappings from distinct model components (geometry hashes) to BOM items. */
+export async function getAssemblyComponentMappings(
+ client: SupabaseClient<Database>,
+ modelUploadId: string
+) {
+ return client
+ .from("assemblyComponentMapping")
+ .select("*, item(id, name, readableIdWithRevision)")
+ .eq("modelUploadId", modelUploadId);
+}
+
+export async function upsertAssemblyComponentMapping(
+ client: SupabaseClient<Database>,
+ data: {
+ modelUploadId: string;
+ geometryHash: string;
+ itemId: string;
+ confidence?: "high" | "low";
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("assemblyComponentMapping")
+ .upsert(
+ {
+ modelUploadId: data.modelUploadId,
+ geometryHash: data.geometryHash,
+ itemId: data.itemId,
+ confidence: data.confidence ?? "high",
+ companyId: data.companyId,
+ createdBy: data.createdBy,
+ updatedBy: data.createdBy,
+ updatedAt: new Date().toISOString()
+ },
+ { onConflict: "modelUploadId,geometryHash" }
+ )
+ .select("id")
+ .single();
+}
+
+export async function deleteAssemblyComponentMapping(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("assemblyComponentMapping").delete().eq("id", id);
+}
+
+export type FlattenedBomMaterial = {
+ itemId: string;
+ name: string | null;
+ readableIdWithRevision: string | null;
+ /** Total quantity per one parent assembly (multiplied through levels) */
+ quantity: number;
+ methodType: string;
+ depth: number;
+};
+
+/**
+ * The engineering bill of materials for a made item, flattened through its
+ * Make subassemblies (makeMethod → methodMaterial → materialMakeMethodId),
+ * with quantities multiplied per level. Uses the Active make method, or
+ * the first one when none is active.
+ */
+export async function getFlattenedBomMaterials(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+): Promise<FlattenedBomMaterial[]> {
+ const makeMethods = await client
+ .from("makeMethod")
+ .select("id, status")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId);
+ if (makeMethods.error || !makeMethods.data?.length) return [];
+
+ const active =
+ makeMethods.data.find((method) => method.status === "Active") ??
+ makeMethods.data[0];
+ if (!active) return [];
+
+ const results: FlattenedBomMaterial[] = [];
+ const visited = new Set<string>();
+
+ const walk = async (
+ makeMethodId: string,
+ multiplier: number,
+ depth: number
+ ): Promise<void> => {
+ if (depth > 5 || visited.has(makeMethodId)) return;
+ visited.add(makeMethodId);
+
+ const materials = await client
+ .from("methodMaterial")
+ .select(
+ "id, itemId, quantity, methodType, materialMakeMethodId, item(id, name, readableIdWithRevision)"
+ )
+ .eq("makeMethodId", makeMethodId)
+ .order("order", { ascending: true });
+
+ for (const material of materials.data ?? []) {
+ if (!material.itemId) continue;
+ const quantity = (material.quantity ?? 1) * multiplier;
+ results.push({
+ itemId: material.itemId,
+ name: material.item?.name ?? null,
+ readableIdWithRevision: material.item?.readableIdWithRevision ?? null,
+ quantity,
+ methodType: material.methodType,
+ depth
+ });
+ if (material.materialMakeMethodId) {
+ await walk(material.materialMakeMethodId, quantity, depth + 1);
+ }
+ }
+ };
+
+ await walk(active.id, 1, 0);
+ return results;
+}
+
+export type AutoMatchResult = {
+ mapped: number;
+ totalComponents: number;
+ unmatchedBomItems: string[];
+};
+
+/**
+ * Suggests and persists component→BOM mappings for an instruction's model:
+ * strong name matches first (greedy, best score wins), then unique
+ * quantity matches (a component appearing N times matched to the only BOM line
+ * with quantity N) as low-confidence fallbacks. Existing mappings are kept.
+ */
+export async function autoMatchAssemblyComponents(
+ client: SupabaseClient<Database>,
+ args: { assemblyInstructionId: string; companyId: string; userId: string }
+): Promise<AutoMatchResult | { error: string }> {
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("id, itemId, modelUploadId, modelUpload(graphPath)")
+ .eq("id", args.assemblyInstructionId)
+ .single();
+ if (instruction.error || !instruction.data.modelUploadId) {
+ return { error: "This instruction has no model" };
+ }
+ if (!instruction.data.itemId) {
+ return { error: "Link the instruction to an item first" };
+ }
+ const graphPath = instruction.data.modelUpload?.graphPath;
+ if (!graphPath) {
+ return { error: "The model has not been processed" };
+ }
+
+ const graphFile = await client.storage.from("private").download(graphPath);
+ if (graphFile.error || !graphFile.data) {
+ return { error: "Failed to load the model graph" };
+ }
+ let graph: AssemblyGraph;
+ try {
+ graph = JSON.parse(await graphFile.data.text()) as AssemblyGraph;
+ } catch {
+ return { error: "Failed to parse the model graph" };
+ }
+
+ // Distinct parts: hash → { name, count }
+ const componentGroups = new Map<string, { name: string; count: number }>();
+ const visit = (node: AssemblyGraph["root"]) => {
+ if (!node.children.length) {
+ const key = node.geometryHash ?? `name:${node.name}`;
+ const group = componentGroups.get(key);
+ if (group) group.count++;
+ else componentGroups.set(key, { name: node.name, count: 1 });
+ }
+ for (const child of node.children) visit(child);
+ };
+ visit(graph.root);
+
+ const bom = await getFlattenedBomMaterials(
+ client,
+ instruction.data.itemId,
+ args.companyId
+ );
+ if (bom.length === 0) {
+ return { error: "The item has no bill of materials" };
+ }
+
+ const existing = await getAssemblyComponentMappings(
+ client,
+ instruction.data.modelUploadId
+ );
+ const mappedHashes = new Set(
+ (existing.data ?? []).map((mapping) => mapping.geometryHash)
+ );
+ const usedItemIds = new Set(
+ (existing.data ?? []).map((mapping) => mapping.itemId)
+ );
+
+ type Suggestion = {
+ geometryHash: string;
+ itemId: string;
+ score: number;
+ confidence: "high" | "low";
+ };
+ const suggestions: Suggestion[] = [];
+
+ // Name-based candidates, all pairs above threshold, greedy by score
+ for (const [hash, group] of componentGroups) {
+ if (mappedHashes.has(hash)) continue;
+ for (const material of bom) {
+ const score = nameSimilarity(group.name, material.name ?? "");
+ if (score >= 0.45) {
+ suggestions.push({
+ geometryHash: hash,
+ itemId: material.itemId,
+ score,
+ confidence: score >= 0.7 ? "high" : "low"
+ });
+ }
+ }
+ }
+ suggestions.sort((a, b) => b.score - a.score);
+
+ const matchedHashes = new Set<string>(mappedHashes);
+ const matchedItems = new Set<string>(usedItemIds);
+ const accepted: Suggestion[] = [];
+ for (const suggestion of suggestions) {
+ if (matchedHashes.has(suggestion.geometryHash)) continue;
+ if (matchedItems.has(suggestion.itemId)) continue;
+ matchedHashes.add(suggestion.geometryHash);
+ matchedItems.add(suggestion.itemId);
+ accepted.push(suggestion);
+ }
+
+ // Quantity fallback: a still-unmatched part whose instance count equals
+ // exactly one still-unmatched BOM line's quantity
+ for (const [hash, group] of componentGroups) {
+ if (matchedHashes.has(hash)) continue;
+ const candidates = bom.filter(
+ (material) =>
+ !matchedItems.has(material.itemId) &&
+ Math.round(material.quantity) === group.count
+ );
+ const sameCountComponents = [...componentGroups.entries()].filter(
+ ([otherHash, other]) =>
+ !matchedHashes.has(otherHash) && other.count === group.count
+ );
+ const candidate = candidates[0];
+ if (
+ candidates.length === 1 &&
+ sameCountComponents.length === 1 &&
+ candidate
+ ) {
+ matchedHashes.add(hash);
+ matchedItems.add(candidate.itemId);
+ accepted.push({
+ geometryHash: hash,
+ itemId: candidate.itemId,
+ score: 0,
+ confidence: "low"
+ });
+ }
+ }
+
+ for (const suggestion of accepted) {
+ await upsertAssemblyComponentMapping(client, {
+ modelUploadId: instruction.data.modelUploadId,
+ geometryHash: suggestion.geometryHash,
+ itemId: suggestion.itemId,
+ confidence: suggestion.confidence,
+ companyId: args.companyId,
+ createdBy: args.userId
+ });
+ }
+
+ return {
+ mapped: matchedHashes.size,
+ totalComponents: componentGroups.size,
+ unmatchedBomItems: bom
+ .filter((material) => !matchedItems.has(material.itemId))
+ .map(
+ (material) =>
+ material.readableIdWithRevision ?? material.name ?? material.itemId
+ )
+ };
+}
+
+type GenerateStepsResult =
+ | { ok: true; created: number }
+ | {
+ ok: false;
+ reason: "no-model" | "no-plan" | "steps-exist" | "steps-locked" | "error";
+ modelUploadId?: string;
+ message?: string;
+ };
+
+/**
+ * Creates draft steps from the motion plan: walks the planned assembly
+ * sequence, groups consecutive identical parts (same geometry, same motion
+ * shape) into one step, and inserts them in order with status Review. Parts
+ * the planner flagged (blockedBy: no collision-free path exists) are stored
+ * with motion "none" plus a `warnings` payload — the viewer fades them in
+ * rather than animating a fabricated colliding path. The author
+ * validates/edits the drafts instead of authoring motions by hand.
+ */
+export async function generateAssemblyStepsFromPlan(
+ client: SupabaseClient<Database>,
+ args: {
+ assemblyInstructionId: string;
+ companyId: string;
+ userId: string;
+ /**
+ * "regenerate" replaces the existing steps with fresh drafts from the
+ * latest plan — refused while any step is manually authored
+ * (planConfidence "manual") or already Done.
+ */
+ mode?: "generate" | "regenerate";
+ }
+): Promise<GenerateStepsResult> {
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("id, modelUploadId, modelUpload(graphPath)")
+ .eq("id", args.assemblyInstructionId)
+ .single();
+ if (instruction.error || !instruction.data.modelUploadId) {
+ return { ok: false, reason: "no-model" };
+ }
+ const modelUploadId = instruction.data.modelUploadId;
+
+ const existing = await client
+ .from("assemblyInstructionStep")
+ .select("id, planConfidence, status")
+ .eq("assemblyInstructionId", args.assemblyInstructionId);
+ if ((existing.data ?? []).length > 0) {
+ if (args.mode !== "regenerate") {
+ return { ok: false, reason: "steps-exist", modelUploadId };
+ }
+ const locked = (existing.data ?? []).filter(
+ (step) => step.planConfidence === "manual" || step.status === "Done"
+ );
+ if (locked.length > 0) {
+ return {
+ ok: false,
+ reason: "steps-locked",
+ modelUploadId,
+ message: `${locked.length} ${locked.length === 1 ? "step is" : "steps are"} manually authored or done — delete or reset them before regenerating`
+ };
+ }
+ const removed = await client
+ .from("assemblyInstructionStep")
+ .delete()
+ .eq("assemblyInstructionId", args.assemblyInstructionId);
+ if (removed.error) {
+ return { ok: false, reason: "error", message: removed.error.message };
+ }
+ }
+
+ const plan = await getAssemblyPlanJson(client, modelUploadId);
+ if (!plan) {
+ return { ok: false, reason: "no-plan", modelUploadId };
+ }
+
+ // graph.json powers identical-part grouping (geometryHash) and fallback
+ // motion synthesis for unplanned, unflagged parts
+ let graphIndex: AssemblyGraphIndex | null = null;
+ const graphPath = instruction.data.modelUpload?.graphPath;
+ if (graphPath) {
+ const graphFile = await client.storage.from("private").download(graphPath);
+ if (graphFile.data) {
+ try {
+ const graph = JSON.parse(await graphFile.data.text()) as AssemblyGraph;
+ graphIndex = indexAssemblyGraph(graph);
+ } catch {
+ // grouping degrades to per-part steps
+ }
+ }
+ }
+
+ const groups = buildAssemblyStepGroups(plan, graphIndex);
+ if (groups.length === 0) {
+ return { ok: false, reason: "error", message: "The plan has no parts" };
+ }
+
+ // Bake an occlusion-aware camera per step: an unobstructed view of the step's
+ // components on their motion path, given only the components already animated
+ // by earlier steps. Falls back to the viewer's live framing (camera: null)
+ // when the graph is unavailable.
+ const cameras = graphIndex ? computeStepCameras(groups, graphIndex) : [];
+
+ const rows = groups.map((group, index) => {
+ const motion = motionSchema.safeParse(group.motion);
+ return {
+ assemblyInstructionId: args.assemblyInstructionId,
+ sortOrder: index + 1,
+ // A pre-grouped unit (e.g. a purchased PCB) titles its step with the
+ // unit name; ungrouped steps derive their title from their parts.
+ title: group.name ?? null,
+ componentNodeIds: group.componentNodeIds,
+ motion: (motion.success ? motion.data : { type: "none" }) as Json,
+ camera: (cameras[index] ?? null) as Json | null,
+ warnings:
+ group.blockedBy.length > 0
+ ? ({ flagged: true, blockedBy: group.blockedBy } as Json)
+ : null,
+ planConfidence: group.confidence,
+ status: "Review" as const,
+ companyId: args.companyId,
+ createdBy: args.userId
+ };
+ });
+
+ const insert = await client
+ .from("assemblyInstructionStep")
+ .insert(rows)
+ .select("id, componentNodeIds");
+ if (insert.error) {
+ return { ok: false, reason: "error", message: insert.error.message };
+ }
+
+ // Seed each step's materials from the model's component→BOM mappings —
+ // best-effort; generation succeeds regardless.
+ if (graphIndex && insert.data?.length) {
+ const mappings = await getAssemblyComponentMappings(client, modelUploadId);
+ const itemIdByGeometryHash = new Map(
+ (mappings.data ?? []).map((mapping) => [
+ mapping.geometryHash,
+ mapping.itemId
+ ])
+ );
+ if (itemIdByGeometryHash.size > 0) {
+ const seeds = deriveAssemblyStepMaterialSeeds({
+ steps: insert.data,
+ graphIndex,
+ itemIdByGeometryHash
+ });
+ if (seeds.length > 0) {
+ await insertAssemblyStepMaterialSeeds(client, seeds, args);
+ }
+ }
+ }
+
+ return { ok: true, created: rows.length };
+}
+
+/**
+ * Maps a DB step row to the viewer's step shape. JSONB columns are validated
+ * defensively — `path` motions with invalid keyframes throw inside the viewer,
+ * so anything that fails the schema falls back to a safe default.
+ */
+export function toViewerStep(step: AssemblyInstructionStepRow): AssemblyStep {
+ const motion = motionSchema.safeParse(step.motion);
+ const camera = cameraSchema.safeParse(step.camera);
+ const fastener = fastenerSchema.safeParse(step.fastener);
+ const planWarnings = stepPlanWarningsSchema.safeParse(step.warnings);
+
+ return {
+ id: step.id,
+ title: step.title,
+ instructionText: step.instructionText,
+ componentNodeIds: step.componentNodeIds ?? [],
+ motion: motion.success ? motion.data : { type: "none" },
+ camera: camera.success ? camera.data : null,
+ fastener: fastener.success ? fastener.data : null,
+ durationSeconds: step.durationSeconds,
+ flagged:
+ planWarnings.success && planWarnings.data.flagged === true
+ ? true
+ : undefined
+ };
+}
+
// Purchase order lines for a job's materials, scoped by item + location (not
// jobId, since planning-generated POs aren't linked to the job). Flattened to
// the procurement-status shape used by the BoM tree and the Materials table.
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index 2ae98251a9..c6ce5a4526 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -1,6 +1,14 @@
import type { Database } from "@carbon/database";
import type {
getActiveProductionEvents,
+ getAssemblyComponentMappings,
+ getAssemblyInstruction,
+ getAssemblyInstructionStepMaterials,
+ getAssemblyInstructionStepRequirements,
+ getAssemblyInstructionSteps,
+ getAssemblyInstructions,
+ getAssemblyStandardNotes,
+ getAssemblyUnits,
getFailureMode,
getFailureModes,
getJob,
@@ -181,3 +189,37 @@ export type ProductionPlanningItem = NonNullable<
export type ScrapReason = NonNullable<
Awaited<ReturnType<typeof getScrapReasons>>["data"]
>[number];
+
+// --- Assembly Instructions ---------------------------------------------
+
+export type AssemblyInstruction = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstruction>>["data"]
+>;
+
+export type AssemblyInstructionListItem = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructions>>["data"]
+>[number];
+
+export type AssemblyInstructionStepRow = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructionSteps>>["data"]
+>[number];
+
+export type AssemblyStepRequirement = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructionStepRequirements>>["data"]
+>[number];
+
+export type AssemblyStepMaterial = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyInstructionStepMaterials>>["data"]
+>[number];
+
+export type AssemblyStandardNote = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyStandardNotes>>["data"]
+>[number];
+
+export type AssemblyUnit = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyUnits>>["data"]
+>[number];
+
+export type AssemblyComponentMapping = NonNullable<
+ Awaited<ReturnType<typeof getAssemblyComponentMappings>>["data"]
+>[number];
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx
new file mode 100644
index 0000000000..aea23df405
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx
@@ -0,0 +1,1612 @@
+import {
+ Badge,
+ Button,
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+ cn,
+ IconButton,
+ Input,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalHeader,
+ ModalTitle,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ toast,
+ VStack
+} from "@carbon/react";
+import type { AssemblyGraphIndex, ComponentGroup } from "@carbon/viewer";
+import { describeStep, groupComponentNodeIds } from "@carbon/viewer";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import type { MouseEvent } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ LuArrowDownAZ,
+ LuArrowDownWideNarrow,
+ LuBlocks,
+ LuChevronDown,
+ LuChevronRight,
+ LuCirclePlus,
+ LuEye,
+ LuEyeOff,
+ LuMerge,
+ LuPencil,
+ LuSearch,
+ LuSettings,
+ LuTrash,
+ LuX
+} from "react-icons/lu";
+import { useFetcher, useParams } from "react-router";
+import { Empty } from "~/components";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import type { FlattenedBomMaterial } from "../../production.service";
+import { toViewerStep } from "../../production.service";
+import type {
+ AssemblyComponentMapping,
+ AssemblyInstructionStepRow,
+ AssemblyUnit
+} from "../../types";
+import { ComponentColorSwatch } from "./AssemblyStepBom";
+
+type SortMode = "count" | "alpha";
+
+/** The distinct component types inside a subassembly, with the member instances of each. */
+type UnitChild = { group: ComponentGroup; nodeIds: string[] };
+
+/**
+ * One rendered row: a subassembly (virtual component) and its expanded member
+ * components, or a component group and its expanded instances. Subassemblies and multi-quantity
+ * groups both expand the same way.
+ */
+type ListRow =
+ | { type: "unit"; unit: AssemblyUnit; children: UnitChild[] }
+ | {
+ type: "unitChild";
+ unit: AssemblyUnit;
+ group: ComponentGroup;
+ nodeIds: string[];
+ }
+ | { type: "group"; group: ComponentGroup }
+ | {
+ type: "instance";
+ group: ComponentGroup;
+ nodeId: string;
+ instanceIndex: number;
+ };
+
+/** The instance nodeIds a row represents (all of them for a group/unit row). */
+function rowNodeIds(row: ListRow): string[] {
+ switch (row.type) {
+ case "unit":
+ return row.unit.componentNodeIds ?? [];
+ case "unitChild":
+ return row.nodeIds;
+ case "group":
+ return row.group.nodeIds;
+ case "instance":
+ return [row.nodeId];
+ }
+}
+
+type SelectionState = "none" | "partial" | "all";
+
+function selectionStateOf(
+ nodeIds: string[],
+ selected: ReadonlySet<string>
+): SelectionState {
+ let count = 0;
+ for (const id of nodeIds) if (selected.has(id)) count++;
+ if (count === 0) return "none";
+ return count === nodeIds.length ? "all" : "partial";
+}
+
+type AssemblyBomTreeProps = {
+ graphIndex: AssemblyGraphIndex | null;
+ steps: AssemblyInstructionStepRow[];
+ units: AssemblyUnit[];
+ isDisabled: boolean;
+ modelUploadId: string | null;
+ componentMappings: AssemblyComponentMapping[];
+ bomMaterials: FlattenedBomMaterial[];
+ /** Current selection (shared with the viewer) — marks + scrolls to the rows */
+ selectedNodeIds: string[];
+ /** The Components tab is the visible tab — gate scroll-to-selection on it */
+ isActive: boolean;
+ /** A new-step create is in flight — disables the Add Step action */
+ isAddingStep: boolean;
+ onHighlightComponents: (nodeIds: string[]) => void;
+ onHideComponents: (nodeIds: string[]) => void;
+ onSelectStep: (stepId: string) => void;
+ /** Create a step seeded with the current selection (shared with the parent) */
+ onAddStep: () => void;
+};
+
+/**
+ * Bill of materials derived from the model's assembly graph: every distinct
+ * component with its instance count, plus authored subassembly units — sets of
+ * components the planner treats as one rigid body (overriding the automatic
+ * BOM-driven derivation). Selecting rows highlights all instances in the viewer;
+ * a selection can be planned as one component via the toolbar or right-click menu.
+ * Components map to engineering BOM items (methodMaterial) by geometry hash —
+ * auto-matched by name/quantity, adjustable per component in the detail popover.
+ */
+export default function AssemblyBomTree({
+ graphIndex,
+ steps,
+ units,
+ isDisabled,
+ modelUploadId,
+ componentMappings,
+ bomMaterials,
+ selectedNodeIds,
+ isActive,
+ isAddingStep,
+ onHighlightComponents,
+ onHideComponents,
+ onSelectStep,
+ onAddStep
+}: AssemblyBomTreeProps) {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const permissions = usePermissions();
+ const canGroup = !isDisabled && permissions.can("create", "production");
+ const canAddStep = !isDisabled && permissions.can("update", "production");
+ const canMap =
+ !isDisabled &&
+ permissions.can("update", "production") &&
+ Boolean(modelUploadId);
+
+ const autoMatchFetcher = useFetcher<{ success: boolean }>();
+ const mappingsByHash = useMemo(
+ () =>
+ new Map(
+ componentMappings.map((mapping) => [mapping.geometryHash, mapping])
+ ),
+ [componentMappings]
+ );
+
+ const [sortMode, setSortMode] = useState<SortMode>("count");
+ const [search, setSearch] = useState("");
+ // Selection and visibility are tracked per instance (nodeId), so a group with
+ // several instances can be partly selected or hidden — e.g. 2 of 4 screws.
+ // Selection round-trips through the parent (shared with the viewer).
+ const selectedSet = useMemo(
+ () => new Set(selectedNodeIds),
+ [selectedNodeIds]
+ );
+ const [hiddenNodeIds, setHiddenNodeIds] = useState<ReadonlySet<string>>(
+ new Set()
+ );
+ const [expandedKeys, setExpandedKeys] = useState<ReadonlySet<string>>(
+ new Set()
+ );
+ const [showCreateUnit, setShowCreateUnit] = useState(false);
+ const [editingUnit, setEditingUnit] = useState<AssemblyUnit | null>(null);
+ const lastClickedIndexRef = useRef<number | null>(null);
+
+ // Every instance that belongs to a subassembly — those show under the
+ // subassembly, so they're dropped from the flat list to avoid double-listing.
+ const unitMemberSet = useMemo(() => {
+ const set = new Set<string>();
+ for (const unit of units) {
+ for (const nodeId of unit.componentNodeIds ?? []) set.add(nodeId);
+ }
+ return set;
+ }, [units]);
+
+ const componentGroups = useMemo(() => {
+ if (!graphIndex) return [];
+ // Keep only the instances of each component that aren't inside a subassembly.
+ // A component half in a subassembly still lists its loose instances (with the
+ // reduced count); a component fully consumed by subassemblies drops out.
+ const groups: ComponentGroup[] = [];
+ for (const group of graphIndex.groups) {
+ const nodeIds =
+ unitMemberSet.size === 0
+ ? group.nodeIds
+ : group.nodeIds.filter((nodeId) => !unitMemberSet.has(nodeId));
+ if (nodeIds.length === 0) continue;
+ groups.push(
+ nodeIds.length === group.nodeIds.length
+ ? group
+ : { ...group, nodeIds, count: nodeIds.length }
+ );
+ }
+ if (sortMode === "count") {
+ groups.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
+ } else {
+ groups.sort((a, b) => a.name.localeCompare(b.name));
+ }
+ return groups;
+ }, [graphIndex, sortMode, unitMemberSet]);
+
+ // Name filter for the rendered list. Selection/hiding still operate on the
+ // full `componentGroups` (they key by group, not display position); only the rows
+ // shown, the shift-click range, and scroll-to-selection use `rows`.
+ const normalizedSearch = search.trim().toLowerCase();
+ const rows = useMemo(() => {
+ if (!normalizedSearch) return componentGroups;
+ return componentGroups.filter((group) =>
+ group.name.toLowerCase().includes(normalizedSearch)
+ );
+ }, [componentGroups, normalizedSearch]);
+
+ // A step whose components are exactly a subassembly unit is titled by its name.
+ const namedUnits = useMemo(
+ () =>
+ units.map((unit) => ({
+ name: unit.name,
+ componentNodeIds: unit.componentNodeIds ?? []
+ })),
+ [units]
+ );
+
+ /** groupKey → steps that install instances of the component */
+ const stepUsage = useMemo(() => {
+ const usage = new Map<
+ string,
+ { stepId: string; index: number; title: string }[]
+ >();
+ if (!graphIndex) return usage;
+ steps.forEach((step, index) => {
+ const seen = new Set<string>();
+ for (const nodeId of step.componentNodeIds ?? []) {
+ const group = graphIndex.groupByNodeId.get(nodeId);
+ if (!group || seen.has(group.key)) continue;
+ seen.add(group.key);
+ const entry = usage.get(group.key) ?? [];
+ entry.push({
+ stepId: step.id,
+ index,
+ title:
+ describeStep(toViewerStep(step), graphIndex, namedUnits) ??
+ "Untitled step"
+ });
+ usage.set(group.key, entry);
+ }
+ });
+ return usage;
+ }, [steps, graphIndex, namedUnits]);
+
+ // A subassembly's member instances, grouped by component type — so it expands
+ // into "Screw ×4 / Board ×1" child rows the same way a multi-quantity component does.
+ const unitChildren = useMemo(() => {
+ const map = new Map<string, UnitChild[]>();
+ if (!graphIndex) return map;
+ for (const unit of units) {
+ const byGroup = new Map<string, UnitChild>();
+ for (const nodeId of unit.componentNodeIds ?? []) {
+ const group = graphIndex.groupByNodeId.get(nodeId);
+ if (!group) continue;
+ const existing = byGroup.get(group.key);
+ if (existing) existing.nodeIds.push(nodeId);
+ else byGroup.set(group.key, { group, nodeIds: [nodeId] });
+ }
+ map.set(unit.id, [...byGroup.values()]);
+ }
+ return map;
+ }, [units, graphIndex]);
+
+ const visibleUnits = useMemo(() => {
+ if (!normalizedSearch) return units;
+ return units.filter((unit) =>
+ unit.name.toLowerCase().includes(normalizedSearch)
+ );
+ }, [units, normalizedSearch]);
+
+ // Flatten subassemblies and component groups (each with their expanded children)
+ // into the virtualized list. Subassemblies lead — they're the higher-level
+ // grouping — and expand into their member components; a component group with count > 1
+ // expands into one row per instance. Either way a subset can be selected or
+ // hidden individually.
+ const visualRows = useMemo<ListRow[]>(() => {
+ const list: ListRow[] = [];
+ for (const unit of visibleUnits) {
+ const children = unitChildren.get(unit.id) ?? [];
+ list.push({ type: "unit", unit, children });
+ if (expandedKeys.has(`unit:${unit.id}`)) {
+ for (const child of children) {
+ list.push({
+ type: "unitChild",
+ unit,
+ group: child.group,
+ nodeIds: child.nodeIds
+ });
+ }
+ }
+ }
+ for (const group of rows) {
+ list.push({ type: "group", group });
+ if (group.count > 1 && expandedKeys.has(group.key)) {
+ group.nodeIds.forEach((nodeId, instanceIndex) => {
+ list.push({ type: "instance", group, nodeId, instanceIndex });
+ });
+ }
+ }
+ return list;
+ }, [rows, expandedKeys, visibleUnits, unitChildren]);
+
+ const hasSelection = selectedNodeIds.length > 0;
+
+ // Push the hidden instance set up to the viewer.
+ useEffect(() => {
+ onHideComponents([...hiddenNodeIds]);
+ }, [hiddenNodeIds, onHideComponents]);
+
+ const applyNodeSelection = (next: ReadonlySet<string>) => {
+ onHighlightComponents([...next]);
+ };
+
+ const onRowClick = (event: MouseEvent, rowIndex: number) => {
+ const row = visualRows[rowIndex];
+ if (!row) return;
+ const rowNodes = rowNodeIds(row);
+ let next: Set<string>;
+ if (event.shiftKey && lastClickedIndexRef.current !== null) {
+ next = new Set(selectedNodeIds);
+ const start = Math.min(lastClickedIndexRef.current, rowIndex);
+ const end = Math.max(lastClickedIndexRef.current, rowIndex);
+ for (let i = start; i <= end; i++) {
+ const inRange = visualRows[i];
+ if (inRange) for (const id of rowNodeIds(inRange)) next.add(id);
+ }
+ } else if (event.metaKey || event.ctrlKey) {
+ next = new Set(selectedNodeIds);
+ const allSelected = rowNodes.every((id) => next.has(id));
+ for (const id of rowNodes) {
+ if (allSelected) next.delete(id);
+ else next.add(id);
+ }
+ } else {
+ // Plain click selects just this row; clicking it when it is already the
+ // entire selection clears it.
+ const isOnlySelection =
+ selectedNodeIds.length === rowNodes.length &&
+ rowNodes.every((id) => selectedSet.has(id));
+ next = isOnlySelection ? new Set() : new Set(rowNodes);
+ }
+ lastClickedIndexRef.current = rowIndex;
+ applyNodeSelection(next);
+ };
+
+ const onToggleExpand = (key: string) => {
+ setExpandedKeys((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ };
+
+ const onHideSelection = () => {
+ setHiddenNodeIds((prev) => {
+ const next = new Set(prev);
+ for (const id of selectedNodeIds) next.add(id);
+ return next;
+ });
+ applyNodeSelection(new Set());
+ };
+
+ // Toggle visibility of a set of instances (a whole group, or one instance).
+ // A group hides unless every instance is already hidden, in which case it
+ // reveals them (Onshape-style per-row eye).
+ const onToggleHide = (nodeIds: string[]) => {
+ setHiddenNodeIds((prev) => {
+ const next = new Set(prev);
+ const allHidden = nodeIds.every((id) => next.has(id));
+ for (const id of nodeIds) {
+ if (allHidden) next.delete(id);
+ else next.add(id);
+ }
+ return next;
+ });
+ };
+
+ const onShowAll = () => setHiddenNodeIds(new Set());
+
+ const parentRef = useRef<HTMLDivElement>(null);
+ const virtualizer = useVirtualizer({
+ count: visualRows.length,
+ getScrollElement: () => parentRef.current,
+ estimateSize: () => 36,
+ overscan: 12
+ });
+
+ // Bring the current selection into view — when it changes while the Components tab
+ // is open, and when the tab becomes active with a selection already present.
+ // The scroll container has no dimensions while the tab is hidden, so gate on
+ // isActive and defer a frame so the just-shown list can measure.
+ const firstSelectedIndex = useMemo(
+ () =>
+ visualRows.findIndex((row) =>
+ rowNodeIds(row).some((id) => selectedSet.has(id))
+ ),
+ [visualRows, selectedSet]
+ );
+ useEffect(() => {
+ if (!isActive || firstSelectedIndex < 0) return;
+ const frame = requestAnimationFrame(() =>
+ virtualizer.scrollToIndex(firstSelectedIndex, { align: "center" })
+ );
+ return () => cancelAnimationFrame(frame);
+ }, [isActive, firstSelectedIndex, virtualizer]);
+
+ if (!graphIndex) {
+ return (
+ <Empty className="border-none">
+ <p className="text-sm text-muted-foreground max-w-[280px] text-center">
+ The bill of materials appears here once the model loads
+ </p>
+ </Empty>
+ );
+ }
+
+ return (
+ <div className="flex h-full w-full flex-col">
+ <div className="flex w-full flex-none items-center justify-between border-b border-border px-3 py-1.5">
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {hasSelection
+ ? `${selectedNodeIds.length} selected`
+ : bomMaterials.length > 0
+ ? `${componentGroups.length} components · ${mappingsByHash.size} mapped to BOM`
+ : `${componentGroups.length} component${componentGroups.length === 1 ? "" : "s"} · ${graphIndex.graph.componentCount} instance${graphIndex.graph.componentCount === 1 ? "" : "s"}`}
+ </span>
+ <div className="flex items-center gap-1">
+ {!hasSelection && canMap && bomMaterials.length > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="secondary"
+ size="sm"
+ isDisabled={autoMatchFetcher.state !== "idle"}
+ isLoading={autoMatchFetcher.state !== "idle"}
+ onClick={() => {
+ autoMatchFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.autoMatchAssemblyComponents(id)
+ });
+ }}
+ >
+ Match BOM
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Match components to BOM items</TooltipContent>
+ </Tooltip>
+ )}
+ {hasSelection && canGroup && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label="Plan as one component"
+ icon={<LuMerge />}
+ variant="ghost"
+ size="sm"
+ onClick={() => setShowCreateUnit(true)}
+ />
+ </TooltipTrigger>
+ <TooltipContent>Plan as one component</TooltipContent>
+ </Tooltip>
+ )}
+ {hasSelection && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label="Hide selected components"
+ icon={<LuEyeOff />}
+ variant="ghost"
+ size="sm"
+ onClick={onHideSelection}
+ />
+ </TooltipTrigger>
+ <TooltipContent>Hide selected components</TooltipContent>
+ </Tooltip>
+ )}
+ {hiddenNodeIds.size > 0 && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label="Show all hidden components"
+ icon={<LuEye />}
+ variant="ghost"
+ size="sm"
+ onClick={onShowAll}
+ />
+ </TooltipTrigger>
+ <TooltipContent>Show all hidden components</TooltipContent>
+ </Tooltip>
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label={
+ sortMode === "count" ? "Sort alphabetically" : "Sort by count"
+ }
+ icon={
+ sortMode === "count" ? (
+ <LuArrowDownWideNarrow />
+ ) : (
+ <LuArrowDownAZ />
+ )
+ }
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ setSortMode((mode) => (mode === "count" ? "alpha" : "count"))
+ }
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ {sortMode === "count" ? "Sort alphabetically" : "Sort by count"}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ {componentGroups.length > 0 && (
+ <div className="relative w-full flex-none border-b border-border px-2 py-1.5">
+ <LuSearch className="pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ aria-label="Search components"
+ placeholder="Search components"
+ size="sm"
+ className="pl-7"
+ value={search}
+ onChange={(searchEvent) => setSearch(searchEvent.target.value)}
+ />
+ </div>
+ )}
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <div
+ ref={parentRef}
+ className="w-full flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ onKeyDown={(event) => {
+ if (event.key === "Escape" && hasSelection) {
+ applyNodeSelection(new Set());
+ }
+ }}
+ >
+ <div
+ className="relative w-full"
+ style={{ height: virtualizer.getTotalSize() }}
+ >
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const row = visualRows[virtualRow.index];
+ if (!row) return null;
+ const style: React.CSSProperties = {
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: virtualRow.size,
+ transform: `translateY(${virtualRow.start}px)`
+ };
+ const nodes = rowNodeIds(row);
+ if (row.type === "unit") {
+ return (
+ <UnitListRow
+ key={`unit-${row.unit.id}`}
+ unit={row.unit}
+ memberCount={nodes.length}
+ isExpandable={row.children.length > 0}
+ isExpanded={expandedKeys.has(`unit:${row.unit.id}`)}
+ selection={selectionStateOf(nodes, selectedSet)}
+ hidden={selectionStateOf(nodes, hiddenNodeIds)}
+ isDisabled={isDisabled}
+ instructionId={id}
+ style={style}
+ onClick={(event) => onRowClick(event, virtualRow.index)}
+ onToggleHide={() => onToggleHide(nodes)}
+ onToggleExpand={() =>
+ onToggleExpand(`unit:${row.unit.id}`)
+ }
+ onEdit={() => setEditingUnit(row.unit)}
+ />
+ );
+ }
+ if (row.type === "unitChild") {
+ return (
+ <UnitChildRow
+ key={`unitchild-${row.unit.id}-${row.group.key}`}
+ group={row.group}
+ count={row.nodeIds.length}
+ selection={selectionStateOf(nodes, selectedSet)}
+ hidden={selectionStateOf(nodes, hiddenNodeIds)}
+ style={style}
+ onClick={(event) => onRowClick(event, virtualRow.index)}
+ onToggleHide={() => onToggleHide(nodes)}
+ />
+ );
+ }
+ if (row.type === "instance") {
+ return (
+ <InstanceRow
+ key={row.nodeId}
+ group={row.group}
+ instanceIndex={row.instanceIndex}
+ isSelected={selectedSet.has(row.nodeId)}
+ isHidden={hiddenNodeIds.has(row.nodeId)}
+ style={style}
+ onClick={(event) => onRowClick(event, virtualRow.index)}
+ onToggleHide={() => onToggleHide(nodes)}
+ />
+ );
+ }
+ const group = row.group;
+ return (
+ <ComponentRow
+ key={group.key}
+ group={group}
+ selection={selectionStateOf(nodes, selectedSet)}
+ hidden={selectionStateOf(nodes, hiddenNodeIds)}
+ isExpanded={expandedKeys.has(group.key)}
+ usage={stepUsage.get(group.key) ?? []}
+ mapping={mappingsByHash.get(group.key) ?? null}
+ bomMaterials={bomMaterials}
+ canMap={canMap}
+ modelUploadId={modelUploadId}
+ instructionId={id}
+ style={style}
+ onClick={(event) => onRowClick(event, virtualRow.index)}
+ onToggleHide={() => onToggleHide(nodes)}
+ onToggleExpand={() => onToggleExpand(group.key)}
+ onSelectStep={onSelectStep}
+ />
+ );
+ })}
+ </div>
+ {rows.length === 0 &&
+ visibleUnits.length === 0 &&
+ normalizedSearch && (
+ <p className="px-3 py-4 text-center text-xs text-muted-foreground">
+ No components match “{search.trim()}”
+ </p>
+ )}
+ </div>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem
+ disabled={!canAddStep || !hasSelection || isAddingStep}
+ onClick={onAddStep}
+ >
+ <LuCirclePlus className="mr-2 h-4 w-4" />
+ Add step
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!canGroup || !hasSelection}
+ onClick={() => setShowCreateUnit(true)}
+ >
+ <LuMerge className="mr-2 h-4 w-4" />
+ Plan as one component
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem disabled={!hasSelection} onClick={onHideSelection}>
+ <LuEyeOff className="mr-2 h-4 w-4" />
+ Hide selected components
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={hiddenNodeIds.size === 0}
+ onClick={onShowAll}
+ >
+ <LuEye className="mr-2 h-4 w-4" />
+ Show all hidden components
+ </ContextMenuItem>
+ <ContextMenuItem
+ disabled={!hasSelection}
+ onClick={() => applyNodeSelection(new Set())}
+ >
+ Clear selection
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ {canAddStep && (
+ <div className="w-full flex-none border-t border-border p-4">
+ <Button
+ className="w-full"
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ isDisabled={isAddingStep}
+ isLoading={isAddingStep}
+ onClick={onAddStep}
+ >
+ Add Step
+ </Button>
+ </div>
+ )}
+ {showCreateUnit && modelUploadId && (
+ <CreateUnitModal
+ instructionId={id}
+ modelUploadId={modelUploadId}
+ componentNodeIds={selectedNodeIds}
+ onClose={() => setShowCreateUnit(false)}
+ onCreated={() => {
+ setShowCreateUnit(false);
+ applyNodeSelection(new Set());
+ }}
+ />
+ )}
+ {editingUnit && modelUploadId && (
+ <EditUnitModal
+ instructionId={id}
+ modelUploadId={modelUploadId}
+ unit={editingUnit}
+ graphIndex={graphIndex}
+ selectedNodeIds={selectedNodeIds}
+ onClose={() => setEditingUnit(null)}
+ onUpdated={() => {
+ setEditingUnit(null);
+ toast.success(
+ "Subassembly updated — re-run motion planning to apply the change"
+ );
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * A subassembly as a virtual component row: click selects its members (red in the
+ * viewer), the chevron expands it into its member component types (UnitChildRow),
+ * and it carries the same hide / edit / delete affordances as the old section.
+ */
+function UnitListRow({
+ unit,
+ memberCount,
+ isExpandable,
+ isExpanded,
+ selection,
+ hidden,
+ isDisabled,
+ instructionId,
+ style,
+ onClick,
+ onToggleHide,
+ onToggleExpand,
+ onEdit
+}: {
+ unit: AssemblyUnit;
+ memberCount: number;
+ isExpandable: boolean;
+ isExpanded: boolean;
+ selection: SelectionState;
+ hidden: SelectionState;
+ isDisabled: boolean;
+ instructionId: string;
+ style: React.CSSProperties;
+ onClick: (event: MouseEvent) => void;
+ onToggleHide: () => void;
+ onToggleExpand: () => void;
+ onEdit: () => void;
+}) {
+ const permissions = usePermissions();
+ const deleteFetcher = useFetcher<{ success: boolean }>();
+ const canUpdate = !isDisabled && permissions.can("update", "production");
+ const canDelete = !isDisabled && permissions.can("delete", "production");
+ const allHidden = hidden === "all";
+
+ if (deleteFetcher.state !== "idle") return null;
+
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ style={style}
+ className={cn(
+ "group relative flex cursor-pointer select-none items-center gap-2 border-b border-border px-3 text-sm hover:bg-accent/30",
+ selection === "all" && "bg-blue-500/10 hover:bg-blue-500/10",
+ selection === "partial" && "bg-blue-500/5 hover:bg-blue-500/5",
+ allHidden && "opacity-50"
+ )}
+ onClick={onClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onClick(event as unknown as MouseEvent);
+ }
+ }}
+ >
+ {selection !== "none" && (
+ <span
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-y-0 left-0 w-0.5 bg-blue-500",
+ selection === "partial" && "opacity-50"
+ )}
+ />
+ )}
+ {isExpandable ? (
+ <button
+ type="button"
+ aria-label={
+ isExpanded ? `Collapse ${unit.name}` : `Expand ${unit.name}`
+ }
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent"
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleExpand();
+ }}
+ >
+ {isExpanded ? (
+ <LuChevronDown className="h-3.5 w-3.5" />
+ ) : (
+ <LuChevronRight className="h-3.5 w-3.5" />
+ )}
+ </button>
+ ) : (
+ <span className="h-5 w-5 shrink-0" aria-hidden />
+ )}
+ <LuBlocks className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate font-medium" title={unit.name}>
+ {unit.name}
+ </span>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{memberCount}
+ </Badge>
+ <div className="flex items-center">
+ <IconButton
+ aria-label={allHidden ? `Show ${unit.name}` : `Hide ${unit.name}`}
+ icon={allHidden ? <LuEyeOff /> : <LuEye />}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "focus:opacity-100",
+ hidden !== "none"
+ ? "opacity-100 text-muted-foreground"
+ : "opacity-0 group-hover:opacity-100"
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleHide();
+ }}
+ />
+ {canUpdate && (
+ <IconButton
+ aria-label={`Edit subassembly ${unit.name}`}
+ icon={<LuPencil />}
+ variant="ghost"
+ size="sm"
+ className="opacity-0 group-hover:opacity-100 focus:opacity-100"
+ onClick={(event) => {
+ event.stopPropagation();
+ onEdit();
+ }}
+ />
+ )}
+ {canDelete && (
+ <IconButton
+ aria-label={`Delete subassembly ${unit.name}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ className="opacity-0 group-hover:opacity-100 focus:opacity-100"
+ onClick={(event) => {
+ event.stopPropagation();
+ deleteFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyUnit(instructionId, unit.id)
+ });
+ }}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** One member component type inside an expanded subassembly (indented, selectable). */
+function UnitChildRow({
+ group,
+ count,
+ selection,
+ hidden,
+ style,
+ onClick,
+ onToggleHide
+}: {
+ group: ComponentGroup;
+ count: number;
+ selection: SelectionState;
+ hidden: SelectionState;
+ style: React.CSSProperties;
+ onClick: (event: MouseEvent) => void;
+ onToggleHide: () => void;
+}) {
+ const allHidden = hidden === "all";
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ style={style}
+ className={cn(
+ "group relative flex cursor-pointer select-none items-center gap-2 border-b border-border py-1 pl-9 pr-3 text-sm hover:bg-accent/30",
+ selection === "all" && "bg-blue-500/10 hover:bg-blue-500/10",
+ selection === "partial" && "bg-blue-500/5 hover:bg-blue-500/5",
+ allHidden && "opacity-50"
+ )}
+ onClick={onClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onClick(event as unknown as MouseEvent);
+ }
+ }}
+ >
+ {selection !== "none" && (
+ <span
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-y-0 left-0 w-0.5 bg-blue-500",
+ selection === "partial" && "opacity-50"
+ )}
+ />
+ )}
+ <ComponentColorSwatch color={group.color} />
+ <span
+ className="min-w-0 flex-1 truncate text-muted-foreground"
+ title={group.name}
+ >
+ {group.name}
+ </span>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{count}
+ </Badge>
+ <IconButton
+ aria-label={allHidden ? `Show ${group.name}` : `Hide ${group.name}`}
+ icon={allHidden ? <LuEyeOff /> : <LuEye />}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "focus:opacity-100",
+ hidden !== "none"
+ ? "opacity-100 text-muted-foreground"
+ : "opacity-0 group-hover:opacity-100"
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleHide();
+ }}
+ />
+ </div>
+ );
+}
+
+function CreateUnitModal({
+ instructionId,
+ modelUploadId,
+ componentNodeIds,
+ onClose,
+ onCreated
+}: {
+ instructionId: string;
+ modelUploadId: string;
+ componentNodeIds: string[];
+ onClose: () => void;
+ onCreated: () => void;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ const [name, setName] = useState("");
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ onCreated();
+ }
+ }, [fetcher.state, fetcher.data, onCreated]);
+
+ const onSubmit = () => {
+ if (!name.trim()) return;
+ const formData = new FormData();
+ formData.append("modelUploadId", modelUploadId);
+ formData.append("name", name.trim());
+ formData.append("componentNodeIds", JSON.stringify(componentNodeIds));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.newAssemblyUnit(instructionId)
+ });
+ };
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Plan as one component</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={3} className="w-full">
+ <p className="text-sm text-muted-foreground">
+ The planner treats these {componentNodeIds.length} component
+ {componentNodeIds.length === 1 ? "" : "s"} as one rigid body — one
+ step in the instructions. Re-run the plan to apply.
+ </p>
+ <Input
+ aria-label="Subassembly name"
+ placeholder="Subassembly name"
+ value={name}
+ autoFocus
+ onChange={(nameEvent) => setName(nameEvent.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") onSubmit();
+ }}
+ />
+ <Button
+ className="self-end"
+ isDisabled={!name.trim() || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ onClick={onSubmit}
+ >
+ Create
+ </Button>
+ </VStack>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+/**
+ * Edits an authored subassembly in place: rename it and change which components it
+ * groups (remove a component type, or add the currently-selected components). Membership
+ * feeds the motion planner, so the caller nudges the user to re-run planning
+ * after saving.
+ */
+function EditUnitModal({
+ instructionId,
+ modelUploadId,
+ unit,
+ graphIndex,
+ selectedNodeIds,
+ onClose,
+ onUpdated
+}: {
+ instructionId: string;
+ modelUploadId: string;
+ unit: AssemblyUnit;
+ graphIndex: AssemblyGraphIndex | null;
+ selectedNodeIds: string[];
+ onClose: () => void;
+ onUpdated: () => void;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ const [name, setName] = useState(unit.name);
+ const [memberIds, setMemberIds] = useState<string[]>(
+ unit.componentNodeIds ?? []
+ );
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ onUpdated();
+ }
+ }, [fetcher.state, fetcher.data, onUpdated]);
+
+ const memberSet = useMemo(() => new Set(memberIds), [memberIds]);
+ // Distinct components in the unit, so removal is per component type ("drop this cap"),
+ // not per individual instance.
+ const groups = useMemo(
+ () => (graphIndex ? groupComponentNodeIds(memberIds, graphIndex) : []),
+ [graphIndex, memberIds]
+ );
+ // Components currently selected in the tree/viewer that aren't yet members.
+ const addableIds = useMemo(
+ () => selectedNodeIds.filter((id) => !memberSet.has(id)),
+ [selectedNodeIds, memberSet]
+ );
+
+ const removeGroup = (group: ComponentGroup) => {
+ const drop = new Set(group.nodeIds);
+ setMemberIds((prev) => prev.filter((id) => !drop.has(id)));
+ };
+
+ const addSelected = () => {
+ setMemberIds((prev) => [...prev, ...addableIds]);
+ };
+
+ const onSubmit = () => {
+ if (!name.trim() || memberIds.length === 0) return;
+ const formData = new FormData();
+ formData.append("modelUploadId", modelUploadId);
+ formData.append("name", name.trim());
+ formData.append("componentNodeIds", JSON.stringify(memberIds));
+ if (unit.itemId) formData.append("itemId", unit.itemId);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.updateAssemblyUnit(instructionId, unit.id)
+ });
+ };
+
+ const isSubmitting = fetcher.state !== "idle";
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Edit subassembly</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={3} className="w-full">
+ <Input
+ aria-label="Subassembly name"
+ placeholder="Subassembly name"
+ value={name}
+ autoFocus
+ onChange={(nameEvent) => setName(nameEvent.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") onSubmit();
+ }}
+ />
+ <VStack spacing={1} className="w-full">
+ <div className="flex w-full items-center justify-between">
+ <span className="text-xs text-muted-foreground">
+ {memberIds.length} component
+ {memberIds.length === 1 ? "" : "s"} in this subassembly
+ </span>
+ {addableIds.length > 0 && (
+ <Button variant="secondary" size="sm" onClick={addSelected}>
+ Add {addableIds.length} selected
+ </Button>
+ )}
+ </div>
+ {groups.length > 0 ? (
+ <ul className="max-h-64 w-full overflow-y-auto rounded-md border border-border">
+ {groups.map((group) => (
+ <li
+ key={group.key}
+ className="flex items-center gap-2 border-b border-border px-2 py-1 text-sm last:border-b-0"
+ >
+ <ComponentColorSwatch color={group.color} />
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={group.name}
+ >
+ {group.name}
+ </span>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ <IconButton
+ aria-label={`Remove ${group.name} from ${unit.name}`}
+ icon={<LuX />}
+ variant="ghost"
+ size="sm"
+ onClick={() => removeGroup(group)}
+ />
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {graphIndex
+ ? "No components — add a selection or cancel."
+ : "The model is still loading."}
+ </p>
+ )}
+ </VStack>
+ <p className="text-xs text-muted-foreground">
+ Changing the components redefines the subassembly. Re-run Motion
+ Planning to apply the change to the steps.
+ </p>
+ <Button
+ className="self-end"
+ isDisabled={
+ !name.trim() || memberIds.length === 0 || isSubmitting
+ }
+ isLoading={isSubmitting}
+ onClick={onSubmit}
+ >
+ Save
+ </Button>
+ </VStack>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+}
+
+function ComponentRow({
+ group,
+ selection,
+ hidden,
+ isExpanded,
+ usage,
+ mapping,
+ bomMaterials,
+ canMap,
+ modelUploadId,
+ instructionId,
+ style,
+ onClick,
+ onToggleHide,
+ onToggleExpand,
+ onSelectStep
+}: {
+ group: ComponentGroup;
+ selection: SelectionState;
+ hidden: SelectionState;
+ isExpanded: boolean;
+ usage: { stepId: string; index: number; title: string }[];
+ mapping: AssemblyComponentMapping | null;
+ bomMaterials: FlattenedBomMaterial[];
+ canMap: boolean;
+ modelUploadId: string | null;
+ instructionId: string;
+ style: React.CSSProperties;
+ onClick: (event: MouseEvent) => void;
+ onToggleHide: () => void;
+ onToggleExpand: () => void;
+ onSelectStep: (stepId: string) => void;
+}) {
+ const bomLine = mapping
+ ? bomMaterials.find((material) => material.itemId === mapping.itemId)
+ : undefined;
+ const quantityMismatch =
+ bomLine !== undefined && Math.round(bomLine.quantity) !== group.count;
+ const allHidden = hidden === "all";
+ const expandable = group.count > 1;
+
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ style={style}
+ className={cn(
+ "group relative flex cursor-pointer select-none items-center gap-2 border-b border-border px-3 text-sm hover:bg-accent/30",
+ // Selection gets a blue left bar plus a blue wash. A partly-selected
+ // group reads lighter than a full one.
+ selection === "all" && "bg-blue-500/10 hover:bg-blue-500/10",
+ selection === "partial" && "bg-blue-500/5 hover:bg-blue-500/5",
+ allHidden && "opacity-50"
+ )}
+ onClick={onClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onClick(event as unknown as MouseEvent);
+ }
+ }}
+ >
+ {selection !== "none" && (
+ <span
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-y-0 left-0 w-0.5 bg-blue-500",
+ selection === "partial" && "opacity-50"
+ )}
+ />
+ )}
+ {expandable ? (
+ <button
+ type="button"
+ aria-label={
+ isExpanded ? `Collapse ${group.name}` : `Expand ${group.name}`
+ }
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent"
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleExpand();
+ }}
+ >
+ {isExpanded ? (
+ <LuChevronDown className="h-3.5 w-3.5" />
+ ) : (
+ <LuChevronRight className="h-3.5 w-3.5" />
+ )}
+ </button>
+ ) : (
+ <span className="h-5 w-5 shrink-0" aria-hidden />
+ )}
+ <ComponentColorSwatch color={group.color} />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate" title={group.name}>
+ {group.name}
+ </span>
+ {mapping?.item && (
+ <span
+ className={cn(
+ "truncate text-xs",
+ // Mismatch stands out via full-strength text + the explicit "≠"
+ // clause below — no colored status text (see .ai/ds-rules.md)
+ quantityMismatch ? "text-foreground" : "text-muted-foreground"
+ )}
+ title={mapping.item.name ?? undefined}
+ >
+ {mapping.item.readableIdWithRevision}
+ {quantityMismatch &&
+ bomLine &&
+ ` · BOM qty ${Math.round(bomLine.quantity)} ≠ model ${group.count}`}
+ </span>
+ )}
+ </div>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ {/* Ghost icon buttons sit flush together (no gap between them) */}
+ <div className="flex items-center">
+ <IconButton
+ aria-label={allHidden ? `Show ${group.name}` : `Hide ${group.name}`}
+ icon={allHidden ? <LuEyeOff /> : <LuEye />}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "focus:opacity-100",
+ // A group with any hidden instance keeps the eye visible as its
+ // status + control; fully-visible groups reveal it on hover.
+ hidden !== "none"
+ ? "opacity-100 text-muted-foreground"
+ : "opacity-0 group-hover:opacity-100"
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleHide();
+ }}
+ />
+ <Popover>
+ <PopoverTrigger asChild>
+ <IconButton
+ aria-label={`Component details: ${group.name}`}
+ icon={<LuSettings />}
+ variant="ghost"
+ size="sm"
+ className="opacity-0 group-hover:opacity-100 focus:opacity-100 data-[state=open]:opacity-100"
+ onClick={(event) => event.stopPropagation()}
+ />
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ className="w-72 text-sm"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <ComponentDetails
+ group={group}
+ usage={usage}
+ mapping={mapping}
+ bomMaterials={bomMaterials}
+ canMap={canMap}
+ modelUploadId={modelUploadId}
+ instructionId={instructionId}
+ onSelectStep={onSelectStep}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+ );
+}
+
+/** A single instance of an expanded group — selectable and hideable on its own. */
+function InstanceRow({
+ group,
+ instanceIndex,
+ isSelected,
+ isHidden,
+ style,
+ onClick,
+ onToggleHide
+}: {
+ group: ComponentGroup;
+ instanceIndex: number;
+ isSelected: boolean;
+ isHidden: boolean;
+ style: React.CSSProperties;
+ onClick: (event: MouseEvent) => void;
+ onToggleHide: () => void;
+}) {
+ const label = `${group.name} #${instanceIndex + 1}`;
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ style={style}
+ className={cn(
+ "group relative flex cursor-pointer select-none items-center gap-2 border-b border-border py-1 pl-9 pr-3 text-sm hover:bg-accent/30",
+ isSelected && "bg-blue-500/10 hover:bg-blue-500/10",
+ isHidden && "opacity-50"
+ )}
+ onClick={onClick}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onClick(event as unknown as MouseEvent);
+ }
+ }}
+ >
+ {isSelected && (
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-y-0 left-0 w-0.5 bg-blue-500"
+ />
+ )}
+ <ComponentColorSwatch color={group.color} />
+ <span
+ className="min-w-0 flex-1 truncate text-muted-foreground"
+ title={label}
+ >
+ {group.name}{" "}
+ <span className="tabular-nums text-foreground">
+ #{instanceIndex + 1}
+ </span>
+ </span>
+ <IconButton
+ aria-label={isHidden ? `Show ${label}` : `Hide ${label}`}
+ icon={isHidden ? <LuEyeOff /> : <LuEye />}
+ variant="ghost"
+ size="sm"
+ className={cn(
+ "focus:opacity-100",
+ isHidden
+ ? "opacity-100 text-muted-foreground"
+ : "opacity-0 group-hover:opacity-100"
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleHide();
+ }}
+ />
+ </div>
+ );
+}
+
+function ComponentDetails({
+ group,
+ usage,
+ mapping,
+ bomMaterials,
+ canMap,
+ modelUploadId,
+ instructionId,
+ onSelectStep
+}: {
+ group: ComponentGroup;
+ usage: { stepId: string; index: number; title: string }[];
+ mapping: AssemblyComponentMapping | null;
+ bomMaterials: FlattenedBomMaterial[];
+ canMap: boolean;
+ modelUploadId: string | null;
+ instructionId: string;
+ onSelectStep: (stepId: string) => void;
+}) {
+ const mapFetcher = useFetcher<{ success: boolean }>();
+ const size = [
+ group.bbox.max[0] - group.bbox.min[0],
+ group.bbox.max[1] - group.bbox.min[1],
+ group.bbox.max[2] - group.bbox.min[2]
+ ];
+
+ const onMap = (itemId: string) => {
+ if (!modelUploadId) return;
+ const formData = new FormData();
+ formData.append("modelUploadId", modelUploadId);
+ formData.append("geometryHash", group.key);
+ formData.append("itemId", itemId);
+ mapFetcher.submit(formData, {
+ method: "post",
+ action: path.to.newAssemblyComponentMapping(instructionId)
+ });
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <ComponentColorSwatch color={group.color} />
+ <p className="min-w-0 flex-1 truncate font-medium" title={group.name}>
+ {group.name}
+ </p>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ </div>
+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">
+ <dt className="text-muted-foreground">Size</dt>
+ <dd className="tabular-nums">
+ {size.map((dim) => formatLength(dim)).join(" × ")} mm
+ </dd>
+ <dt className="text-muted-foreground">Volume</dt>
+ <dd className="tabular-nums">{formatVolume(group.volume)}</dd>
+ </dl>
+ {bomMaterials.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <p className="text-xs text-muted-foreground">Bill of materials</p>
+ {mapping?.item ? (
+ <div className="flex items-center gap-2 text-xs">
+ <span className="min-w-0 flex-1 truncate">
+ {mapping.item.readableIdWithRevision} · {mapping.item.name}
+ </span>
+ {canMap && (
+ <IconButton
+ aria-label="Remove BOM mapping"
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ isDisabled={mapFetcher.state !== "idle"}
+ onClick={() => {
+ mapFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyComponentMapping(
+ instructionId,
+ mapping.id
+ )
+ });
+ }}
+ />
+ )}
+ </div>
+ ) : canMap ? (
+ <ul className="flex max-h-36 flex-col overflow-y-auto">
+ {bomMaterials.map((material) => (
+ <li key={`${material.itemId}-${material.depth}`}>
+ <button
+ type="button"
+ className="w-full truncate rounded-sm px-1 py-0.5 text-left text-xs hover:bg-accent disabled:opacity-50"
+ disabled={mapFetcher.state !== "idle"}
+ title={material.name ?? undefined}
+ onClick={() => onMap(material.itemId)}
+ >
+ <span className="text-muted-foreground tabular-nums mr-1">
+ ×{Math.round(material.quantity)}
+ </span>
+ {material.readableIdWithRevision} · {material.name}
+ </button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-muted-foreground">Not mapped</p>
+ )}
+ </div>
+ )}
+ <div className="flex flex-col gap-1">
+ <p className="text-xs text-muted-foreground">Used in steps</p>
+ {usage.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ Not referenced by any step
+ </p>
+ ) : (
+ <ul className="flex flex-col">
+ {usage.map((entry) => (
+ <li key={entry.stepId}>
+ <button
+ type="button"
+ className="w-full truncate rounded-sm px-1 py-0.5 text-left text-xs hover:bg-accent"
+ title={entry.title}
+ onClick={() => onSelectStep(entry.stepId)}
+ >
+ <span className="text-muted-foreground tabular-nums mr-1">
+ {entry.index + 1}.
+ </span>
+ {entry.title}
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function formatLength(mm: number): string {
+ return mm >= 100 ? mm.toFixed(0) : mm.toFixed(1);
+}
+
+function formatVolume(mm3: number | null): string {
+ if (mm3 === null) return "—";
+ if (mm3 >= 1000) return `${(mm3 / 1000).toFixed(1)} cm³`;
+ return `${mm3.toFixed(0)} mm³`;
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx
new file mode 100644
index 0000000000..05a3376a98
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx
@@ -0,0 +1,806 @@
+import {
+ Button,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Input,
+ Modal,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ useDebounce,
+ useInterval,
+ VStack
+} from "@carbon/react";
+import type { AssemblyGraphIndex } from "@carbon/viewer";
+import {
+ describeStep,
+ groupComponentNodeIds,
+ synthesizeFallbackMotion
+} from "@carbon/viewer";
+import type { DragControls } from "framer-motion";
+import { Reorder, useDragControls } from "framer-motion";
+import type { ReactNode } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ LuChevronDown,
+ LuCirclePlus,
+ LuEllipsisVertical,
+ LuGripVertical,
+ LuSearch,
+ LuSparkles,
+ LuTrash,
+ LuWaypoints
+} from "react-icons/lu";
+import { useFetcher, useParams, useRevalidator } from "react-router";
+import { Empty } from "~/components";
+import { ProcedureStepTypeIcon } from "~/components/Icons";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { isAssemblyPlanRunning } from "../../production.models";
+import type { FlattenedBomMaterial } from "../../production.service";
+import { toViewerStep } from "../../production.service";
+import type {
+ AssemblyComponentMapping,
+ AssemblyInstructionStepRow,
+ AssemblyUnit
+} from "../../types";
+import AssemblyBomTree from "./AssemblyBomTree";
+
+type AssemblyInstructionExplorerProps = {
+ steps: AssemblyInstructionStepRow[];
+ units: AssemblyUnit[];
+ selectedStepId: string | null;
+ isDisabled: boolean;
+ /** The CAD model is still being converted — block step generation until it lands */
+ isConverting: boolean;
+ graphIndex: AssemblyGraphIndex | null;
+ /** A successful motion plan exists for the model */
+ hasPlan: boolean;
+ /** Latest plan job in any state — drives the generate-steps wait UI */
+ planJob: {
+ id: string;
+ status: string;
+ error: string | null;
+ createdAt: string;
+ } | null;
+ modelUploadId: string | null;
+ componentMappings: AssemblyComponentMapping[];
+ bomMaterials: FlattenedBomMaterial[];
+ /** Current component selection (shared with the viewer) — highlighted in the Components tab */
+ selectedNodeIds: string[];
+ onSelectStep: (stepId: string) => void;
+ onHighlightComponents: (nodeIds: string[]) => void;
+ onHideComponents: (nodeIds: string[]) => void;
+};
+
+export default function AssemblyInstructionExplorer({
+ steps,
+ units,
+ selectedStepId,
+ isDisabled,
+ isConverting,
+ graphIndex,
+ hasPlan,
+ planJob,
+ modelUploadId,
+ componentMappings,
+ bomMaterials,
+ selectedNodeIds,
+ onSelectStep,
+ onHighlightComponents,
+ onHideComponents
+}: AssemblyInstructionExplorerProps) {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const permissions = usePermissions();
+ const revalidator = useRevalidator();
+
+ const sortOrderFetcher = useFetcher<{ success: boolean }>();
+ const newStepFetcher = useFetcher<{ success: boolean; id?: string }>();
+ const generateFetcher = useFetcher<{
+ success: boolean;
+ planning?: boolean;
+ }>();
+
+ // Generate Steps needs a motion plan. Planning is lazy (nothing runs until
+ // the user asks), so the first click usually lands before plan.json exists —
+ // the action then (idempotently) kicks the planner and returns
+ // planning:true. We hold the button in a pending state, poll until the plan
+ // lands, then generate the steps automatically — the click already
+ // expressed the intent.
+ const [isAwaitingPlan, setIsAwaitingPlan] = useState(false);
+
+ // Controlled so the Components tab knows when it becomes active — it scrolls the
+ // current selection into view on activation
+ const [tab, setTab] = useState<"steps" | "components">("steps");
+ // A pre-existing Failed job stays the latest row until the freshly
+ // triggered run inserts its own — remember it so it doesn't read as the
+ // outcome of the run we're waiting on.
+ const ignoredFailedJobId = useRef<string | null>(null);
+ const planFailed =
+ isAwaitingPlan &&
+ planJob?.status === "Failed" &&
+ planJob.id !== ignoredFailedJobId.current;
+
+ useEffect(() => {
+ if (generateFetcher.data?.planning) {
+ setIsAwaitingPlan(true);
+ } else if (generateFetcher.data?.success) {
+ setIsAwaitingPlan(false);
+ }
+ }, [generateFetcher.data]);
+
+ const [showRerunConfirm, setShowRerunConfirm] = useState(false);
+
+ // Poll while planning runs (awaiting-plan generate flow, or an explicit
+ // re-plan) so the fresh plan and its generated steps surface on their own
+ const isPlanning = isAssemblyPlanRunning(planJob);
+ useInterval(
+ () => revalidator.revalidate(),
+ (isAwaitingPlan && !hasPlan && !planFailed) || isPlanning ? 5000 : null
+ );
+
+ // Surface elapsed time while the planner runs so the wait shows a rough
+ // expectation and forward progress instead of an open-ended spinner. A plan
+ // runs server-side, so reflect a Processing plan job (isPlanning) too — the
+ // "solving" state must survive navigating away and back, when the ephemeral
+ // isAwaitingPlan flag is gone but the plan is still running.
+ const isSolving =
+ generateFetcher.state !== "idle" ||
+ (isAwaitingPlan && !planFailed) ||
+ (isPlanning && steps.length === 0);
+ const [solveStartedAt, setSolveStartedAt] = useState<number | null>(null);
+ const [solveNow, setSolveNow] = useState(() => Date.now());
+ useEffect(() => {
+ setSolveStartedAt((prev) => {
+ if (!isSolving) return null;
+ if (prev != null) return prev;
+ // Anchor elapsed to the plan job's real start when a plan is running, so
+ // the timer is accurate even after leaving and returning to the page.
+ if (isPlanning && planJob?.createdAt) {
+ return new Date(planJob.createdAt).getTime();
+ }
+ return Date.now();
+ });
+ }, [isSolving, isPlanning, planJob?.createdAt]);
+ useInterval(
+ () => setSolveNow(Date.now()),
+ solveStartedAt != null ? 1000 : null
+ );
+ const solveElapsedSeconds =
+ solveStartedAt != null
+ ? Math.max(0, Math.round((solveNow - solveStartedAt) / 1000))
+ : 0;
+ const solveElapsedLabel = `${Math.floor(solveElapsedSeconds / 60)}:${String(
+ solveElapsedSeconds % 60
+ ).padStart(2, "0")}`;
+
+ const rerunPlanFetcher = useFetcher<{ success: boolean }>();
+
+ // The user's click is waiting on a plan. When it lands, generate the steps —
+ // no second click. If the wait stalls with nothing running (the click raced
+ // the model conversion, and planning is no longer chained to conversion),
+ // re-submit so the action kicks the planner. Fetcher "idle" implies the
+ // post-action revalidation is done, so isPlanning/isConverting are fresh.
+ useEffect(() => {
+ if (!isAwaitingPlan || generateFetcher.state !== "idle") return;
+ if (hasPlan) {
+ setIsAwaitingPlan(false);
+ } else if (isConverting || isPlanning || planFailed) {
+ return;
+ }
+ generateFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.generateAssemblyInstructionSteps(id)
+ });
+ }, [
+ isAwaitingPlan,
+ hasPlan,
+ isConverting,
+ isPlanning,
+ planFailed,
+ generateFetcher,
+ id
+ ]);
+
+ const [stepToDelete, setStepToDelete] =
+ useState<AssemblyInstructionStepRow | null>(null);
+
+ const [sortOrder, setSortOrder] = useState<string[]>(
+ steps.map((step) => step.id)
+ );
+
+ useEffect(() => {
+ setSortOrder(steps.map((step) => step.id));
+ }, [steps]);
+
+ // Select the newly created step
+ useEffect(() => {
+ if (newStepFetcher.data?.success && newStepFetcher.data.id) {
+ onSelectStep(newStepFetcher.data.id);
+ }
+ }, [newStepFetcher.data, onSelectStep]);
+
+ const stepMap = useMemo(
+ () =>
+ steps.reduce<Record<string, AssemblyInstructionStepRow>>(
+ (acc, step) => ({ ...acc, [step.id]: step }),
+ {}
+ ),
+ [steps]
+ );
+
+ // Authored subassembly units, normalized for step-title derivation: a step
+ // whose components are exactly a unit is titled by its name, not by every component.
+ const namedUnits = useMemo(
+ () =>
+ units.map((unit) => ({
+ name: unit.name,
+ componentNodeIds: unit.componentNodeIds ?? []
+ })),
+ [units]
+ );
+
+ const stepTitles = useMemo(
+ () =>
+ new Map(
+ steps.map((step) => [
+ step.id,
+ describeStep(toViewerStep(step), graphIndex, namedUnits) ??
+ "Untitled step"
+ ])
+ ),
+ [steps, graphIndex, namedUnits]
+ );
+
+ const [search, setSearch] = useState("");
+ const isSearching = search.trim().length > 0;
+
+ /** stepId → lowercase haystack of title, component names, and fastener spec */
+ const searchText = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const step of steps) {
+ const viewerStep = toViewerStep(step);
+ const componentNames = graphIndex
+ ? groupComponentNodeIds(viewerStep.componentNodeIds, graphIndex)
+ .map((group) => group.name)
+ .join(" ")
+ : "";
+ map.set(
+ step.id,
+ [
+ step.title ?? "",
+ stepTitles.get(step.id) ?? "",
+ componentNames,
+ viewerStep.fastener?.spec ?? "",
+ step.instructionText ?? ""
+ ]
+ .join(" ")
+ .toLowerCase()
+ );
+ }
+ return map;
+ }, [steps, graphIndex, stepTitles]);
+
+ const visibleOrder = useMemo(() => {
+ if (!isSearching) return sortOrder;
+ const needle = search.trim().toLowerCase();
+ return sortOrder.filter((stepId) =>
+ searchText.get(stepId)?.includes(needle)
+ );
+ }, [sortOrder, isSearching, search, searchText]);
+
+ const updateSortOrder = useDebounce(
+ (updates: Record<string, number>) => {
+ const formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStepOrder(id)
+ });
+ },
+ 2500,
+ true
+ );
+
+ const onReorder = (newOrder: string[]) => {
+ if (isDisabled || isSearching) return;
+
+ const updates: Record<string, number> = {};
+ newOrder.forEach((stepId, index) => {
+ updates[stepId] = index + 1;
+ });
+ setSortOrder(newOrder);
+ updateSortOrder(updates);
+ };
+
+ const onAddStep = () => {
+ const formData = new FormData();
+ formData.append("assemblyInstructionId", id);
+
+ // When components are selected, seed the new step with the components and a
+ // basic synthesized insertion animation. Otherwise create an empty
+ // process-only step. The title is left blank on purpose — it derives live
+ // from the components (describeStep) everywhere it is displayed.
+ if (selectedNodeIds.length > 0) {
+ // The new step appends after every existing step, so its obstacle world
+ // is everything those steps install ("none" fades in when blocked)
+ const present = new Set(
+ steps.flatMap((step) => step.componentNodeIds ?? [])
+ );
+ const motion = graphIndex
+ ? synthesizeFallbackMotion(graphIndex, selectedNodeIds, present)
+ : null;
+ formData.append("componentNodeIds", JSON.stringify(selectedNodeIds));
+ formData.append("motion", JSON.stringify(motion ?? { type: "none" }));
+ } else {
+ formData.append("motion", JSON.stringify({ type: "none" }));
+ }
+
+ newStepFetcher.submit(formData, {
+ method: "post",
+ action: path.to.newAssemblyInstructionStep(id)
+ });
+ };
+
+ return (
+ <>
+ <Tabs
+ value={tab}
+ onValueChange={(value) => setTab(value as "steps" | "components")}
+ className="flex h-[calc(100dvh-99px)] w-full flex-col"
+ >
+ <TabsList className="w-auto flex-none gap-1 mx-3 mt-3">
+ <TabsTrigger className="flex-1" value="steps">
+ Steps
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="components">
+ Components
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent
+ value="steps"
+ className="flex min-h-0 flex-1 flex-col justify-between"
+ >
+ {steps.length > 0 && (
+ <div className="relative w-full flex-none border-b border-border px-2 py-1.5">
+ <LuSearch className="pointer-events-none absolute left-4 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ aria-label="Search steps"
+ placeholder="Search steps"
+ size="sm"
+ className="pl-7"
+ value={search}
+ onChange={(searchEvent) => setSearch(searchEvent.target.value)}
+ />
+ </div>
+ )}
+ <VStack
+ className="w-full flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent"
+ spacing={0}
+ >
+ {steps.length > 0 ? (
+ <Reorder.Group
+ axis="y"
+ values={visibleOrder}
+ onReorder={onReorder}
+ className="w-full"
+ disabled={isDisabled || isSearching}
+ >
+ {visibleOrder.map((stepId) => (
+ <DraggableStepItem
+ key={stepId}
+ stepId={stepId}
+ isDisabled={isDisabled || isSearching}
+ >
+ {(dragControls) => (
+ <StepItem
+ step={stepMap[stepId]}
+ title={stepTitles.get(stepId) ?? "Untitled step"}
+ index={sortOrder.indexOf(stepId)}
+ isDisabled={isDisabled || isSearching}
+ isSelected={stepId === selectedStepId}
+ dragControls={dragControls}
+ onSelect={() => onSelectStep(stepId)}
+ onDelete={() => setStepToDelete(stepMap[stepId])}
+ />
+ )}
+ </DraggableStepItem>
+ ))}
+ </Reorder.Group>
+ ) : (
+ <Empty>
+ {permissions.can("update", "production") && (
+ <VStack spacing={2} className="items-center">
+ <Button
+ isDisabled={isDisabled || isConverting || isSolving}
+ isLoading={isSolving}
+ leftIcon={<LuSparkles />}
+ onClick={() => {
+ // The action starts a fresh planner run when the
+ // latest one failed — don't read that stale failure
+ // as this run's outcome
+ ignoredFailedJobId.current =
+ planJob?.status === "Failed" ? planJob.id : null;
+ setIsAwaitingPlan(false);
+ generateFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.generateAssemblyInstructionSteps(id)
+ });
+ }}
+ >
+ {planFailed ? "Retry Generate Steps" : "Generate Steps"}
+ </Button>
+ <p className="max-w-[220px] text-center text-xs text-muted-foreground">
+ {planFailed
+ ? (planJob?.error ??
+ "Motion planning failed — retry to run it again")
+ : isSolving
+ ? `Solving assembly motions from the model's geometry — this usually takes 1–3 minutes (${solveElapsedLabel} elapsed)`
+ : hasPlan
+ ? "Creates draft steps with motions solved from the model's geometry"
+ : "Runs the motion planner over the model, then creates draft steps"}
+ </p>
+ <Button
+ isDisabled={isDisabled}
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={onAddStep}
+ >
+ Add Step Manually
+ </Button>
+ </VStack>
+ )}
+ </Empty>
+ )}
+ {steps.length > 0 && isSearching && visibleOrder.length === 0 && (
+ <p className="w-full px-4 py-3 text-center text-xs text-muted-foreground">
+ No steps match "{search.trim()}"
+ </p>
+ )}
+ </VStack>
+ {steps.length > 0 && (
+ <div className="w-full flex-none border-t border-border p-4">
+ {steps.length > 0 &&
+ modelUploadId &&
+ permissions.can("update", "production") && (
+ <Button
+ className="mb-2 w-full"
+ isDisabled={
+ isDisabled ||
+ isPlanning ||
+ rerunPlanFetcher.state !== "idle"
+ }
+ isLoading={isPlanning || rerunPlanFetcher.state !== "idle"}
+ leftIcon={<LuWaypoints />}
+ variant="secondary"
+ onClick={() => setShowRerunConfirm(true)}
+ >
+ {isPlanning ? "Planning motion…" : "Run Motion Planning"}
+ </Button>
+ )}
+ <Button
+ className="w-full"
+ isDisabled={
+ isDisabled ||
+ !permissions.can("update", "production") ||
+ newStepFetcher.state !== "idle"
+ }
+ isLoading={newStepFetcher.state !== "idle"}
+ leftIcon={<LuCirclePlus />}
+ variant="secondary"
+ onClick={onAddStep}
+ >
+ Add Step
+ </Button>
+ </div>
+ )}
+ </TabsContent>
+ {/* forceMount keeps the BOM selection (and viewer highlight) alive across tab switches */}
+ <TabsContent
+ value="components"
+ forceMount
+ className="min-h-0 flex-1 data-[state=inactive]:hidden"
+ >
+ <AssemblyBomTree
+ graphIndex={graphIndex}
+ steps={steps}
+ units={units}
+ isDisabled={isDisabled}
+ modelUploadId={modelUploadId}
+ componentMappings={componentMappings}
+ bomMaterials={bomMaterials}
+ selectedNodeIds={selectedNodeIds}
+ isActive={tab === "components"}
+ isAddingStep={newStepFetcher.state !== "idle"}
+ onHighlightComponents={onHighlightComponents}
+ onHideComponents={onHideComponents}
+ onSelectStep={onSelectStep}
+ onAddStep={onAddStep}
+ />
+ </TabsContent>
+ </Tabs>
+ {stepToDelete && (
+ <ConfirmDelete
+ action={path.to.deleteAssemblyInstructionStep(id, stepToDelete.id)}
+ name={stepTitles.get(stepToDelete.id) ?? "this step"}
+ text={`Are you sure you want to delete the step: ${
+ stepTitles.get(stepToDelete.id) ?? stepToDelete.id
+ }? This cannot be undone.`}
+ onCancel={() => setStepToDelete(null)}
+ onSubmit={() => setStepToDelete(null)}
+ />
+ )}
+ {showRerunConfirm && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) setShowRerunConfirm(false);
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Run motion planning?</ModalTitle>
+ <ModalDescription>
+ Recomputes how each step's components move into place, using the
+ current step order and avoiding collisions with components from
+ earlier steps. Steps you've marked Done are left as-is.
+ </ModalDescription>
+ </ModalHeader>
+ <ModalFooter>
+ <Button
+ variant="secondary"
+ onClick={() => setShowRerunConfirm(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ isDisabled={rerunPlanFetcher.state !== "idle"}
+ isLoading={rerunPlanFetcher.state !== "idle"}
+ onClick={() => {
+ rerunPlanFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.assemblyPlanRerun(id)
+ });
+ setShowRerunConfirm(false);
+ }}
+ >
+ Run
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+}
+
+const stepStatusOrder = ["Todo", "Review", "Done"] as const;
+type StepStatus = (typeof stepStatusOrder)[number];
+
+const stepStatusStyles: Record<StepStatus, string> = {
+ Todo: "bg-red-500",
+ Review: "bg-yellow-500",
+ Done: "bg-green-500"
+};
+
+const StepStatusDot = ({ status }: { status: StepStatus }) => (
+ <span
+ className={cn(
+ "block size-2 shrink-0 rounded-full",
+ stepStatusStyles[status] ?? stepStatusStyles.Todo
+ )}
+ />
+);
+
+function StepStatusControl({
+ stepId,
+ status,
+ isDisabled
+}: {
+ stepId: string;
+ status: StepStatus;
+ isDisabled: boolean;
+}) {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const fetcher = useFetcher<{ success: boolean }>();
+
+ // Optimistic: show the in-flight status while the fetcher is busy
+ const displayed =
+ fetcher.state !== "idle" && fetcher.formData
+ ? ((fetcher.formData.get("status") as StepStatus) ?? status)
+ : status;
+
+ const onSelect = (value: string) => {
+ if (value === status) return;
+ const formData = new FormData();
+ formData.append("status", value);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStepStatus(id, stepId)
+ });
+ };
+
+ // Non-interactive: a labeled chip so the status is legible without the dot
+ // color code (published/archived instructions can't be edited)
+ if (isDisabled) {
+ return (
+ <span className="inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md border border-border px-1.5 text-xs text-foreground">
+ <StepStatusDot status={displayed} />
+ {displayed}
+ </span>
+ );
+ }
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Step status: ${displayed}. Change status`}
+ className="inline-flex h-6 shrink-0 items-center gap-1.5 rounded-md border border-border bg-card px-1.5 text-xs text-foreground shadow-button-base hover:bg-accent focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.98]"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <StepStatusDot status={displayed} />
+ {displayed}
+ <LuChevronDown className="size-3 text-muted-foreground" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="min-w-[8rem]"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <DropdownMenuRadioGroup value={displayed} onValueChange={onSelect}>
+ {stepStatusOrder.map((option) => (
+ <DropdownMenuRadioItem key={option} value={option}>
+ <span className="flex items-center gap-2">
+ <StepStatusDot status={option} />
+ {option}
+ </span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function DraggableStepItem({
+ stepId,
+ isDisabled,
+ children
+}: {
+ stepId: string;
+ isDisabled: boolean;
+ children: (dragControls: DragControls) => ReactNode;
+}) {
+ const dragControls = useDragControls();
+ return (
+ <Reorder.Item
+ key={stepId}
+ value={stepId}
+ dragListener={false}
+ dragControls={dragControls}
+ >
+ {children(dragControls)}
+ </Reorder.Item>
+ );
+}
+
+type StepItemProps = {
+ step?: AssemblyInstructionStepRow;
+ title: string;
+ index: number;
+ isDisabled: boolean;
+ isSelected: boolean;
+ dragControls?: DragControls;
+ onSelect: () => void;
+ onDelete: () => void;
+};
+
+function StepItem({
+ step,
+ title,
+ index,
+ isDisabled,
+ isSelected,
+ dragControls,
+ onSelect,
+ onDelete
+}: StepItemProps) {
+ const permissions = usePermissions();
+ if (!step) return null;
+
+ const componentCount = step.componentNodeIds?.length ?? 0;
+
+ return (
+ <HStack
+ className={cn(
+ "group w-full p-2 items-start hover:bg-accent/30 relative border-b bg-card cursor-pointer",
+ isSelected && "bg-accent/50 hover:bg-accent/50"
+ )}
+ onClick={onSelect}
+ >
+ <IconButton
+ aria-label="Drag handle"
+ icon={<LuGripVertical />}
+ variant="ghost"
+ disabled={isDisabled}
+ className="cursor-grab active:cursor-grabbing shrink-0"
+ onPointerDown={(e) => {
+ if (!isDisabled && dragControls) dragControls.start(e);
+ }}
+ style={{ touchAction: "none" }}
+ />
+ <VStack spacing={2} className="flex-grow min-w-0">
+ <p className="text-foreground text-sm w-full min-w-0 line-clamp-1">
+ <span className="text-muted-foreground tabular-nums mr-2">
+ {index + 1}.
+ </span>
+ {title}
+ </p>
+ <HStack spacing={2}>
+ <ProcedureStepTypeIcon
+ type={step.type ?? "Task"}
+ className="shrink-0 size-3.5 text-muted-foreground"
+ />
+ <StepStatusControl
+ stepId={step.id}
+ status={step.status ?? "Todo"}
+ isDisabled={isDisabled}
+ />
+ <p className="text-muted-foreground text-xs">
+ {componentCount} component{componentCount === 1 ? "" : "s"}
+ </p>
+ </HStack>
+ </VStack>
+ {!isDisabled && (
+ <div className="absolute right-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ className="opacity-0 group-hover:opacity-100 group-active:opacity-100 data-[state=open]:opacity-100"
+ icon={<LuEllipsisVertical />}
+ variant="solid"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ destructive
+ disabled={!permissions.can("delete", "production")}
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete();
+ }}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Step
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
+ </HStack>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx
new file mode 100644
index 0000000000..86e7536d08
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionForm.tsx
@@ -0,0 +1,209 @@
+import { useCarbon } from "@carbon/auth";
+import { ValidatedForm } from "@carbon/form";
+import {
+ Alert,
+ AlertDescription,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ VStack
+} from "@carbon/react";
+import { useCallback, useEffect, useState } from "react";
+import { LuCircleCheck, LuInfo, LuTriangleAlert } from "react-icons/lu";
+import type { z } from "zod";
+import { Hidden, Item, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import {
+ assemblyInstructionFromItemValidator,
+ getAssemblyModelState
+} from "../../production.models";
+
+type ModelStatus =
+ | { state: "idle" }
+ | { state: "loading" }
+ | { state: "converted"; label: string }
+ | { state: "convertible" }
+ | { state: "processing" }
+ | { state: "failed"; error: string | null }
+ | { state: "none" };
+
+type AssemblyInstructionFormProps = {
+ initialValues: z.infer<typeof assemblyInstructionFromItemValidator>;
+ open?: boolean;
+ onClose: () => void;
+};
+
+const AssemblyInstructionForm = ({
+ initialValues,
+ open = true,
+ onClose
+}: AssemblyInstructionFormProps) => {
+ const permissions = usePermissions();
+ const { carbon } = useCarbon();
+
+ const [modelStatus, setModelStatus] = useState<ModelStatus>({
+ state: "idle"
+ });
+
+ // Mirrors getModelForItem on the server: conversion is lazy, so any STEP
+ // model is usable — the state just tells the user what will happen on save
+ const checkModel = useCallback(
+ async (itemId: string) => {
+ if (!carbon || !itemId) {
+ setModelStatus({ state: "idle" });
+ return;
+ }
+ setModelStatus({ state: "loading" });
+
+ const { data: item } = await carbon
+ .from("item")
+ .select("modelUploadId")
+ .eq("id", itemId)
+ .maybeSingle();
+
+ if (!item?.modelUploadId) {
+ setModelStatus({ state: "none" });
+ return;
+ }
+
+ const { data: model } = await carbon
+ .from("modelUpload")
+ .select(
+ "id, name, componentCount, processingStatus, processingError, glbPath, graphPath, modelPath"
+ )
+ .eq("id", item.modelUploadId)
+ .maybeSingle();
+
+ const state = getAssemblyModelState(model ?? null);
+ switch (state) {
+ case "converted": {
+ const name = model!.name ?? "Model";
+ setModelStatus({
+ state,
+ label:
+ typeof model!.componentCount === "number"
+ ? `${name} (${model!.componentCount} components)`
+ : name
+ });
+ break;
+ }
+ case "failed":
+ setModelStatus({ state, error: model!.processingError });
+ break;
+ default:
+ setModelStatus({ state });
+ }
+ },
+ [carbon]
+ );
+
+ useEffect(() => {
+ if (initialValues.itemId) checkModel(initialValues.itemId);
+ }, [initialValues.itemId, checkModel]);
+
+ const isDisabled =
+ !permissions.can("create", "production") ||
+ ["idle", "loading", "none"].includes(modelStatus.state);
+
+ return (
+ <ModalDrawerProvider type="modal">
+ <ModalDrawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={assemblyInstructionFromItemValidator}
+ method="post"
+ action={path.to.newAssemblyInstruction}
+ defaultValues={initialValues}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>New Assembly Instruction</ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <VStack spacing={4}>
+ {modelStatus.state === "convertible" && (
+ <Alert variant="info">
+ <LuInfo />
+ <AlertDescription>
+ This model will be converted for assembly instructions
+ when you save. This can take a minute.
+ </AlertDescription>
+ </Alert>
+ )}
+ {modelStatus.state === "processing" && (
+ <Alert variant="info">
+ <LuInfo />
+ <AlertDescription>
+ Model conversion is in progress. You can save now — the
+ model will appear once conversion finishes.
+ </AlertDescription>
+ </Alert>
+ )}
+ {modelStatus.state === "failed" && (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertDescription>
+ {modelStatus.error
+ ? `Previous model conversion failed: ${modelStatus.error}. Saving will retry.`
+ : "Previous model conversion failed. Saving will retry."}
+ </AlertDescription>
+ </Alert>
+ )}
+ {modelStatus.state === "none" && (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertDescription>
+ This item has no 3D model. Upload a STEP file on the
+ item's Model tab first.
+ </AlertDescription>
+ </Alert>
+ )}
+ <VStack spacing={1} className="w-full">
+ <Item
+ name="itemId"
+ label="Item"
+ type="Item"
+ replenishmentSystem="Make"
+ onChange={(selected) => {
+ checkModel(selected?.value ?? "");
+ }}
+ />
+ {modelStatus.state === "loading" && (
+ <p className="text-xs text-muted-foreground">
+ Checking for a 3D model…
+ </p>
+ )}
+ {modelStatus.state === "converted" && (
+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <LuCircleCheck className="h-3.5 w-3.5 shrink-0" />
+ Model: {modelStatus.label}
+ </p>
+ )}
+ </VStack>
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default AssemblyInstructionForm;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx
new file mode 100644
index 0000000000..0a54ddb57a
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx
@@ -0,0 +1,219 @@
+import {
+ Badge,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Input,
+ useDisclosure
+} from "@carbon/react";
+import { useState } from "react";
+import {
+ LuBlocks,
+ LuEllipsisVertical,
+ LuPanelLeft,
+ LuPanelRight,
+ LuTrash
+} from "react-icons/lu";
+import { Link, useFetcher, useParams } from "react-router";
+import { usePanels } from "~/components/Layout";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import {
+ useDateFormatter,
+ usePermissions,
+ useRouteData,
+ useUser
+} from "~/hooks";
+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import type { MethodItemType } from "~/modules/shared";
+import { useItems } from "~/stores";
+import { path } from "~/utils/path";
+import type { assemblyInstructionStatuses } from "../../production.models";
+import type { AssemblyInstruction } from "../../types";
+import AssemblyInstructionStatus from "./AssemblyInstructionStatus";
+
+const itemTypesWithDetails = ["Part", "Material", "Tool", "Consumable"];
+
+const AssemblyInstructionHeader = () => {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
+ const routeData = useRouteData<{
+ instruction: AssemblyInstruction;
+ }>(path.to.assemblyInstruction(id));
+ const instruction = routeData?.instruction;
+
+ const permissions = usePermissions();
+ const user = useUser();
+ const { formatRelativeTime } = useDateFormatter();
+ const { toggleExplorer, toggleProperties } = usePanels();
+ const deleteDisclosure = useDisclosure();
+
+ const nameFetcher = useFetcher<{}>();
+ const statusFetcher = useFetcher<{}>();
+
+ const [name, setName] = useState(instruction?.name ?? "");
+
+ const isDraft = instruction?.status === "Draft";
+ const canUpdate = permissions.can("update", "production");
+
+ const [items] = useItems();
+ const item = instruction?.itemId
+ ? items.find((i) => i.id === instruction.itemId)
+ : undefined;
+
+ const onUpdateName = (value: string) => {
+ if (!instruction || !value.trim() || value === instruction.name) return;
+ const formData = new FormData();
+ formData.append("name", value);
+ formData.append("modelUploadId", instruction.modelUploadId);
+ if (instruction.itemId) formData.append("itemId", instruction.itemId);
+ nameFetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstruction(id)
+ });
+ };
+
+ const onStatusChange = (
+ status: (typeof assemblyInstructionStatuses)[number]
+ ) => {
+ const formData = new FormData();
+ formData.append("status", status);
+ statusFetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStatus(id)
+ });
+ };
+
+ return (
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
+ <HStack className="flex-grow" spacing={1}>
+ <IconButton
+ aria-label="Toggle Explorer"
+ icon={<LuPanelLeft />}
+ onClick={toggleExplorer}
+ variant="ghost"
+ />
+ <Input
+ className="mr-2 w-auto min-w-0 max-w-[320px] font-semibold text-foreground field-sizing-content"
+ value={name}
+ borderless
+ onChange={
+ isDraft && canUpdate ? (e) => setName(e.target.value) : undefined
+ }
+ onBlur={
+ isDraft && canUpdate
+ ? (e) => onUpdateName(e.target.value)
+ : undefined
+ }
+ />
+ <AssemblyInstructionStatus status={instruction?.status} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {item && itemTypesWithDetails.includes(item.type) && (
+ <DropdownMenuItem asChild>
+ <Link
+ to={getLinkToItemDetails(
+ item.type as MethodItemType,
+ item.id
+ )}
+ >
+ <DropdownMenuIcon icon={<LuBlocks />} />
+ View Item Master
+ </Link>
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ disabled={
+ !permissions.can("delete", "production") ||
+ !permissions.is("employee")
+ }
+ destructive
+ onClick={deleteDisclosure.onOpen}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Instruction
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {instruction && (
+ <Badge variant="outline" className="shrink-0 tabular-nums">
+ Edit {instruction.version}
+ </Badge>
+ )}
+ {instruction && (
+ <span className="hidden whitespace-nowrap text-xs text-muted-foreground lg:inline">
+ {instruction.createdBy === user.id ? "By you · " : ""}
+ edited{" "}
+ {formatRelativeTime(instruction.updatedAt ?? instruction.createdAt)}
+ </span>
+ )}
+ </HStack>
+ <div className="flex flex-shrink-0 gap-2 items-center justify-end">
+ {instruction?.status === "Draft" && (
+ <Button
+ isDisabled={!canUpdate}
+ isLoading={statusFetcher.state !== "idle"}
+ onClick={() => onStatusChange("Published")}
+ >
+ Publish
+ </Button>
+ )}
+ {instruction?.status === "Published" && (
+ <Button
+ variant="secondary"
+ isDisabled={!canUpdate}
+ isLoading={statusFetcher.state !== "idle"}
+ onClick={() => onStatusChange("Archived")}
+ >
+ Archive
+ </Button>
+ )}
+ {instruction?.status === "Archived" && (
+ <Button
+ variant="secondary"
+ isDisabled={!canUpdate}
+ isLoading={statusFetcher.state !== "idle"}
+ onClick={() => onStatusChange("Draft")}
+ >
+ Restore to Draft
+ </Button>
+ )}
+ <IconButton
+ aria-label="Toggle Properties"
+ icon={<LuPanelRight />}
+ onClick={toggleProperties}
+ variant="ghost"
+ />
+ </div>
+ {deleteDisclosure.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteAssemblyInstruction(id)}
+ isOpen={deleteDisclosure.isOpen}
+ name={instruction?.name ?? "assembly instruction"}
+ text={`Are you sure you want to delete ${instruction?.name}? This cannot be undone.`}
+ onCancel={() => {
+ deleteDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ deleteDisclosure.onClose();
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+export default AssemblyInstructionHeader;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
new file mode 100644
index 0000000000..d6b23b4402
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx
@@ -0,0 +1,610 @@
+import { useCarbon } from "@carbon/auth";
+import {
+ Array as ArrayInput,
+ Boolean as BooleanInput,
+ Hidden,
+ Input,
+ Number,
+ SelectControlled,
+ Submit,
+ ValidatedForm
+} from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import {
+ Badge,
+ Button,
+ cn,
+ HStack,
+ IconButton,
+ Label,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ toast,
+ VStack
+} from "@carbon/react";
+import { Editor } from "@carbon/react/Editor";
+import type { AssemblyGraphIndex, NamedUnit } from "@carbon/viewer";
+import { describeStep, groupComponentNodeIds } from "@carbon/viewer";
+import { nanoid } from "nanoid";
+import { useMemo, useState } from "react";
+import { LuCirclePlus, LuX } from "react-icons/lu";
+import { useFetcher, useParams } from "react-router";
+import { Empty } from "~/components";
+import { UnitOfMeasure } from "~/components/Form";
+import { ProcedureStepTypeIcon } from "~/components/Icons";
+import { usePermissions, useUser } from "~/hooks";
+import { procedureStepType } from "~/modules/shared";
+import { getPrivateUrl, path } from "~/utils/path";
+import {
+ assemblyInstructionStepValidator,
+ fastenerSchema,
+ stepPlanWarningsSchema
+} from "../../production.models";
+import type { FlattenedBomMaterial } from "../../production.service";
+import type {
+ AssemblyInstructionStepRow,
+ AssemblyStandardNote,
+ AssemblyStepMaterial,
+ AssemblyStepRequirement
+} from "../../types";
+import AssemblyStepBom, { ComponentColorSwatch } from "./AssemblyStepBom";
+import AssemblyStepMaterials from "./AssemblyStepMaterials";
+import AssemblyStepRequirements from "./AssemblyStepRequirements";
+
+type AssemblyInstructionPropertiesProps = {
+ step: AssemblyInstructionStepRow | null;
+ draftComponentNodeIds: string[] | null;
+ /** Current viewer/Components-panel selection — marks the matching component rows */
+ selectedNodeIds: string[];
+ /** Add-mode is on — picking components appends them to this step */
+ isAddingComponents: boolean;
+ isDisabled: boolean;
+ graphIndex: AssemblyGraphIndex | null;
+ /** Authored subassembly units — a step matching one is titled by its name. */
+ units: NamedUnit[];
+ requirements: AssemblyStepRequirement[];
+ stepMaterials: AssemblyStepMaterial[];
+ bomMaterials: FlattenedBomMaterial[];
+ standardNotes: AssemblyStandardNote[];
+ onSelectComponents: (nodeIds: string[]) => void;
+ onStartAddComponents: () => void;
+ onStopAddComponents: () => void;
+ onRemoveComponents: (nodeIds: string[]) => void;
+ /** The active step's motion path is open in the 3D editor */
+ isEditingMotion: boolean;
+ onEditMotion: (stepId: string) => void;
+ onStopEditMotion: () => void;
+ onSetCamera: (stepId: string) => void;
+ onClearCamera: (stepId: string) => void;
+};
+
+const AssemblyInstructionProperties = ({
+ step,
+ draftComponentNodeIds,
+ selectedNodeIds,
+ isAddingComponents,
+ isDisabled,
+ graphIndex,
+ units,
+ requirements,
+ stepMaterials,
+ bomMaterials,
+ standardNotes,
+ onSelectComponents,
+ onStartAddComponents,
+ onStopAddComponents,
+ onRemoveComponents,
+ isEditingMotion,
+ onEditMotion,
+ onStopEditMotion,
+ onSetCamera,
+ onClearCamera
+}: AssemblyInstructionPropertiesProps) => {
+ const { id: instructionId } = useParams();
+ if (!instructionId) throw new Error("Could not find id");
+
+ return (
+ <VStack
+ spacing={4}
+ className="w-[450px] bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"
+ >
+ <VStack spacing={2}>
+ <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ Step
+ </h3>
+ </VStack>
+ {step ? (
+ <Tabs defaultValue="details" className="w-full">
+ <TabsList className="w-full mb-4">
+ <TabsTrigger className="flex-1" value="details">
+ Details
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="bom">
+ BOM
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="requirements">
+ Requirements
+ </TabsTrigger>
+ </TabsList>
+ {/* forceMount keeps unsaved form edits alive while the BOM tab is open */}
+ <TabsContent
+ value="details"
+ forceMount
+ className="data-[state=inactive]:hidden"
+ >
+ <StepForm
+ key={step.id}
+ step={step}
+ draftComponentNodeIds={draftComponentNodeIds}
+ selectedNodeIds={selectedNodeIds}
+ isAddingComponents={isAddingComponents}
+ isDisabled={isDisabled}
+ graphIndex={graphIndex}
+ units={units}
+ onSelectComponents={onSelectComponents}
+ onStartAddComponents={onStartAddComponents}
+ onStopAddComponents={onStopAddComponents}
+ onRemoveComponents={onRemoveComponents}
+ isEditingMotion={isEditingMotion}
+ onEditMotion={onEditMotion}
+ onStopEditMotion={onStopEditMotion}
+ onSetCamera={onSetCamera}
+ onClearCamera={onClearCamera}
+ />
+ </TabsContent>
+ <TabsContent value="bom">
+ <VStack spacing={4} className="w-full py-2">
+ <AssemblyStepMaterials
+ stepId={step.id}
+ instructionId={instructionId}
+ materials={stepMaterials}
+ bomMaterials={bomMaterials}
+ isDisabled={isDisabled}
+ />
+ <AssemblyStepBom
+ componentNodeIds={
+ draftComponentNodeIds ?? step.componentNodeIds ?? []
+ }
+ graphIndex={graphIndex}
+ />
+ </VStack>
+ </TabsContent>
+ <TabsContent value="requirements">
+ <AssemblyStepRequirements
+ stepId={step.id}
+ instructionId={instructionId}
+ requirements={requirements}
+ standardNotes={standardNotes}
+ isDisabled={isDisabled}
+ />
+ </TabsContent>
+ </Tabs>
+ ) : (
+ <Empty className="border-none">Select a step to edit it</Empty>
+ )}
+ </VStack>
+ );
+};
+
+export default AssemblyInstructionProperties;
+
+function StepForm({
+ step,
+ draftComponentNodeIds,
+ selectedNodeIds,
+ isAddingComponents,
+ isDisabled,
+ graphIndex,
+ units,
+ onSelectComponents,
+ onStartAddComponents,
+ onStopAddComponents,
+ onRemoveComponents,
+ isEditingMotion,
+ onEditMotion,
+ onStopEditMotion,
+ onSetCamera,
+ onClearCamera
+}: {
+ step: AssemblyInstructionStepRow;
+ draftComponentNodeIds: string[] | null;
+ selectedNodeIds: string[];
+ isAddingComponents: boolean;
+ isDisabled: boolean;
+ graphIndex: AssemblyGraphIndex | null;
+ units: NamedUnit[];
+ onSelectComponents: (nodeIds: string[]) => void;
+ onStartAddComponents: () => void;
+ onStopAddComponents: () => void;
+ onRemoveComponents: (nodeIds: string[]) => void;
+ isEditingMotion: boolean;
+ onEditMotion: (stepId: string) => void;
+ onStopEditMotion: () => void;
+ onSetCamera: (stepId: string) => void;
+ onClearCamera: (stepId: string) => void;
+}) {
+ const { id: instructionId } = useParams();
+ if (!instructionId) throw new Error("Could not find id");
+
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{ success: boolean }>();
+ const { carbon } = useCarbon();
+ const {
+ company: { id: companyId }
+ } = useUser();
+
+ const [stepType, setStepType] = useState<(typeof procedureStepType)[number]>(
+ step.type ?? "Task"
+ );
+ const [description, setDescription] = useState<JSONContent>(
+ (step.description as JSONContent) ?? {}
+ );
+
+ const typeOptions = useMemo(
+ () =>
+ procedureStepType.map((type) => ({
+ label: (
+ <HStack>
+ <ProcedureStepTypeIcon type={type} className="mr-2" />
+ {type}
+ </HStack>
+ ),
+ value: type
+ })),
+ []
+ );
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/assembly/${instructionId}/${nanoid()}.${fileType}`;
+
+ const result = await carbon?.storage.from("private").upload(fileName, file);
+
+ if (result?.error) {
+ toast.error("Failed to upload image");
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return getPrivateUrl(result.data.path);
+ };
+
+ const componentNodeIds = draftComponentNodeIds ?? step.componentNodeIds ?? [];
+
+ const cannotSave = isDisabled || !permissions.can("update", "production");
+
+ const hasCamera = step.camera != null;
+
+ // Title shown when the title field is left blank — derived from the components
+ // plus any stored fastener, matching how the step is titled elsewhere.
+ const derivedTitle = useMemo(() => {
+ const parsedFastener = fastenerSchema.safeParse(step.fastener);
+ return describeStep(
+ {
+ title: null,
+ componentNodeIds,
+ fastener: parsedFastener.success ? parsedFastener.data : null
+ },
+ graphIndex,
+ units
+ );
+ }, [componentNodeIds, step.fastener, graphIndex, units]);
+
+ // Planner flag: no collision-free path exists for these components. The player
+ // fades them in at the seated pose; a manual motion overrides the flag.
+ const planFlag = useMemo(() => {
+ const parsed = stepPlanWarningsSchema.safeParse(step.warnings);
+ if (!parsed.success || parsed.data.flagged !== true) return null;
+ const blockers = (parsed.data.blockedBy ?? [])
+ .map((nodeId) => graphIndex?.nodesById.get(nodeId)?.name)
+ .filter((name): name is string => Boolean(name));
+ return { blockers: [...new Set(blockers)] };
+ }, [step.warnings, graphIndex]);
+
+ return (
+ <ValidatedForm
+ validator={assemblyInstructionStepValidator}
+ method="post"
+ action={path.to.assemblyInstructionStep(instructionId, step.id)}
+ defaultValues={{
+ id: step.id,
+ assemblyInstructionId: instructionId,
+ title: step.title ?? "",
+ type: step.type ?? "Task",
+ required: step.required ?? false,
+ unitOfMeasureCode: step.unitOfMeasureCode ?? "",
+ minValue: step.minValue ?? undefined,
+ maxValue: step.maxValue ?? undefined,
+ listValues: step.listValues ?? []
+ }}
+ fetcher={fetcher}
+ className="w-full"
+ >
+ <Hidden name="id" />
+ <Hidden name="assemblyInstructionId" />
+ <Hidden name="description" value={JSON.stringify(description)} />
+ <Hidden
+ name="componentNodeIds"
+ value={JSON.stringify(componentNodeIds)}
+ />
+ <VStack spacing={4} className="w-full pb-4">
+ <SelectControlled
+ name="type"
+ label="Type"
+ options={typeOptions}
+ value={stepType}
+ isReadOnly={isDisabled}
+ onChange={(option) => {
+ if (option) {
+ setStepType(option.value as (typeof procedureStepType)[number]);
+ }
+ }}
+ />
+ <Input
+ name="title"
+ label="Title"
+ placeholder={derivedTitle ?? "Untitled step"}
+ />
+ <VStack spacing={2} className="w-full">
+ <Label>Instruction</Label>
+ <Editor
+ initialValue={(step.description as JSONContent) ?? {}}
+ onUpload={onUploadImage}
+ onChange={(value) => {
+ setDescription(value);
+ }}
+ className="[&_.is-empty]:text-muted-foreground min-h-[120px] p-4 rounded-lg border w-full"
+ />
+ </VStack>
+
+ {stepType === "Measurement" && (
+ <VStack spacing={2} className="w-full">
+ <UnitOfMeasure name="unitOfMeasureCode" label="Unit of Measure" />
+ <div className="grid grid-cols-2 gap-2 w-full">
+ <Number
+ name="minValue"
+ label="Minimum"
+ formatOptions={{
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 10
+ }}
+ />
+ <Number
+ name="maxValue"
+ label="Maximum"
+ formatOptions={{
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 10
+ }}
+ />
+ </div>
+ </VStack>
+ )}
+ {stepType === "List" && (
+ <ArrayInput name="listValues" label="List Options" />
+ )}
+ <BooleanInput
+ name="required"
+ label="Required"
+ description="Operators must record this step to complete the operation"
+ />
+
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <Label>Motion</Label>
+ {!isDisabled && (
+ <Button
+ variant={isEditingMotion ? "primary" : "secondary"}
+ size="sm"
+ isDisabled={componentNodeIds.length === 0}
+ onClick={() =>
+ isEditingMotion ? onStopEditMotion() : onEditMotion(step.id)
+ }
+ >
+ {isEditingMotion ? "Done editing path" : "Edit path"}
+ </Button>
+ )}
+ </HStack>
+ {componentNodeIds.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ Assign components to this step to edit its motion path.
+ </p>
+ ) : isEditingMotion ? (
+ <p className="text-xs text-muted-foreground">
+ Drag the red waypoints in the viewer to shape the insertion path.
+ Double-click the path to add a waypoint; select one and press
+ Delete to remove it.
+ </p>
+ ) : planFlag ? (
+ <p className="text-xs text-muted-foreground">
+ No collision-free insertion path was found
+ {planFlag.blockers.length > 0
+ ? ` — blocked by ${planFlag.blockers.join(", ")}`
+ : ""}
+ . Edit the path to author one.
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Edit the path to adjust how these components move into place.
+ </p>
+ )}
+ </VStack>
+
+ <VStack spacing={2} className="w-full">
+ <Label>Camera</Label>
+ <p className="text-xs text-muted-foreground">
+ {hasCamera
+ ? "A saved view frames this step during playback."
+ : "This step auto-frames during playback. Orbit to the angle you want, then save it."}
+ </p>
+ {!isDisabled && (
+ <HStack spacing={2}>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => onSetCamera(step.id)}
+ >
+ Set camera to current view
+ </Button>
+ {hasCamera && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onClearCamera(step.id)}
+ >
+ Clear view
+ </Button>
+ )}
+ </HStack>
+ )}
+ </VStack>
+
+ <StepComponentsEditor
+ componentNodeIds={componentNodeIds}
+ graphIndex={graphIndex}
+ selectedNodeIds={selectedNodeIds}
+ isAddingComponents={isAddingComponents}
+ isDisabled={isDisabled}
+ onSelectComponents={onSelectComponents}
+ onStartAddComponents={onStartAddComponents}
+ onStopAddComponents={onStopAddComponents}
+ onRemoveComponents={onRemoveComponents}
+ />
+
+ <Submit
+ isDisabled={cannotSave || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Save Step
+ </Submit>
+ </VStack>
+ </ValidatedForm>
+ );
+}
+
+/**
+ * The step's assigned components as an explicit, editable list. Clicking a row
+ * makes that component the active selection (red in the viewer, marked in the
+ * Components panel); the ✕ removes it from the step. Components are only *added*
+ * through "Add components", which clears the selection and appends whatever you
+ * pick next — so ordinary selection never mutates a step's components. Add/remove
+ * autosave immediately.
+ */
+function StepComponentsEditor({
+ componentNodeIds,
+ graphIndex,
+ selectedNodeIds,
+ isAddingComponents,
+ isDisabled,
+ onSelectComponents,
+ onStartAddComponents,
+ onStopAddComponents,
+ onRemoveComponents
+}: {
+ componentNodeIds: string[];
+ graphIndex: AssemblyGraphIndex | null;
+ selectedNodeIds: string[];
+ isAddingComponents: boolean;
+ isDisabled: boolean;
+ onSelectComponents: (nodeIds: string[]) => void;
+ onStartAddComponents: () => void;
+ onStopAddComponents: () => void;
+ onRemoveComponents: (nodeIds: string[]) => void;
+}) {
+ const groups = useMemo(
+ () =>
+ graphIndex ? groupComponentNodeIds(componentNodeIds, graphIndex) : [],
+ [componentNodeIds, graphIndex]
+ );
+ const selectedSet = useMemo(
+ () => new Set(selectedNodeIds),
+ [selectedNodeIds]
+ );
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <HStack className="w-full justify-between">
+ <Label>Components</Label>
+ {!isDisabled && (
+ <Button
+ variant={isAddingComponents ? "primary" : "secondary"}
+ size="sm"
+ leftIcon={isAddingComponents ? undefined : <LuCirclePlus />}
+ onClick={() =>
+ isAddingComponents
+ ? onStopAddComponents()
+ : onStartAddComponents()
+ }
+ >
+ {isAddingComponents ? "Done adding" : "Add components"}
+ </Button>
+ )}
+ </HStack>
+ {isAddingComponents && (
+ <p className="text-xs text-muted-foreground">
+ Click components in the viewer or the Components panel to add them to
+ this step. Shift-click to add several.
+ </p>
+ )}
+ {groups.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ {isAddingComponents
+ ? "No components yet — pick components in the viewer to add them."
+ : "No components assigned. Click Add components, then pick components in the viewer."}
+ </p>
+ ) : (
+ <ul className="max-h-64 w-full divide-y divide-border overflow-y-auto rounded-lg border border-border scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ {groups.map((group) => {
+ const isSelected = group.nodeIds.every((nodeId) =>
+ selectedSet.has(nodeId)
+ );
+ return (
+ <li
+ key={group.key}
+ role="button"
+ tabIndex={0}
+ className={cn(
+ "group flex w-full cursor-pointer select-none items-center gap-2 px-2 py-1.5 text-sm hover:bg-accent/30",
+ isSelected && "bg-blue-500/10 hover:bg-blue-500/10"
+ )}
+ onClick={() => onSelectComponents(group.nodeIds)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ onSelectComponents(group.nodeIds);
+ }
+ }}
+ >
+ <ComponentColorSwatch color={group.color} />
+ <span className="min-w-0 flex-1 truncate" title={group.name}>
+ {group.name}
+ </span>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ {!isDisabled && (
+ <IconButton
+ aria-label={`Remove ${group.name} from this step`}
+ icon={<LuX />}
+ variant="ghost"
+ size="sm"
+ className="opacity-0 group-hover:opacity-100 focus:opacity-100"
+ onClick={(event) => {
+ event.stopPropagation();
+ onRemoveComponents(group.nodeIds);
+ }}
+ />
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionStatus.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionStatus.tsx
new file mode 100644
index 0000000000..6889c25998
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionStatus.tsx
@@ -0,0 +1,23 @@
+import { Status } from "@carbon/react";
+import type { assemblyInstructionStatuses } from "../../production.models";
+
+type AssemblyInstructionStatusProps = {
+ status?: (typeof assemblyInstructionStatuses)[number] | null;
+};
+
+const AssemblyInstructionStatus = ({
+ status
+}: AssemblyInstructionStatusProps) => {
+ switch (status) {
+ case "Draft":
+ return <Status color="gray">{status}</Status>;
+ case "Published":
+ return <Status color="green">{status}</Status>;
+ case "Archived":
+ return <Status color="red">{status}</Status>;
+ default:
+ return null;
+ }
+};
+
+export default AssemblyInstructionStatus;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
new file mode 100644
index 0000000000..4b48a9590b
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
@@ -0,0 +1,230 @@
+import {
+ MenuIcon,
+ MenuItem,
+ Status,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo, useState } from "react";
+import { flushSync } from "react-dom";
+import {
+ LuBlocks,
+ LuBox,
+ LuCalendar,
+ LuCircleCheck,
+ LuPencil,
+ LuSquareStack,
+ LuTrash
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { Hyperlink, New, Table } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import type { MethodItemType } from "~/modules/shared";
+import { useItems } from "~/stores";
+import { path } from "~/utils/path";
+import type { AssemblyInstructionListItem } from "../../types";
+import AssemblyInstructionStatus from "./AssemblyInstructionStatus";
+
+type AssemblyInstructionsTableProps = {
+ data: AssemblyInstructionListItem[];
+ count: number;
+};
+
+const itemTypesWithDetails = ["Part", "Material", "Tool", "Consumable"];
+
+function ProcessingStatus({ status }: { status?: string | null }) {
+ switch (status) {
+ case "Success":
+ return <Status color="green">{status}</Status>;
+ case "Failed":
+ return <Status color="red">{status}</Status>;
+ case "Queued":
+ case "Processing":
+ return <Status color="yellow">{status}</Status>;
+ case "Idle":
+ return <Status color="gray">{status}</Status>;
+ default:
+ return null;
+ }
+}
+
+const AssemblyInstructionsTable = memo(
+ ({ data, count }: AssemblyInstructionsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [items] = useItems();
+ const deleteDisclosure = useDisclosure();
+ const [selectedInstruction, setSelectedInstruction] =
+ useState<AssemblyInstructionListItem | null>(null);
+
+ const columns = useMemo<ColumnDef<AssemblyInstructionListItem>[]>(
+ () => [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <Hyperlink to={path.to.assemblyInstruction(row.original.id)}>
+ {row.original.name}
+ </Hyperlink>
+ ),
+ meta: {
+ icon: <LuBlocks />
+ }
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: ({ row }) => (
+ <AssemblyInstructionStatus status={row.original.status} />
+ ),
+ meta: {
+ icon: <LuCircleCheck />
+ }
+ },
+ {
+ accessorKey: "itemId",
+ header: "Item",
+ cell: ({ row }) => {
+ const item = items.find((i) => i.id === row.original.itemId);
+ if (!item) {
+ return <span className="text-muted-foreground">—</span>;
+ }
+ return itemTypesWithDetails.includes(item.type) ? (
+ <Hyperlink
+ to={getLinkToItemDetails(item.type as MethodItemType, item.id)}
+ >
+ {item.readableIdWithRevision}
+ </Hyperlink>
+ ) : (
+ <span>{item.readableIdWithRevision}</span>
+ );
+ },
+ meta: {
+ icon: <LuSquareStack />
+ }
+ },
+ {
+ id: "model",
+ header: "Model",
+ cell: ({ row }) => {
+ const model = row.original.modelUpload;
+ if (!model) {
+ return <span className="text-muted-foreground">—</span>;
+ }
+ return (
+ <VStack spacing={0}>
+ <span className="truncate">{model.name ?? model.id}</span>
+ {typeof model.componentCount === "number" && (
+ <span className="text-xs text-muted-foreground tabular-nums">
+ {model.componentCount} component
+ {model.componentCount === 1 ? "" : "s"}
+ </span>
+ )}
+ </VStack>
+ );
+ },
+ meta: {
+ icon: <LuBox />
+ }
+ },
+ {
+ id: "processingStatus",
+ header: "Processing",
+ cell: ({ row }) => (
+ <ProcessingStatus
+ status={row.original.modelUpload?.processingStatus}
+ />
+ ),
+ meta: {
+ icon: <LuCircleCheck />
+ }
+ },
+ {
+ accessorKey: "updatedAt",
+ header: "Updated",
+ cell: ({ row }) =>
+ formatDate(row.original.updatedAt ?? row.original.createdAt),
+ meta: {
+ icon: <LuCalendar />
+ }
+ }
+ ],
+ [items]
+ );
+
+ const renderContextMenu = useCallback(
+ (row: AssemblyInstructionListItem) => {
+ return (
+ <>
+ <MenuItem
+ disabled={!permissions.can("update", "production")}
+ onClick={() => {
+ navigate(path.to.assemblyInstruction(row.id));
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Instruction
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "production")}
+ onClick={() => {
+ flushSync(() => {
+ setSelectedInstruction(row);
+ });
+ deleteDisclosure.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Instruction
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, permissions, deleteDisclosure]
+ );
+
+ return (
+ <>
+ <Table<AssemblyInstructionListItem>
+ data={data}
+ columns={columns}
+ count={count}
+ primaryAction={
+ permissions.can("create", "production") && (
+ <New
+ label="Assembly Instruction"
+ to={path.to.newAssemblyInstruction}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Assembly Instructions"
+ />
+ {deleteDisclosure.isOpen && selectedInstruction && (
+ <ConfirmDelete
+ action={path.to.deleteAssemblyInstruction(selectedInstruction.id)}
+ isOpen
+ onCancel={() => {
+ setSelectedInstruction(null);
+ deleteDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ setSelectedInstruction(null);
+ deleteDisclosure.onClose();
+ }}
+ name={selectedInstruction.name ?? "assembly instruction"}
+ text="Are you sure you want to delete this assembly instruction?"
+ />
+ )}
+ </>
+ );
+ }
+);
+
+AssemblyInstructionsTable.displayName = "AssemblyInstructionsTable";
+export default AssemblyInstructionsTable;
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx
new file mode 100644
index 0000000000..288e8e3160
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStandardNotesModal.tsx
@@ -0,0 +1,187 @@
+import { Hidden, Input, Submit, TextArea, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ HStack,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalHeader,
+ ModalTitle,
+ ToggleGroup,
+ ToggleGroupItem,
+ VStack
+} from "@carbon/react";
+import { useEffect, useState } from "react";
+import { LuPencil, LuTrash } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import {
+ type assemblyNoteSeverities,
+ assemblyStandardNoteValidator
+} from "../../production.models";
+import type { AssemblyStandardNote } from "../../types";
+import { SeverityIcon } from "./AssemblyStepRequirements";
+
+type Severity = (typeof assemblyNoteSeverities)[number];
+
+/**
+ * CRUD for company-level standard note templates. Templates are copied into
+ * steps on insert, so edits here never change authored instructions.
+ */
+export default function AssemblyStandardNotesModal({
+ standardNotes,
+ onClose
+}: {
+ standardNotes: AssemblyStandardNote[];
+ onClose: () => void;
+}) {
+ const permissions = usePermissions();
+ const formFetcher = useFetcher<{ success: boolean }>();
+ const deleteFetcher = useFetcher<{ success: boolean }>();
+
+ const [editing, setEditing] = useState<AssemblyStandardNote | null>(null);
+ const [severity, setSeverity] = useState<Severity>("Info");
+ const [formKey, setFormKey] = useState(0);
+
+ useEffect(() => {
+ if (formFetcher.state === "idle" && formFetcher.data?.success) {
+ setEditing(null);
+ setSeverity("Info");
+ setFormKey((key) => key + 1);
+ }
+ }, [formFetcher.state, formFetcher.data]);
+
+ const onEdit = (note: AssemblyStandardNote) => {
+ setEditing(note);
+ setSeverity(note.severity);
+ setFormKey((key) => key + 1);
+ };
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>Standard Notes</ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <VStack spacing={4} className="w-full">
+ {standardNotes.length > 0 && (
+ <ul className="w-full">
+ {standardNotes.map((note) => (
+ <li
+ key={note.id}
+ className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm"
+ >
+ <SeverityIcon severity={note.severity} />
+ <VStack spacing={0} className="min-w-0 flex-1">
+ <span className="truncate font-medium">{note.name}</span>
+ <span
+ className="truncate text-xs text-muted-foreground"
+ title={note.content}
+ >
+ {note.content}
+ </span>
+ </VStack>
+ <IconButton
+ aria-label={`Edit ${note.name}`}
+ icon={<LuPencil />}
+ variant="ghost"
+ size="sm"
+ onClick={() => onEdit(note)}
+ />
+ {permissions.can("delete", "production") && (
+ <IconButton
+ aria-label={`Delete ${note.name}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ isDisabled={deleteFetcher.state !== "idle"}
+ onClick={() => {
+ deleteFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyStandardNote(note.id)
+ });
+ }}
+ />
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ <ValidatedForm
+ key={formKey}
+ validator={assemblyStandardNoteValidator}
+ method="post"
+ action={
+ editing
+ ? path.to.assemblyStandardNote(editing.id)
+ : path.to.newAssemblyStandardNote
+ }
+ defaultValues={{
+ name: editing?.name ?? "",
+ content: editing?.content ?? ""
+ }}
+ fetcher={formFetcher}
+ className="w-full"
+ >
+ <Hidden name="severity" value={severity} />
+ <VStack spacing={2} className="w-full">
+ <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ {editing ? `Edit "${editing.name}"` : "New standard note"}
+ </h4>
+ <Input name="name" placeholder="e.g. Apply threadlocker" />
+ <TextArea
+ name="content"
+ placeholder="e.g. Apply Loctite 242 to threads before insertion"
+ />
+ <HStack className="w-full justify-between">
+ <ToggleGroup
+ type="single"
+ value={severity}
+ onValueChange={(value) => {
+ if (value) setSeverity(value as Severity);
+ }}
+ >
+ <ToggleGroupItem value="Info" aria-label="Info">
+ <SeverityIcon severity="Info" />
+ </ToggleGroupItem>
+ <ToggleGroupItem value="Caution" aria-label="Caution">
+ <SeverityIcon severity="Caution" />
+ </ToggleGroupItem>
+ <ToggleGroupItem value="Warning" aria-label="Warning">
+ <SeverityIcon severity="Warning" />
+ </ToggleGroupItem>
+ </ToggleGroup>
+ <HStack spacing={2}>
+ {editing && (
+ <Button
+ variant="ghost"
+ onClick={() => {
+ setEditing(null);
+ setSeverity("Info");
+ setFormKey((key) => key + 1);
+ }}
+ >
+ Cancel
+ </Button>
+ )}
+ <Submit isDisabled={formFetcher.state !== "idle"}>
+ {editing ? "Save" : "Create"}
+ </Submit>
+ </HStack>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ </VStack>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx
new file mode 100644
index 0000000000..4c3b056452
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx
@@ -0,0 +1,85 @@
+import { Badge, VStack } from "@carbon/react";
+import type { AssemblyGraphIndex } from "@carbon/viewer";
+import { groupComponentNodeIds } from "@carbon/viewer";
+import { useMemo } from "react";
+import { Empty } from "~/components";
+
+type AssemblyStepBomProps = {
+ componentNodeIds: string[];
+ graphIndex: AssemblyGraphIndex | null;
+};
+
+/** Components used by the selected step, grouped by identical geometry. */
+export default function AssemblyStepBom({
+ componentNodeIds,
+ graphIndex
+}: AssemblyStepBomProps) {
+ const groups = useMemo(
+ () =>
+ graphIndex ? groupComponentNodeIds(componentNodeIds, graphIndex) : [],
+ [componentNodeIds, graphIndex]
+ );
+
+ if (!graphIndex) {
+ return (
+ <Empty className="border-none">
+ <p className="text-sm text-muted-foreground">
+ The model graph has not loaded yet
+ </p>
+ </Empty>
+ );
+ }
+
+ if (groups.length === 0) {
+ return (
+ <Empty className="border-none">
+ <p className="text-sm text-muted-foreground max-w-[320px] text-center">
+ Click components in the viewer to assign them to this step
+ </p>
+ </Empty>
+ );
+ }
+
+ return (
+ <VStack spacing={2} className="w-full py-2">
+ <ul className="w-full divide-y divide-border">
+ {groups.map((group) => (
+ <li
+ key={group.key}
+ className="flex w-full items-center gap-2 py-2 text-sm"
+ >
+ <ComponentColorSwatch color={group.color} />
+ <span className="min-w-0 flex-1 truncate" title={group.name}>
+ {group.name}
+ </span>
+ <Badge variant="secondary" className="tabular-nums">
+ ×{group.count}
+ </Badge>
+ </li>
+ ))}
+ </ul>
+ </VStack>
+ );
+}
+
+export function ComponentColorSwatch({
+ color
+}: {
+ color: [number, number, number, number] | null;
+}) {
+ return (
+ <span
+ aria-hidden="true"
+ className="h-3 w-3 shrink-0 rounded-sm border border-border bg-muted"
+ style={
+ color
+ ? {
+ backgroundColor: `rgba(${Math.round(color[0] * 255)}, ${Math.round(
+ color[1] * 255
+ )}, ${Math.round(color[2] * 255)}, ${color[3]})`
+ }
+ : undefined
+ }
+ />
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx
new file mode 100644
index 0000000000..9cf2daa487
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx
@@ -0,0 +1,202 @@
+import { Combobox, Hidden, Number, Submit, ValidatedForm } from "@carbon/form";
+import { Badge, HStack, IconButton, VStack } from "@carbon/react";
+import { useEffect, useMemo, useState } from "react";
+import { LuCirclePlus, LuTrash } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Empty } from "~/components";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { assemblyStepMaterialValidator } from "../../production.models";
+import type { FlattenedBomMaterial } from "../../production.service";
+import type { AssemblyStepMaterial } from "../../types";
+
+type AssemblyStepMaterialsProps = {
+ stepId: string;
+ instructionId: string;
+ materials: AssemblyStepMaterial[];
+ bomMaterials: FlattenedBomMaterial[];
+ isDisabled: boolean;
+};
+
+/**
+ * Bill-of-material parts consumed at this step. The picker is limited to the
+ * instruction item's make-method BOM; associations are stored by itemId so
+ * they survive make-method re-versioning.
+ */
+export default function AssemblyStepMaterials({
+ stepId,
+ instructionId,
+ materials,
+ bomMaterials,
+ isDisabled
+}: AssemblyStepMaterialsProps) {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<{ success: boolean }>();
+ // Remount the form after a successful add so the fields clear
+ const [formKey, setFormKey] = useState(0);
+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ setFormKey((key) => key + 1);
+ setSelectedItemId(null);
+ }
+ }, [fetcher.state, fetcher.data]);
+
+ // One option per distinct BOM item, excluding items already on the step
+ const options = useMemo(() => {
+ const usedItemIds = new Set(materials.map((material) => material.itemId));
+ const seen = new Set<string>();
+ return bomMaterials.reduce<{ label: string; value: string }[]>(
+ (acc, material) => {
+ if (seen.has(material.itemId) || usedItemIds.has(material.itemId)) {
+ return acc;
+ }
+ seen.add(material.itemId);
+ acc.push({
+ label: [material.readableIdWithRevision, material.name]
+ .filter(Boolean)
+ .join(" — "),
+ value: material.itemId
+ });
+ return acc;
+ },
+ []
+ );
+ }, [bomMaterials, materials]);
+
+ const selectedBomLine = useMemo(
+ () =>
+ selectedItemId
+ ? bomMaterials.find((material) => material.itemId === selectedItemId)
+ : undefined,
+ [bomMaterials, selectedItemId]
+ );
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ Materials
+ </h4>
+ {materials.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No materials to display</p>
+ ) : (
+ <ul className="w-full">
+ {materials.map((material) => (
+ <MaterialRow
+ key={material.id}
+ material={material}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ ))}
+ </ul>
+ )}
+ {!isDisabled &&
+ (bomMaterials.length === 0 ? (
+ <Empty className="border-none">
+ <p className="text-sm text-muted-foreground max-w-[300px] text-center">
+ Link this instruction to an item with a make method to pick BOM
+ parts
+ </p>
+ </Empty>
+ ) : (
+ permissions.can("create", "production") && (
+ <ValidatedForm
+ key={formKey}
+ validator={assemblyStepMaterialValidator}
+ method="post"
+ action={path.to.newAssemblyStepMaterial(instructionId)}
+ fetcher={fetcher}
+ className="w-full"
+ >
+ <Hidden name="stepId" value={stepId} />
+ <VStack spacing={2} className="w-full">
+ <Combobox
+ name="itemId"
+ placeholder="Pick a BOM item"
+ options={options}
+ onChange={(option) =>
+ setSelectedItemId(option?.value ?? null)
+ }
+ />
+ {/* The hint sits under the whole row so the Add button
+ bottom-aligns with the quantity input itself */}
+ <VStack spacing={1} className="w-full">
+ <HStack className="w-full items-end" spacing={2}>
+ <div className="flex-1 min-w-0">
+ <Number name="quantity" label="Quantity" minValue={0} />
+ </div>
+ <Submit
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Add
+ </Submit>
+ </HStack>
+ <p className="font-normal text-xs text-muted-foreground">
+ {selectedBomLine
+ ? `${selectedBomLine.quantity} on the BOM — leave blank for as needed`
+ : "Leave blank for as needed"}
+ </p>
+ </VStack>
+ </VStack>
+ </ValidatedForm>
+ )
+ ))}
+ </VStack>
+ );
+}
+
+function MaterialRow({
+ material,
+ instructionId,
+ isDisabled
+}: {
+ material: AssemblyStepMaterial;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const deleteFetcher = useFetcher<{ success: boolean }>();
+ const permissions = usePermissions();
+
+ // Optimistically remove the row while the delete is in flight
+ if (deleteFetcher.state !== "idle") return null;
+
+ return (
+ <li className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm">
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={material.item?.name ?? undefined}
+ >
+ {material.item?.name}
+ </span>
+ {material.item?.readableIdWithRevision && (
+ <span className="text-xs text-muted-foreground">
+ {material.item.readableIdWithRevision}
+ </span>
+ )}
+ <Badge variant="secondary" className="tabular-nums">
+ {material.quantity != null ? `×${material.quantity}` : "as needed"}
+ </Badge>
+ {!isDisabled && permissions.can("delete", "production") && (
+ <IconButton
+ aria-label={`Delete ${material.item?.name ?? "material"}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ deleteFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyStepMaterial(
+ instructionId,
+ material.id
+ )
+ });
+ }}
+ />
+ )}
+ </li>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx
new file mode 100644
index 0000000000..2da38f54ee
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepRequirements.tsx
@@ -0,0 +1,614 @@
+import { useCarbon } from "@carbon/auth";
+import { Hidden, Input, Submit, TextArea, ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ cn,
+ HStack,
+ IconButton,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ ToggleGroup,
+ ToggleGroupItem,
+ VStack
+} from "@carbon/react";
+import { nanoid } from "nanoid";
+import { useCallback, useEffect, useState } from "react";
+import { useDropzone } from "react-dropzone";
+import {
+ LuCirclePlus,
+ LuFileVideo,
+ LuInfo,
+ LuOctagonAlert,
+ LuTrash,
+ LuTriangleAlert,
+ LuUpload
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { toast } from "sonner";
+import { Empty } from "~/components";
+import { Tool } from "~/components/Form";
+import { usePermissions, useUser } from "~/hooks";
+import { getPrivateUrl, path } from "~/utils/path";
+import {
+ type assemblyNoteSeverities,
+ assemblyStepRequirementValidator
+} from "../../production.models";
+import type {
+ AssemblyStandardNote,
+ AssemblyStepRequirement
+} from "../../types";
+import AssemblyStandardNotesModal from "./AssemblyStandardNotesModal";
+
+type Severity = (typeof assemblyNoteSeverities)[number];
+
+type AssemblyStepRequirementsProps = {
+ stepId: string;
+ instructionId: string;
+ requirements: AssemblyStepRequirement[];
+ standardNotes: AssemblyStandardNote[];
+ isDisabled: boolean;
+};
+
+/**
+ * Per-step process data: tools/fixtures/consumables (catalog-linked or free
+ * text), classified notes, reusable standard-note templates, and media
+ * attachments.
+ */
+export default function AssemblyStepRequirements({
+ stepId,
+ instructionId,
+ requirements,
+ standardNotes,
+ isDisabled
+}: AssemblyStepRequirementsProps) {
+ const byType = (type: AssemblyStepRequirement["type"]) =>
+ requirements.filter((requirement) => requirement.type === type);
+
+ return (
+ <Tabs defaultValue="tools" className="w-full">
+ <TabsList className="w-full">
+ <TabsTrigger className="flex-1" value="tools">
+ Tools
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="notes">
+ Notes
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="standard-notes">
+ Std Notes
+ </TabsTrigger>
+ <TabsTrigger className="flex-1" value="media">
+ Media
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="tools">
+ <VStack spacing={4} className="w-full py-2">
+ <RequirementSection
+ title="Tools"
+ type="Tool"
+ placeholder="e.g. 4mm hex key"
+ requirements={byType("Tool")}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ <RequirementSection
+ title="Fixtures"
+ type="Fixture"
+ placeholder="e.g. Assembly jig #3"
+ requirements={byType("Fixture")}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ <RequirementSection
+ title="Consumables"
+ type="Consumable"
+ placeholder="e.g. Loctite 242"
+ requirements={byType("Consumable")}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ </VStack>
+ </TabsContent>
+ <TabsContent value="notes">
+ <NotesSection
+ notes={byType("Note")}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ </TabsContent>
+ <TabsContent value="standard-notes">
+ <StandardNotesSection
+ standardNotes={standardNotes}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ </TabsContent>
+ <TabsContent value="media">
+ <MediaSection
+ media={byType("Media")}
+ stepId={stepId}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ </TabsContent>
+ </Tabs>
+ );
+}
+
+function RequirementSection({
+ title,
+ type,
+ placeholder,
+ requirements,
+ stepId,
+ instructionId,
+ isDisabled
+}: {
+ title: string;
+ type: "Tool" | "Fixture" | "Consumable";
+ placeholder: string;
+ requirements: AssemblyStepRequirement[];
+ stepId: string;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ // Remount the form after a successful add so the input clears
+ const [formKey, setFormKey] = useState(0);
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ setFormKey((key) => key + 1);
+ }
+ }, [fetcher.state, fetcher.data]);
+
+ return (
+ <VStack spacing={2} className="w-full">
+ <h4 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ {title}
+ </h4>
+ {requirements.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ No {title.toLowerCase()} to display
+ </p>
+ ) : (
+ <ul className="w-full">
+ {requirements.map((requirement) => (
+ <RequirementRow
+ key={requirement.id}
+ requirement={requirement}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ />
+ ))}
+ </ul>
+ )}
+ {!isDisabled && (
+ <ValidatedForm
+ key={formKey}
+ validator={assemblyStepRequirementValidator}
+ method="post"
+ action={path.to.newAssemblyStepRequirement(instructionId)}
+ fetcher={fetcher}
+ className="w-full"
+ >
+ <Hidden name="stepId" value={stepId} />
+ <Hidden name="type" value={type} />
+ <VStack spacing={2} className="w-full">
+ {type === "Tool" && <Tool name="itemId" />}
+ <HStack className="w-full items-start" spacing={2}>
+ <div className="flex-1 min-w-0">
+ <Input
+ name="name"
+ placeholder={
+ type === "Tool"
+ ? `or enter a name: ${placeholder}`
+ : placeholder
+ }
+ />
+ </div>
+ <Submit
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Add
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ )}
+ </VStack>
+ );
+}
+
+function RequirementRow({
+ requirement,
+ instructionId,
+ isDisabled,
+ children
+}: {
+ requirement: AssemblyStepRequirement;
+ instructionId: string;
+ isDisabled: boolean;
+ children?: React.ReactNode;
+}) {
+ const deleteFetcher = useFetcher<{ success: boolean }>();
+ const permissions = usePermissions();
+
+ // Optimistically remove the row while the delete is in flight
+ if (deleteFetcher.state !== "idle") return null;
+
+ return (
+ <li className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm">
+ {children ?? (
+ <>
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={requirement.name ?? undefined}
+ >
+ {requirement.name}
+ </span>
+ {requirement.item?.readableIdWithRevision && (
+ <span className="text-xs text-muted-foreground">
+ {requirement.item.readableIdWithRevision}
+ </span>
+ )}
+ {requirement.quantity > 1 && (
+ <Badge variant="secondary" className="tabular-nums">
+ ×{requirement.quantity}
+ </Badge>
+ )}
+ </>
+ )}
+ {!isDisabled && permissions.can("delete", "production") && (
+ <IconButton
+ aria-label={`Delete ${requirement.name ?? "requirement"}`}
+ icon={<LuTrash />}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ deleteFetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteAssemblyStepRequirement(
+ instructionId,
+ requirement.id
+ )
+ });
+ }}
+ />
+ )}
+ </li>
+ );
+}
+
+const severityStyles: Record<
+ Severity,
+ { icon: typeof LuInfo; className: string }
+> = {
+ Info: { icon: LuInfo, className: "text-blue-500" },
+ Caution: { icon: LuTriangleAlert, className: "text-yellow-500" },
+ Warning: { icon: LuOctagonAlert, className: "text-red-500" }
+};
+
+export function SeverityIcon({ severity }: { severity: Severity | null }) {
+ const { icon: Icon, className } = severityStyles[severity ?? "Info"];
+ return <Icon className={cn("h-4 w-4 shrink-0", className)} aria-hidden />;
+}
+
+function NotesSection({
+ notes,
+ stepId,
+ instructionId,
+ isDisabled
+}: {
+ notes: AssemblyStepRequirement[];
+ stepId: string;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const fetcher = useFetcher<{ success: boolean }>();
+ const [formKey, setFormKey] = useState(0);
+ const [severity, setSeverity] = useState<Severity>("Info");
+
+ useEffect(() => {
+ if (fetcher.state === "idle" && fetcher.data?.success) {
+ setFormKey((key) => key + 1);
+ setSeverity("Info");
+ }
+ }, [fetcher.state, fetcher.data]);
+
+ return (
+ <VStack spacing={2} className="w-full py-2">
+ {notes.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No notes to display</p>
+ ) : (
+ <ul className="w-full">
+ {notes.map((note) => (
+ <RequirementRow
+ key={note.id}
+ requirement={note}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ >
+ <SeverityIcon severity={note.severity} />
+ <span className="min-w-0 flex-1 whitespace-pre-wrap text-sm">
+ {note.text}
+ </span>
+ </RequirementRow>
+ ))}
+ </ul>
+ )}
+ {!isDisabled && (
+ <ValidatedForm
+ key={formKey}
+ validator={assemblyStepRequirementValidator}
+ method="post"
+ action={path.to.newAssemblyStepRequirement(instructionId)}
+ fetcher={fetcher}
+ className="w-full"
+ >
+ <Hidden name="stepId" value={stepId} />
+ <Hidden name="type" value="Note" />
+ <Hidden name="severity" value={severity} />
+ <VStack spacing={2} className="w-full">
+ <TextArea name="text" placeholder="Add a note for this step" />
+ <HStack className="w-full justify-between">
+ <ToggleGroup
+ type="single"
+ value={severity}
+ onValueChange={(value) => {
+ if (value) setSeverity(value as Severity);
+ }}
+ >
+ <ToggleGroupItem value="Info" aria-label="Info">
+ <SeverityIcon severity="Info" />
+ </ToggleGroupItem>
+ <ToggleGroupItem value="Caution" aria-label="Caution">
+ <SeverityIcon severity="Caution" />
+ </ToggleGroupItem>
+ <ToggleGroupItem value="Warning" aria-label="Warning">
+ <SeverityIcon severity="Warning" />
+ </ToggleGroupItem>
+ </ToggleGroup>
+ <Submit
+ variant="secondary"
+ leftIcon={<LuCirclePlus />}
+ isDisabled={fetcher.state !== "idle"}
+ >
+ Add Note
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ )}
+ </VStack>
+ );
+}
+
+function StandardNotesSection({
+ standardNotes,
+ stepId,
+ instructionId,
+ isDisabled
+}: {
+ standardNotes: AssemblyStandardNote[];
+ stepId: string;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const permissions = usePermissions();
+ const [manageOpen, setManageOpen] = useState(false);
+ const insertFetcher = useFetcher<{ success: boolean }>();
+
+ const onInsert = (note: AssemblyStandardNote) => {
+ // Copy semantics: editing the template later never changes the step
+ const formData = new FormData();
+ formData.append("stepId", stepId);
+ formData.append("type", "Note");
+ formData.append("text", note.content);
+ formData.append("severity", note.severity);
+ insertFetcher.submit(formData, {
+ method: "post",
+ action: path.to.newAssemblyStepRequirement(instructionId)
+ });
+ };
+
+ return (
+ <VStack spacing={2} className="w-full py-2">
+ {standardNotes.length === 0 ? (
+ <Empty className="border-none">
+ <p className="text-sm text-muted-foreground max-w-[300px] text-center">
+ Standard notes are reusable note templates shared across your
+ company
+ </p>
+ </Empty>
+ ) : (
+ <ul className="w-full">
+ {standardNotes.map((note) => (
+ <li
+ key={note.id}
+ className="flex w-full items-center gap-2 border-b border-border py-1.5 text-sm"
+ >
+ <SeverityIcon severity={note.severity} />
+ <VStack spacing={0} className="min-w-0 flex-1">
+ <span className="truncate font-medium">{note.name}</span>
+ <span
+ className="truncate text-xs text-muted-foreground"
+ title={note.content}
+ >
+ {note.content}
+ </span>
+ </VStack>
+ {!isDisabled && (
+ <Button
+ variant="secondary"
+ size="sm"
+ isDisabled={insertFetcher.state !== "idle"}
+ onClick={() => onInsert(note)}
+ >
+ Insert
+ </Button>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ {permissions.can("update", "production") && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="self-end"
+ onClick={() => setManageOpen(true)}
+ >
+ Manage
+ </Button>
+ )}
+ {manageOpen && (
+ <AssemblyStandardNotesModal
+ standardNotes={standardNotes}
+ onClose={() => setManageOpen(false)}
+ />
+ )}
+ </VStack>
+ );
+}
+
+const MAX_MEDIA_BYTES = 50 * 1024 * 1024;
+
+function MediaSection({
+ media,
+ stepId,
+ instructionId,
+ isDisabled
+}: {
+ media: AssemblyStepRequirement[];
+ stepId: string;
+ instructionId: string;
+ isDisabled: boolean;
+}) {
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const fetcher = useFetcher<{ success: boolean }>();
+ const [isUploading, setIsUploading] = useState(false);
+
+ const onDrop = useCallback(
+ async (acceptedFiles: File[]) => {
+ if (!carbon || !company.id) return;
+ setIsUploading(true);
+ try {
+ for (const file of acceptedFiles) {
+ if (file.size > MAX_MEDIA_BYTES) {
+ toast.error(`${file.name} is larger than 50MB`);
+ continue;
+ }
+ const extension = file.name.split(".").pop() ?? "bin";
+ const filePath = `${company.id}/assembly/${instructionId}/${stepId}/${nanoid()}.${extension}`;
+ const upload = await carbon.storage
+ .from("private")
+ .upload(filePath, file);
+ if (upload.error || !upload.data) {
+ toast.error(`Failed to upload ${file.name}`);
+ continue;
+ }
+ const formData = new FormData();
+ formData.append("stepId", stepId);
+ formData.append("type", "Media");
+ formData.append("name", file.name);
+ formData.append("filePath", upload.data.path);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.newAssemblyStepRequirement(instructionId)
+ });
+ }
+ } finally {
+ setIsUploading(false);
+ }
+ },
+ [carbon, company.id, instructionId, stepId, fetcher]
+ );
+
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({
+ onDrop,
+ accept: { "image/*": [], "video/*": [] },
+ disabled: isDisabled || isUploading
+ });
+
+ return (
+ <VStack spacing={2} className="w-full py-2">
+ {media.length === 0 ? (
+ <p className="text-xs text-muted-foreground">No media to display</p>
+ ) : (
+ <ul className="w-full">
+ {media.map((item) => (
+ <RequirementRow
+ key={item.id}
+ requirement={item}
+ instructionId={instructionId}
+ isDisabled={isDisabled}
+ >
+ <MediaThumbnail requirement={item} />
+ <span
+ className="min-w-0 flex-1 truncate"
+ title={item.name ?? undefined}
+ >
+ {item.name}
+ </span>
+ </RequirementRow>
+ ))}
+ </ul>
+ )}
+ {!isDisabled && (
+ <div
+ {...getRootProps()}
+ className={cn(
+ "flex w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border border-dashed border-border p-4 text-center text-sm text-muted-foreground hover:bg-accent/30",
+ isDragActive && "border-primary bg-accent/30",
+ isUploading && "pointer-events-none opacity-50"
+ )}
+ >
+ <input {...getInputProps()} />
+ <LuUpload className="h-4 w-4" />
+ <p>
+ {isUploading
+ ? "Uploading…"
+ : "Drop images or videos here, or click to browse"}
+ </p>
+ </div>
+ )}
+ </VStack>
+ );
+}
+
+function MediaThumbnail({
+ requirement
+}: {
+ requirement: AssemblyStepRequirement;
+}) {
+ if (!requirement.filePath) return null;
+ const isVideo = /\.(mp4|mov|webm|avi|mkv)$/i.test(requirement.filePath);
+ if (isVideo) {
+ return <LuFileVideo className="h-8 w-8 shrink-0 text-muted-foreground" />;
+ }
+ return (
+ <a
+ href={getPrivateUrl(requirement.filePath)}
+ target="_blank"
+ rel="noreferrer"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <img
+ src={getPrivateUrl(requirement.filePath)}
+ alt={requirement.name ?? "Attachment"}
+ className="h-8 w-8 shrink-0 rounded-sm border border-border object-cover"
+ />
+ </a>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/index.ts b/apps/erp/app/modules/production/ui/Assemblies/index.ts
new file mode 100644
index 0000000000..ed4b1a25c6
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Assemblies/index.ts
@@ -0,0 +1,7 @@
+export { default as AssemblyInstructionExplorer } from "./AssemblyInstructionExplorer";
+export { default as AssemblyInstructionForm } from "./AssemblyInstructionForm";
+export { default as AssemblyInstructionHeader } from "./AssemblyInstructionHeader";
+export { default as AssemblyInstructionProperties } from "./AssemblyInstructionProperties";
+export { default as AssemblyInstructionStatus } from "./AssemblyInstructionStatus";
+export { default as AssemblyInstructionsTable } from "./AssemblyInstructionsTable";
+export { default as AssemblyStepMaterials } from "./AssemblyStepMaterials";
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 5678b018dc..9d5d2a9bce 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -481,7 +481,6 @@ const JobBillOfMaterial = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
- className="my-2 "
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index d0015ad5d2..52160d19b2 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -973,7 +973,6 @@ const JobBillOfProcess = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
- className="my-2 "
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index f5ea88bdea..37353f4642 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -5,16 +5,21 @@ import {
LuListChecks,
LuSquareChartGantt,
LuSquareKanban,
+ LuStepForward,
LuTrash
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
+import { useFlags } from "~/hooks/useFlags";
import { useSavedViews } from "~/hooks/useSavedViews";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
+const internalOnlyRoutes = new Set<string>([path.to.assemblyInstructions]);
+
export default function useProductionSubmodules() {
const { t } = useLingui();
const permissions = usePermissions();
+ const { isInternal } = useFlags();
const productionRoutes: AuthenticatedRouteGroup[] = [
{
@@ -25,13 +30,6 @@ export default function useProductionSubmodules() {
to: path.to.jobs,
icon: <LuCirclePlay />,
table: "job"
- },
- {
- name: t`Procedures`,
- to: path.to.procedures,
- icon: <LuListChecks />,
- table: "procedure",
- role: "employee"
}
]
},
@@ -57,6 +55,24 @@ export default function useProductionSubmodules() {
}
]
},
+ {
+ name: t`Work Instructions`,
+ routes: [
+ {
+ name: t`Assemblies`,
+ to: path.to.assemblyInstructions,
+ icon: <LuStepForward />,
+ role: "employee"
+ },
+ {
+ name: t`Procedures`,
+ to: path.to.procedures,
+ icon: <LuListChecks />,
+ table: "procedure",
+ role: "employee"
+ }
+ ]
+ },
{
name: t`Configure`,
routes: [
@@ -71,30 +87,18 @@ export default function useProductionSubmodules() {
];
const { addSavedViewsToRoutes } = useSavedViews();
+ const isRouteVisible = (route: AuthenticatedRouteGroup["routes"][number]) => {
+ if (route.role && !permissions.is(route.role)) return false;
+ if (!isInternal && internalOnlyRoutes.has(route.to)) return false;
+ return true;
+ };
+
return {
groups: productionRoutes
- .filter((group) => {
- const filteredRoutes = group.routes.filter((route) => {
- if (route.role) {
- return permissions.is(route.role);
- } else {
- return true;
- }
- });
-
- return filteredRoutes.length > 0;
- })
+ .filter((group) => group.routes.some(isRouteVisible))
.map((group) => ({
...group,
- routes: group.routes
- .filter((route) => {
- if (route.role) {
- return permissions.is(route.role);
- } else {
- return true;
- }
- })
- .map(addSavedViewsToRoutes)
+ routes: group.routes.filter(isRouteVisible).map(addSavedViewsToRoutes)
}))
};
}
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 4eb5a833e8..c890dd6bdf 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -5,6 +5,7 @@ import { getLogger } from "@carbon/logger";
import { getPurchaseOrderStatus } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import type {
+ PostgrestResponse,
PostgrestSingleResponse,
SupabaseClient
} from "@supabase/supabase-js";
@@ -2358,10 +2359,25 @@ export async function getPurchasingRFQLines(
.order("order", { ascending: true });
}
+type PurchasingRfqSupplierWithSupplier =
+ Database["public"]["Tables"]["purchasingRfqSupplier"]["Row"] & {
+ supplier: { id: string; name: string };
+ };
+
+type LinkedSupplierQuote = {
+ supplierQuoteId: string;
+ supplierQuote:
+ | (Database["public"]["Tables"]["supplierQuote"]["Row"] & {
+ supplier: Database["public"]["Tables"]["supplier"]["Row"] | null;
+ })
+ | null;
+};
+
export async function getPurchasingRFQSuppliers(
client: SupabaseClient<Database>,
purchasingRfqId: string
-) {
+): Promise<PostgrestResponse<PurchasingRfqSupplierWithSupplier>> {
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
return client
.from("purchasingRfqSupplier")
.select("*, supplier(id, name)")
@@ -2610,7 +2626,8 @@ export async function updatePurchasingRFQStatus(
export async function getLinkedSupplierQuotes(
client: SupabaseClient<Database>,
purchasingRfqId: string
-) {
+): Promise<PostgrestResponse<LinkedSupplierQuote>> {
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
return client
.from("purchasingRfqToSupplierQuote")
.select(
@@ -2669,7 +2686,7 @@ export async function getLinkedPurchasingRfqsForInteraction(
export async function getSiblingQuotesForQuote(
client: SupabaseClient<Database>,
supplierQuoteId: string
-) {
+): Promise<PostgrestResponse<LinkedSupplierQuote>> {
// First get all RFQ IDs linked to this quote
const { data: linkedRfqs, error: rfqError } = await client
.from("purchasingRfqToSupplierQuote")
@@ -2677,12 +2694,16 @@ export async function getSiblingQuotesForQuote(
.eq("supplierQuoteId", supplierQuoteId);
if (rfqError || !linkedRfqs || linkedRfqs.length === 0) {
- return { data: [], error: rfqError };
+ return {
+ data: [],
+ error: rfqError
+ } as unknown as PostgrestResponse<LinkedSupplierQuote>;
}
const rfqIds = linkedRfqs.map((r) => r.purchasingRfqId);
// Get all quotes linked to any of these RFQs (excluding current quote)
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
return client
.from("purchasingRfqToSupplierQuote")
.select(
@@ -2716,7 +2737,8 @@ export async function getSupplierQuotesForComparison(
purchasingRfqId: string
) {
// 1. Get all supplier quote IDs linked to this RFQ with supplier info
- const { data: links, error: linksError } = await client
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
+ const linksResult: PostgrestResponse<LinkedSupplierQuote> = await client
.from("purchasingRfqToSupplierQuote")
.select(
`
@@ -2725,6 +2747,7 @@ export async function getSupplierQuotesForComparison(
`
)
.eq("purchasingRfqId", purchasingRfqId);
+ const { data: links, error: linksError } = linksResult;
if (linksError || !links?.length) {
return { data: { quotes: [], lines: [], prices: [] }, error: linksError };
@@ -2777,7 +2800,8 @@ export async function getSupplierQuotesForComparison(
export async function getPurchasingRFQSuppliersWithLinks(
client: SupabaseClient<Database>,
purchasingRfqId: string
-) {
+): Promise<PostgrestResponse<PurchasingRfqSupplierWithSupplier>> {
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
return client
.from("purchasingRfqSupplier")
.select("*, supplier(id, name)")
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index eef7444fb4..924d91eae9 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -2817,11 +2817,25 @@ export async function deleteCustomerItemPriceOverride(
.eq("companyId", companyId);
}
+type CustomerItemPriceOverrideWithRelations =
+ Database["public"]["Tables"]["customerItemPriceOverride"]["Row"] & {
+ customer: { id: string; name: string } | null;
+ customerType: { id: string; name: string } | null;
+ item: { id: string; name: string } | null;
+ breaks: {
+ id: string;
+ quantity: number;
+ overridePrice: number;
+ active: boolean;
+ }[];
+ };
+
export async function getCustomerItemPriceOverrideById(
client: SupabaseClient<Database>,
id: string,
companyId: string
-) {
+): Promise<PostgrestSingleResponse<CustomerItemPriceOverrideWithRelations>> {
+ // @ts-ignore - nested select instantiation exceeds tsgo depth limit
return client
.from("customerItemPriceOverride")
.select(
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 41e5d75b9f..0408b93a08 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -485,7 +485,6 @@ const QuoteBillOfMaterial = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
- className="my-2 "
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 39b2e0f69e..5b3afadc7b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -766,7 +766,6 @@ const QuoteBillOfProcess = ({
onToggleItem={onToggleItem}
onRemoveItem={onRemoveItem}
handleDrag={onCloseOnDrag}
- className="my-2 "
renderExtra={(item) => (
<div key={`${isOpen}`}>
<motion.button
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
index e750f1539f..d4bb3fa41b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -95,7 +95,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
const { data, error } = await carbon
.from("customer")
.select(
- "currencyCode, salesContactId, customerShipping!customerId(shippingCustomerLocationId)"
+ "currencyCode, salesContactId, customerShipping!customerShipping_customerId_fkey(shippingCustomerLocationId)"
)
.eq("id", newValue.value)
.single();
@@ -107,7 +107,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
currencyCode: data.currencyCode ?? undefined,
customerContactId: data.salesContactId ?? undefined,
customerLocationId:
- data.customerShipping?.shippingCustomerLocationId ?? undefined
+ data.customerShipping?.[0]?.shippingCustomerLocationId ?? undefined
}));
}
} else {
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
index 15c78aa07d..9b64dca220 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderForm.tsx
@@ -96,7 +96,7 @@ const SalesOrderForm = ({ initialValues }: SalesOrderFormProps) => {
const { data, error } = await carbon
?.from("customer")
.select(
- "currencyCode, salesContactId, customerShipping!customerId(shippingCustomerLocationId)"
+ "currencyCode, salesContactId, customerShipping!customerShipping_customerId_fkey(shippingCustomerLocationId)"
)
.eq("id", newValue.value)
.single();
@@ -108,7 +108,7 @@ const SalesOrderForm = ({ initialValues }: SalesOrderFormProps) => {
currencyCode: data.currencyCode ?? undefined,
customerContactId: data.salesContactId ?? undefined,
customerLocationId:
- data.customerShipping?.shippingCustomerLocationId ?? undefined
+ data.customerShipping?.[0]?.shippingCustomerLocationId ?? undefined
}));
}
} else {
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/useSalesRfqAutoFill.ts b/apps/erp/app/modules/sales/ui/SalesRFQ/useSalesRfqAutoFill.ts
index 97e518340f..7f907e946a 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/useSalesRfqAutoFill.ts
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/useSalesRfqAutoFill.ts
@@ -108,7 +108,7 @@ export function useSalesRfqAutoFill(initialValues: SalesRFQFormValues) {
const { data: customerDetails, error } = await carbon
.from("customer")
.select(
- "salesContactId, customerShipping!customerId(shippingCustomerLocationId)"
+ "salesContactId, customerShipping!customerShipping_customerId_fkey(shippingCustomerLocationId)"
)
.eq("id", resolvedCustomerId)
.single();
@@ -120,7 +120,7 @@ export function useSalesRfqAutoFill(initialValues: SalesRFQFormValues) {
undefined;
finalLocationId =
resolvedLocationId ??
- customerDetails.customerShipping?.shippingCustomerLocationId ??
+ customerDetails.customerShipping?.[0]?.shippingCustomerLocationId ??
undefined;
setCustomer((prev) => ({
@@ -179,7 +179,7 @@ export function useSalesRfqAutoFill(initialValues: SalesRFQFormValues) {
const { data, error } = await carbon
.from("customer")
.select(
- "salesContactId, customerShipping!customerId(shippingCustomerLocationId)"
+ "salesContactId, customerShipping!customerShipping_customerId_fkey(shippingCustomerLocationId)"
)
.eq("id", newValue.value)
.single();
@@ -190,7 +190,7 @@ export function useSalesRfqAutoFill(initialValues: SalesRFQFormValues) {
...prev,
customerContactId: data.salesContactId ?? undefined,
customerLocationId:
- data.customerShipping?.shippingCustomerLocationId ?? undefined
+ data.customerShipping?.[0]?.shippingCustomerLocationId ?? undefined
}));
}
} else {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 787dd48072..9ca81c1f6f 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-07-09T20:31:33.257Z",
- "totalTools": 1263,
+ "generated": "2026-07-09T20:57:39.950Z",
+ "totalTools": 1303,
"modules": 15,
"tools": [
{
@@ -19736,6 +19736,1288 @@
]
}
},
+ {
+ "name": "production_getAssemblyInstruction",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyInstructions",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instructions",
+ "paramCount": 5,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "search": {
+ "type": "string"
+ },
+ "status": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "limit": {
+ "type": "number"
+ },
+ "offset": {
+ "type": "number"
+ }
+ }
+ }
+ },
+ {
+ "name": "production_getModelForItem",
+ "module": "production",
+ "classification": "READ",
+ "description": "get model for item",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "itemId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyInstructionSteps",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction steps",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "assemblyInstructionId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "assemblyInstructionId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "assemblyInstructionId"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyInstruction",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly instruction",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "modelUploadId": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "name",
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyInstructionStatus",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly instruction status",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "id",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "data": {
+ "type": "object",
+ "properties": {
+ "status": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "data"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyInstruction",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly instruction",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyInstructionStep",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly instruction step",
+ "paramCount": 16,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "assemblyInstructionId": {
+ "type": "string"
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "type": {},
+ "description": {},
+ "required": {
+ "type": "boolean"
+ },
+ "unitOfMeasureCode": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "minValue": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "maxValue": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "listValues": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "type": "string"
+ }
+ },
+ "componentNodeIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "motion": {},
+ "camera": {},
+ "fastener": {},
+ "durationSeconds": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "assemblyInstructionId"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyStepMotion",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly step motion",
+ "paramCount": 3,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "motion": {},
+ "camera": {}
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyStepComponents",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly step components",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "componentNodeIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "id",
+ "componentNodeIds"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyInstructionStepStatus",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly instruction step status",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "id",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "data": {
+ "type": "object",
+ "properties": {
+ "status": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ]
+ }
+ },
+ "required": [
+ "id",
+ "data"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyInstructionStepOrder",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly instruction step order",
+ "paramCount": 2,
+ "serviceParams": [
+ "db",
+ "updates"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "id",
+ "sortOrder"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyInstructionStep",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly instruction step",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyInstructionStepRequirements",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction step requirements",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "stepIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "stepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "stepIds"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyInstructionStepRequirement",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly instruction step requirement",
+ "paramCount": 10,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "stepId": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "text": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "severity": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "filePath": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "quantity": {
+ "type": "number"
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "stepId",
+ "type"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyInstructionStepRequirement",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction step requirement",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyInstructionStepRequirementOrder",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly instruction step requirement order",
+ "paramCount": 2,
+ "serviceParams": [
+ "db",
+ "updates"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "id",
+ "sortOrder"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyInstructionStepRequirement",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly instruction step requirement",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyInstructionStepMaterials",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly instruction step materials",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "stepIds"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "stepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "stepIds"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyInstructionStepMaterial",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly instruction step material",
+ "paramCount": 5,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "stepId": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "quantity": {
+ "type": [
+ "number",
+ "null"
+ ]
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "stepId",
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "production_updateAssemblyInstructionStepMaterialOrder",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "update assembly instruction step material order",
+ "paramCount": 2,
+ "serviceParams": [
+ "db",
+ "updates"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "sortOrder": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "id",
+ "sortOrder"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyInstructionStepMaterial",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly instruction step material",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_syncAssemblyStepMaterialsFromMappings",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "sync assembly step materials from mappings",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "assemblyInstructionId": {
+ "type": "string"
+ },
+ "/** Limit to these steps (default: every step of the instruction) */\n stepIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "/** Limit to these mappings (e.g. one just created) */\n geometryHashes": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "/** Limit to component groups containing one of these instances */\n onlyComponentNodeIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "assemblyInstructionId"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyStandardNotes",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly standard notes",
+ "paramCount": 0,
+ "serviceParams": [
+ "client",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {}
+ }
+ },
+ {
+ "name": "production_upsertAssemblyStandardNote",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly standard note",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "content": {
+ "type": "string"
+ },
+ "severity": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "content",
+ "severity"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyStandardNote",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly standard note",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyUnits",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly units",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "modelUploadId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyUnit",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly unit",
+ "paramCount": 5,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "modelUploadId": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "componentNodeIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "itemId": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "modelUploadId",
+ "name",
+ "componentNodeIds"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyUnit",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly unit",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getLatestAssemblyPlan",
+ "module": "production",
+ "classification": "READ",
+ "description": "get latest assembly plan",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "modelUploadId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_getLatestAssemblyPlanJob",
+ "module": "production",
+ "classification": "READ",
+ "description": "get latest assembly plan job",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "modelUploadId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_createAssemblyPlanJob",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "create assembly plan job",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyPlanJson",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly plan json",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "modelUploadId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_getAssemblyComponentMappings",
+ "module": "production",
+ "classification": "READ",
+ "description": "get assembly component mappings",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "modelUploadId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "modelUploadId"
+ ]
+ }
+ },
+ {
+ "name": "production_upsertAssemblyComponentMapping",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "upsert assembly component mapping",
+ "paramCount": 4,
+ "serviceParams": [
+ "client",
+ "data"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "modelUploadId": {
+ "type": "string"
+ },
+ "geometryHash": {
+ "type": "string"
+ },
+ "itemId": {
+ "type": "string"
+ },
+ "confidence": {
+ "type": "string",
+ "enum": [
+ "high",
+ "low"
+ ]
+ }
+ },
+ "required": [
+ "modelUploadId",
+ "geometryHash",
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "production_deleteAssemblyComponentMapping",
+ "module": "production",
+ "classification": "DESTRUCTIVE",
+ "description": "delete assembly component mapping",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "id"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ]
+ }
+ },
+ {
+ "name": "production_getFlattenedBomMaterials",
+ "module": "production",
+ "classification": "READ",
+ "description": "get flattened bom materials",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "itemId",
+ "companyId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "itemId"
+ ]
+ }
+ },
+ {
+ "name": "production_autoMatchAssemblyComponents",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "auto match assembly components",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "assemblyInstructionId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "assemblyInstructionId"
+ ]
+ }
+ },
+ {
+ "name": "production_generateAssemblyStepsFromPlan",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "generate assembly steps from plan",
+ "paramCount": 2,
+ "serviceParams": [
+ "client",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "assemblyInstructionId": {
+ "type": "string"
+ },
+ "/**\n * \"regenerate\" replaces the existing steps with fresh drafts from the\n * latest plan — refused while any step is manually authored\n * (planConfidence \"manual\") or already Done.\n */\n mode": {
+ "type": "string",
+ "enum": [
+ "generate",
+ "regenerate"
+ ]
+ }
+ },
+ "required": [
+ "assemblyInstructionId"
+ ]
+ }
+ },
+ {
+ "name": "production_toViewerStep",
+ "module": "production",
+ "classification": "WRITE",
+ "description": "to viewer step",
+ "paramCount": 1,
+ "serviceParams": [
+ "step"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "step": {}
+ },
+ "required": [
+ "step"
+ ]
+ }
+ },
{
"name": "production_getJobMaterialPurchaseOrderLines",
"module": "production",
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index 61329f58b4..ffced0bd1d 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -29,6 +29,11 @@ export async function action({ request }: ActionFunctionArgs) {
if (!modelPath) {
throw new Error("Model path is required");
}
+ // The path is client-supplied; never let it point outside this tenant's
+ // storage prefix or escape via traversal.
+ if (!modelPath.startsWith(`${companyId}/`) || modelPath.includes("..")) {
+ throw new Error("Invalid model path");
+ }
const modelRecord = await client.from("modelUpload").insert({
id: modelId,
@@ -76,6 +81,10 @@ export async function action({ request }: ActionFunctionArgs) {
modelId
});
+ // Conversion to assembly-instruction artifacts (GLB + graph) is lazy:
+ // triggered when an assembly instruction is created for this model, not
+ // on upload — most uploaded models never become assemblies.
+
return {
success: true
};
diff --git a/apps/erp/app/routes/x+/assembly+/$id.component-mappings.auto.tsx b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.auto.tsx
new file mode 100644
index 0000000000..3dc776a522
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.auto.tsx
@@ -0,0 +1,59 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ autoMatchAssemblyComponents,
+ syncAssemblyStepMaterialsFromMappings
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const result = await autoMatchAssemblyComponents(client, {
+ assemblyInstructionId: id,
+ companyId,
+ userId
+ });
+
+ if ("error" in result) {
+ return data(
+ { success: false },
+ await flash(request, error(null, result.error))
+ );
+ }
+
+ // An explicit "match everything" gesture — also backfill every step's
+ // materials from the full mapping set (additive; manual edits survive).
+ const materials = await syncAssemblyStepMaterialsFromMappings(client, {
+ assemblyInstructionId: id,
+ companyId,
+ userId
+ });
+
+ const summary =
+ result.unmatchedBomItems.length > 0
+ ? ` (${result.unmatchedBomItems.length} BOM line${result.unmatchedBomItems.length === 1 ? "" : "s"} unmatched: ${result.unmatchedBomItems.slice(0, 3).join(", ")}${result.unmatchedBomItems.length > 3 ? "…" : ""})`
+ : "";
+ const materialsSummary =
+ materials.created > 0
+ ? ` and added ${materials.created} step material${materials.created === 1 ? "" : "s"}`
+ : "";
+
+ return data(
+ { success: true, ...result },
+ await flash(
+ request,
+ success(
+ `Mapped ${result.mapped} of ${result.totalComponents} components to the bill of materials${summary}${materialsSummary}`
+ )
+ )
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.component-mappings.delete.$mappingId.tsx b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.delete.$mappingId.tsx
new file mode 100644
index 0000000000..db4b5823bf
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.delete.$mappingId.tsx
@@ -0,0 +1,28 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyComponentMapping } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { mappingId } = params;
+ if (!mappingId) throw new Error("mappingId is not found");
+
+ const deleteMapping = await deleteAssemblyComponentMapping(client, mappingId);
+ if (deleteMapping.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(deleteMapping.error, "Failed to remove mapping")
+ )
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.component-mappings.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.new.tsx
new file mode 100644
index 0000000000..f8f68b1e8e
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.component-mappings.new.tsx
@@ -0,0 +1,58 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ syncAssemblyStepMaterialsFromMappings,
+ upsertAssemblyComponentMapping
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const modelUploadId = formData.get("modelUploadId") as string;
+ const geometryHash = formData.get("geometryHash") as string;
+ const itemId = formData.get("itemId") as string;
+
+ if (!modelUploadId || !geometryHash || !itemId) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Missing mapping fields"))
+ );
+ }
+
+ const upsert = await upsertAssemblyComponentMapping(client, {
+ modelUploadId,
+ geometryHash,
+ itemId,
+ confidence: "high", // human-confirmed
+ companyId,
+ createdBy: userId
+ });
+
+ if (upsert.error) {
+ return data(
+ { success: false },
+ await flash(request, error(upsert.error, "Failed to map part"))
+ );
+ }
+
+ // The new mapping flows onto every step that installs this component —
+ // additive, so existing step materials are untouched.
+ await syncAssemblyStepMaterialsFromMappings(client, {
+ assemblyInstructionId: id,
+ companyId,
+ userId,
+ geometryHashes: [geometryHash]
+ });
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.materials.$materialId.tsx b/apps/erp/app/routes/x+/assembly+/$id.materials.$materialId.tsx
new file mode 100644
index 0000000000..ec945a82b0
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.materials.$materialId.tsx
@@ -0,0 +1,45 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStepMaterialValidator,
+ upsertAssemblyInstructionStepMaterial
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { materialId } = params;
+ if (!materialId) throw new Error("materialId is not found");
+
+ const validation = await validator(assemblyStepMaterialValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const update = await upsertAssemblyInstructionStepMaterial(client, {
+ ...validation.data,
+ id: materialId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update material"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.materials.delete.$materialId.tsx b/apps/erp/app/routes/x+/assembly+/$id.materials.delete.$materialId.tsx
new file mode 100644
index 0000000000..b978ef8643
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.materials.delete.$materialId.tsx
@@ -0,0 +1,34 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyInstructionStepMaterial } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { materialId } = params;
+ if (!materialId) throw new Error("materialId is not found");
+
+ const deleteMaterial = await deleteAssemblyInstructionStepMaterial(
+ client,
+ materialId
+ );
+ if (deleteMaterial.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(deleteMaterial.error, "Failed to delete material")
+ )
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Successfully deleted material"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.materials.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.materials.new.tsx
new file mode 100644
index 0000000000..915be7d4a4
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.materials.new.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStepMaterialValidator,
+ upsertAssemblyInstructionStepMaterial
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const { id: assemblyInstructionId } = params;
+ if (!assemblyInstructionId) throw new Error("id is not found");
+
+ const validation = await validator(assemblyStepMaterialValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to add material"))
+ );
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
+ const { id, ...rest } = validation.data;
+
+ const create = await upsertAssemblyInstructionStepMaterial(client, {
+ ...rest,
+ companyId,
+ createdBy: userId
+ });
+ if (create.error) {
+ return data(
+ { success: false },
+ await flash(request, error(create.error, "Failed to insert material"))
+ );
+ }
+
+ return { success: true, id: create.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx
new file mode 100644
index 0000000000..89c8537038
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.materials.order.tsx
@@ -0,0 +1,46 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateAssemblyInstructionStepMaterialOrder } from "~/modules/production";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ if (!params.id) throw new Error("Could not find id");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateAssemblyInstructionStepMaterialOrder(
+ getDatabaseClient(),
+ updates
+ );
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx b/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx
new file mode 100644
index 0000000000..36f612ef60
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx
@@ -0,0 +1,68 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { getAssemblyModelState } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select(
+ "modelUploadId, modelUpload(id, processingStatus, glbPath, graphPath, modelPath)"
+ )
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ if (instruction.error || !instruction.data.modelUpload) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(instruction.error, "Could not find the instruction's model")
+ )
+ );
+ }
+
+ const modelState = getAssemblyModelState(instruction.data.modelUpload);
+
+ // Only kick a conversion for unconverted or failed models — "processing"
+ // means a job is already in flight, "converted" needs nothing.
+ if (modelState !== "convertible" && modelState !== "failed") {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(
+ null,
+ modelState === "processing"
+ ? "Model conversion is already in progress"
+ : modelState === "converted"
+ ? "The model is already converted"
+ : "This model cannot be converted (only STEP files are supported)"
+ )
+ )
+ );
+ }
+
+ await trigger("assembly-convert", {
+ companyId,
+ modelUploadId: instruction.data.modelUpload.id,
+ userId
+ });
+
+ return data(
+ { success: true },
+ await flash(request, success("Model conversion started"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx b/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx
new file mode 100644
index 0000000000..2837014604
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx
@@ -0,0 +1,117 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ createAssemblyPlanJob,
+ getLatestAssemblyPlanJob,
+ isAssemblyPlanRunning
+} from "~/modules/production";
+
+/**
+ * Re-runs motion planning over the instruction's converted model. When the
+ * instruction already has steps, it runs in ORDER-PRESERVING mode: the planner
+ * takes the existing step order as fixed and only recomputes each step's motion
+ * to avoid collision with parts from earlier steps, updating the step motions in
+ * place (Done steps kept). With no steps yet, it plans fresh (deriving order).
+ */
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("modelUploadId, modelUpload(processingStatus)")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single();
+
+ if (instruction.error || !instruction.data.modelUploadId) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(instruction.error, "This instruction has no model")
+ )
+ );
+ }
+
+ if (instruction.data.modelUpload?.processingStatus !== "Success") {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(null, "The model must finish converting before planning")
+ )
+ );
+ }
+
+ const planJob = await getLatestAssemblyPlanJob(
+ client,
+ instruction.data.modelUploadId
+ );
+ if (isAssemblyPlanRunning(planJob.data)) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Motion planning is already running"))
+ );
+ }
+ if (planJob.data?.status === "Queued") {
+ // Stale Queued row: the event was never picked up (worker pickup takes
+ // seconds). Fail it so it can't shadow the run we're about to start.
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Failed",
+ error: "Planning never started — the job event was lost",
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", planJob.data.id)
+ .eq("companyId", companyId);
+ }
+
+ // Order-preserving re-motion when steps already exist; fresh (reordering)
+ // plan when there are none yet.
+ const stepCount = await client
+ .from("assemblyInstructionStep")
+ .select("id", { count: "exact", head: true })
+ .eq("assemblyInstructionId", id)
+ .eq("companyId", companyId);
+ const hasSteps = (stepCount.count ?? 0) > 0;
+
+ // Create the job row before sending the event so the UI reflects the run
+ // immediately (the worker adopts it via planJobId). Best-effort: planning
+ // still works if the insert fails — the worker inserts its own row then.
+ const created = await createAssemblyPlanJob(client, {
+ modelUploadId: instruction.data.modelUploadId,
+ companyId,
+ userId
+ });
+
+ await trigger("assembly-plan", {
+ modelUploadId: instruction.data.modelUploadId,
+ companyId,
+ userId,
+ ...(created.data?.id ? { planJobId: created.data.id } : {}),
+ ...(hasSteps ? { reMotionFor: id } : {})
+ });
+
+ return data(
+ { success: true },
+ await flash(
+ request,
+ success(
+ hasSteps
+ ? "Re-planning motions in the current step order — steps update when it finishes"
+ : "Motion planning started — regenerate steps when it finishes"
+ )
+ )
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx
new file mode 100644
index 0000000000..73694fdaee
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.requirements.$requirementId.tsx
@@ -0,0 +1,45 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStepRequirementValidator,
+ upsertAssemblyInstructionStepRequirement
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { requirementId } = params;
+ if (!requirementId) throw new Error("requirementId is not found");
+
+ const validation = await validator(assemblyStepRequirementValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const update = await upsertAssemblyInstructionStepRequirement(client, {
+ ...validation.data,
+ id: requirementId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update requirement"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx
new file mode 100644
index 0000000000..c9710961a9
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.requirements.delete.$requirementId.tsx
@@ -0,0 +1,46 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ deleteAssemblyInstructionStepRequirement,
+ getAssemblyInstructionStepRequirement
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { requirementId } = params;
+ if (!requirementId) throw new Error("requirementId is not found");
+
+ // Media rows own a storage object — remove it before the row
+ const requirement = await getAssemblyInstructionStepRequirement(
+ client,
+ requirementId
+ );
+ if (requirement.data?.type === "Media" && requirement.data.filePath) {
+ await client.storage.from("private").remove([requirement.data.filePath]);
+ }
+
+ const deleteRequirement = await deleteAssemblyInstructionStepRequirement(
+ client,
+ requirementId
+ );
+ if (deleteRequirement.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(deleteRequirement.error, "Failed to delete requirement")
+ )
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Successfully deleted requirement"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx
new file mode 100644
index 0000000000..52193e4c2c
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.requirements.new.tsx
@@ -0,0 +1,63 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStepRequirementValidator,
+ upsertAssemblyInstructionStepRequirement
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const { id: assemblyInstructionId } = params;
+ if (!assemblyInstructionId) throw new Error("id is not found");
+
+ const validation = await validator(assemblyStepRequirementValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(validation.error, "Failed to create requirement")
+ )
+ );
+ }
+
+ // Media uploads must live under this company's path for this instruction
+ const { filePath } = validation.data;
+ if (filePath) {
+ const expectedPrefix = `${companyId}/assembly/${assemblyInstructionId}/`;
+ if (!filePath.startsWith(expectedPrefix) || filePath.includes("..")) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Invalid file path"))
+ );
+ }
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
+ const { id, ...rest } = validation.data;
+
+ const create = await upsertAssemblyInstructionStepRequirement(client, {
+ ...rest,
+ companyId,
+ createdBy: userId
+ });
+ if (create.error) {
+ return data(
+ { success: false },
+ await flash(request, error(create.error, "Failed to insert requirement"))
+ );
+ }
+
+ return { success: true, id: create.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx
new file mode 100644
index 0000000000..c62ebada91
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.requirements.order.tsx
@@ -0,0 +1,46 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateAssemblyInstructionStepRequirementOrder } from "~/modules/production";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ if (!params.id) throw new Error("Could not find id");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateAssemblyInstructionStepRequirementOrder(
+ getDatabaseClient(),
+ updates
+ );
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.status.tsx b/apps/erp/app/routes/x+/assembly+/$id.status.tsx
new file mode 100644
index 0000000000..975e22d197
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.status.tsx
@@ -0,0 +1,52 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import {
+ assemblyInstructionStatuses,
+ updateAssemblyInstructionStatus
+} from "~/modules/production";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const status = formData.get(
+ "status"
+ ) as (typeof assemblyInstructionStatuses)[number];
+
+ if (!status || !assemblyInstructionStatuses.includes(status)) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.assemblyInstruction(id),
+ await flash(request, error(null, "Invalid status"))
+ );
+ }
+
+ const update = await updateAssemblyInstructionStatus(client, id, {
+ status,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.assemblyInstruction(id),
+ await flash(
+ request,
+ error(update.error, "Failed to update assembly instruction status")
+ )
+ );
+ }
+
+ throw redirect(
+ requestReferrer(request) ?? path.to.assemblyInstruction(id),
+ await flash(request, success("Updated assembly instruction status"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.$stepId.tsx
new file mode 100644
index 0000000000..168593cbd0
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.$stepId.tsx
@@ -0,0 +1,67 @@
+import { assertIsPost, error, notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyInstructionStepValidator,
+ upsertAssemblyInstructionStep
+} from "~/modules/production";
+import {
+ logAssemblyStep,
+ readAndLogFormData
+} from "~/modules/production/assembly-debug.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { stepId } = params;
+ if (!stepId) throw notFound("step id is not found");
+
+ const formData = await readAndLogFormData(request, "update.action");
+ const validation = await validator(assemblyInstructionStepValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ logAssemblyStep("update.validationError", {
+ stepId,
+ error: validation.error
+ });
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to update step"))
+ );
+ }
+
+ const update = await upsertAssemblyInstructionStep(client, {
+ ...validation.data,
+ id: stepId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+ logAssemblyStep("update.result", {
+ stepId,
+ hasMotion: validation.data.motion !== undefined,
+ componentNodeIds: validation.data.componentNodeIds,
+ title: validation.data.title ?? null,
+ error: update.error?.message ?? null,
+ updatedId: update.data?.id ?? null
+ });
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(update.error, "Failed to update assembly instruction step")
+ )
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.components.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.components.$stepId.tsx
new file mode 100644
index 0000000000..70693c4010
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.components.$stepId.tsx
@@ -0,0 +1,77 @@
+import { assertIsPost, error, notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyInstructionStepComponentsValidator,
+ syncAssemblyStepMaterialsFromMappings,
+ updateAssemblyStepComponents
+} from "~/modules/production";
+
+// Autosave target for the Details panel's Add/remove component controls: patches
+// only the step's assigned components, leaving the rest of the step untouched.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id, stepId } = params;
+ if (!id) throw notFound("id is not found");
+ if (!stepId) throw notFound("step id is not found");
+
+ const validation = await validator(
+ assemblyInstructionStepComponentsValidator
+ ).validate(await request.formData());
+
+ if (validation.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(validation.error, "Failed to update components")
+ )
+ );
+ }
+
+ // Captured before the update so newly added components can be auto-matched
+ // to BOM items below.
+ const previous = await client
+ .from("assemblyInstructionStep")
+ .select("componentNodeIds")
+ .eq("id", stepId)
+ .single();
+
+ const update = await updateAssemblyStepComponents(client, {
+ id: stepId,
+ componentNodeIds: validation.data.componentNodeIds,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update components"))
+ );
+ }
+
+ // Components added to the step pull their mapped BOM items onto the step's
+ // materials. Additive only — removals and manual material edits are left alone.
+ const previousNodeIds = new Set(previous.data?.componentNodeIds ?? []);
+ const addedNodeIds = validation.data.componentNodeIds.filter(
+ (nodeId) => !previousNodeIds.has(nodeId)
+ );
+ if (addedNodeIds.length > 0) {
+ await syncAssemblyStepMaterialsFromMappings(client, {
+ assemblyInstructionId: id,
+ companyId,
+ userId,
+ stepIds: [stepId],
+ onlyComponentNodeIds: addedNodeIds
+ });
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.delete.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.delete.$stepId.tsx
new file mode 100644
index 0000000000..3c054fe3cb
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.delete.$stepId.tsx
@@ -0,0 +1,32 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyInstructionStep } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { stepId } = params;
+ if (!stepId) throw new Error("stepId is not found");
+
+ const deleteStep = await deleteAssemblyInstructionStep(client, stepId);
+ if (deleteStep.error) {
+ return data(
+ {
+ success: false
+ },
+ await flash(request, error(deleteStep.error, "Failed to delete step"))
+ );
+ }
+
+ return data(
+ {
+ success: true
+ },
+ await flash(request, success("Successfully deleted step"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx
new file mode 100644
index 0000000000..f9942565bf
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx
@@ -0,0 +1,98 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ createAssemblyPlanJob,
+ generateAssemblyStepsFromPlan,
+ getLatestAssemblyPlanJob,
+ isAssemblyPlanRunning
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const mode =
+ formData.get("mode") === "regenerate" ? "regenerate" : "generate";
+
+ const result = await generateAssemblyStepsFromPlan(client, {
+ assemblyInstructionId: id,
+ companyId,
+ userId,
+ mode
+ });
+
+ if (result.ok) {
+ return data(
+ { success: true },
+ await flash(
+ request,
+ success(
+ mode === "regenerate"
+ ? `Regenerated ${result.created} steps from the motion plan`
+ : `Generated ${result.created} steps from the motion plan`
+ )
+ )
+ );
+ }
+
+ if (result.reason === "no-plan" && result.modelUploadId) {
+ // No plan yet — planning is lazy, so this click is what starts it. The
+ // caller polls and re-submits once the plan lands (or once a still-running
+ // conversion finishes). Don't start a run while the model is converting or
+ // a plan job is already Queued/Processing.
+ const [model, planJob] = await Promise.all([
+ client
+ .from("modelUpload")
+ .select("processingStatus")
+ .eq("id", result.modelUploadId)
+ .maybeSingle(),
+ getLatestAssemblyPlanJob(client, result.modelUploadId)
+ ]);
+
+ const isConverting =
+ model.data?.processingStatus === "Queued" ||
+ model.data?.processingStatus === "Processing";
+ const isPlanning = isAssemblyPlanRunning(planJob.data);
+
+ if (!isConverting && !isPlanning) {
+ // Pre-create the job row so the run is visible to the very next loader
+ // read; the worker adopts it via planJobId (falls back to inserting its
+ // own row when the insert fails).
+ const created = await createAssemblyPlanJob(client, {
+ modelUploadId: result.modelUploadId,
+ companyId,
+ userId
+ });
+
+ await trigger("assembly-plan", {
+ modelUploadId: result.modelUploadId,
+ companyId,
+ userId,
+ ...(created.data?.id ? { planJobId: created.data.id } : {})
+ });
+ }
+
+ return { success: false, planning: true };
+ }
+
+ const message =
+ result.reason === "steps-exist"
+ ? "Steps already exist — delete them before generating from the plan"
+ : result.reason === "steps-locked"
+ ? (result.message ?? "Some steps are locked — cannot regenerate")
+ : result.reason === "no-model"
+ ? "This instruction has no processed model"
+ : (result.message ?? "Failed to generate steps");
+
+ return data({ success: false }, await flash(request, error(null, message)));
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx
new file mode 100644
index 0000000000..72cd95f236
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.motion.$stepId.tsx
@@ -0,0 +1,64 @@
+import { assertIsPost, error, notFound } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyInstructionStepMotionValidator,
+ updateAssemblyStepMotion
+} from "~/modules/production";
+import {
+ logAssemblyStep,
+ readAndLogFormData
+} from "~/modules/production/assembly-debug.server";
+
+// Autosave target for the 3D motion-path editor: patches only motion/camera on
+// a step (drag autosave + "Set view"/"Clear view"), leaving the rest untouched.
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { stepId } = params;
+ if (!stepId) throw notFound("step id is not found");
+
+ const formData = await readAndLogFormData(request, "motion.action");
+ const validation = await validator(
+ assemblyInstructionStepMotionValidator
+ ).validate(formData);
+
+ if (validation.error) {
+ logAssemblyStep("motion.validationError", {
+ stepId,
+ error: validation.error
+ });
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to update motion"))
+ );
+ }
+
+ const update = await updateAssemblyStepMotion(client, {
+ id: stepId,
+ motion: validation.data.motion,
+ camera: validation.data.camera,
+ updatedBy: userId
+ });
+ logAssemblyStep("motion.updateResult", {
+ stepId,
+ motion: validation.data.motion,
+ hasCamera: validation.data.camera !== undefined,
+ error: update.error?.message ?? null,
+ updatedId: update.data?.id ?? null
+ });
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update motion"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx
new file mode 100644
index 0000000000..1c714a24b7
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.new.tsx
@@ -0,0 +1,62 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyInstructionStepValidator,
+ upsertAssemblyInstructionStep
+} from "~/modules/production";
+import {
+ logAssemblyStep,
+ readAndLogFormData
+} from "~/modules/production/assembly-debug.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const { id: assemblyInstructionId } = params;
+ if (!assemblyInstructionId) throw new Error("id is not found");
+
+ const formData = await readAndLogFormData(request, "new.action");
+ const validation = await validator(assemblyInstructionStepValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ logAssemblyStep("new.validationError", { error: validation.error });
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to create step"))
+ );
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
+ const { id, ...rest } = validation.data;
+
+ const create = await upsertAssemblyInstructionStep(client, {
+ ...rest,
+ companyId,
+ createdBy: userId
+ });
+ logAssemblyStep("new.result", {
+ createdId: create.data?.id ?? null,
+ componentNodeIds: rest.componentNodeIds,
+ error: create.error?.message ?? null
+ });
+ if (create.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(create.error, "Failed to insert assembly instruction step")
+ )
+ );
+ }
+
+ return { success: true, id: create.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx
new file mode 100644
index 0000000000..6e833642f8
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.order.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { updateAssemblyInstructionStepOrder } from "~/modules/production";
+import { getDatabaseClient } from "~/services/database.server";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ if (!params.id) throw new Error("Could not find id");
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return data(
+ { success: false },
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, sortOrderString]) => ({
+ id,
+ sortOrder: Number(sortOrderString),
+ updatedBy: userId
+ })
+ );
+
+ try {
+ await updateAssemblyInstructionStepOrder(getDatabaseClient(), updates);
+ } catch (err) {
+ return data(
+ { success: false },
+ await flash(request, error(err, "Failed to update sort order"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.status.$stepId.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.status.$stepId.tsx
new file mode 100644
index 0000000000..53c0830901
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.status.$stepId.tsx
@@ -0,0 +1,42 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyInstructionStepStatusValidator,
+ updateAssemblyInstructionStepStatus
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { stepId } = params;
+ if (!stepId) throw new Error("stepId is not found");
+
+ const validation = await validator(
+ assemblyInstructionStepStatusValidator
+ ).validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const update = await updateAssemblyInstructionStepStatus(client, stepId, {
+ status: validation.data.status,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update step status"))
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsx
new file mode 100644
index 0000000000..a0a3c8e040
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx
@@ -0,0 +1,586 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import {
+ Button,
+ ClientOnly,
+ Spinner,
+ toast,
+ useInterval,
+ useMode
+} from "@carbon/react";
+import type {
+ AssemblyGraph,
+ AssemblyPlayerHandle,
+ CameraPose,
+ Motion
+} from "@carbon/viewer";
+import { AssemblyPlayer, indexAssemblyGraph } from "@carbon/viewer";
+import { msg } from "@lingui/core/macro";
+import { useCallback, useMemo, useRef, useState } from "react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import {
+ data,
+ redirect,
+ useFetcher,
+ useLoaderData,
+ useParams,
+ useRevalidator
+} from "react-router";
+import { Empty } from "~/components";
+import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
+import { usePermissions } from "~/hooks";
+import {
+ assemblyInstructionValidator,
+ getAssemblyComponentMappings,
+ getAssemblyInstruction,
+ getAssemblyInstructionStepMaterials,
+ getAssemblyInstructionStepRequirements,
+ getAssemblyInstructionSteps,
+ getAssemblyPlanJson,
+ getAssemblyStandardNotes,
+ getAssemblyUnits,
+ getFlattenedBomMaterials,
+ getLatestAssemblyPlanJob,
+ isAssemblyPlanRunning,
+ toViewerStep,
+ upsertAssemblyInstruction
+} from "~/modules/production";
+import AssemblyInstructionExplorer from "~/modules/production/ui/Assemblies/AssemblyInstructionExplorer";
+import AssemblyInstructionHeader from "~/modules/production/ui/Assemblies/AssemblyInstructionHeader";
+import AssemblyInstructionProperties from "~/modules/production/ui/Assemblies/AssemblyInstructionProperties";
+import type { Handle } from "~/utils/handle";
+import { getPrivateUrl, path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`Assemblies`,
+ to: path.to.assemblyInstructions,
+ module: "production"
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const [instruction, steps, standardNotes] = await Promise.all([
+ getAssemblyInstruction(client, id),
+ getAssemblyInstructionSteps(client, id),
+ getAssemblyStandardNotes(client, companyId)
+ ]);
+
+ if (instruction.error) {
+ throw redirect(
+ path.to.assemblyInstructions,
+ await flash(
+ request,
+ error(instruction.error, "Failed to load assembly instruction")
+ )
+ );
+ }
+
+ const stepIds = (steps.data ?? []).map((step) => step.id);
+ const [
+ requirements,
+ stepMaterials,
+ plan,
+ planJob,
+ componentMappings,
+ units,
+ bomMaterials
+ ] = await Promise.all([
+ getAssemblyInstructionStepRequirements(client, stepIds),
+ getAssemblyInstructionStepMaterials(client, stepIds),
+ instruction.data.modelUploadId
+ ? getAssemblyPlanJson(client, instruction.data.modelUploadId)
+ : Promise.resolve(null),
+ instruction.data.modelUploadId
+ ? getLatestAssemblyPlanJob(client, instruction.data.modelUploadId)
+ : Promise.resolve({ data: null }),
+ instruction.data.modelUploadId
+ ? getAssemblyComponentMappings(client, instruction.data.modelUploadId)
+ : Promise.resolve({ data: [] }),
+ instruction.data.modelUploadId
+ ? getAssemblyUnits(client, instruction.data.modelUploadId)
+ : Promise.resolve({ data: [] }),
+ instruction.data.itemId
+ ? getFlattenedBomMaterials(client, instruction.data.itemId, companyId)
+ : Promise.resolve([])
+ ]);
+
+ return {
+ instruction: instruction.data,
+ steps: steps.data ?? [],
+ requirements: requirements.data ?? [],
+ stepMaterials: stepMaterials.data ?? [],
+ standardNotes: standardNotes.data ?? [],
+ units: units.data ?? [],
+ plan,
+ planJob: planJob.data ?? null,
+ componentMappings: componentMappings.data ?? [],
+ bomMaterials
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const validation = await validator(assemblyInstructionValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const update = await upsertAssemblyInstruction(client, {
+ ...validation.data,
+ id,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(update.error, "Failed to update assembly instruction")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.assemblyInstruction(id),
+ await flash(request, success("Updated assembly instruction"))
+ );
+}
+
+export default function AssemblyInstructionRoute() {
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const {
+ instruction,
+ steps,
+ requirements,
+ stepMaterials,
+ standardNotes,
+ units,
+ plan,
+ planJob,
+ componentMappings,
+ bomMaterials
+ } = useLoaderData<typeof loader>();
+ const permissions = usePermissions();
+ const mode = useMode();
+
+ const isDisabled =
+ instruction.status !== "Draft" || !permissions.can("update", "production");
+
+ // Motion planning runs server-side and patches step motions when it lands
+ // (the explorer polls while it runs). Until then the stored motions are
+ // stale or missing — surface that over the viewer and fade "none"-motion
+ // steps in rather than animating fallback paths the plan is about to replace.
+ const isPlanning = isAssemblyPlanRunning(planJob);
+
+ const [selectedStepId, setSelectedStepId] = useState<string | null>(
+ steps[0]?.id ?? null
+ );
+ const [draftComponentNodeIds, setDraftComponentNodeIds] = useState<
+ string[] | null
+ >(null);
+ const [graph, setGraph] = useState<AssemblyGraph | null>(null);
+ const graphIndex = useMemo(
+ () => (graph ? indexAssemblyGraph(graph) : null),
+ [graph]
+ );
+ // The current component selection — a single source of truth shared by all
+ // three panels: it renders red in the viewer, marks + scrolls to the row in the
+ // Components panel, and (while authoring a step) stages the step's draft components.
+ const [selectedNodeIds, setSelectedNodeIds] = useState<string[]>([]);
+ const [hiddenNodeIds, setHiddenNodeIds] = useState<string[]>([]);
+ // Add-mode: while on, picking components (in the viewer or the Components panel)
+ // appends them to the active step. Off by default, so plain selection never
+ // mutates a step's components — you must explicitly start adding.
+ const [isAddingComponents, setIsAddingComponents] = useState(false);
+
+ const selectedStep =
+ steps.find((step) => step.id === selectedStepId) ?? steps[0] ?? null;
+ const activeStepIndex = selectedStep
+ ? steps.findIndex((step) => step.id === selectedStep.id)
+ : 0;
+
+ // Read the latest steps inside the stable onSelectStep without widening its
+ // deps (it feeds explorer effects that must not re-fire on every steps change).
+ const stepsRef = useRef(steps);
+ stepsRef.current = steps;
+
+ // Autosave the active step's components (Add/remove in the Details panel) via a
+ // partial-update route, mirroring the motion-path autosave — never touching
+ // the title/typed fields.
+ const componentsFetcher = useFetcher<{ success: boolean }>();
+ const saveComponentNodeIds = useCallback(
+ (stepId: string, componentNodeIds: string[]) => {
+ const formData = new FormData();
+ formData.set("componentNodeIds", JSON.stringify(componentNodeIds));
+ componentsFetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStepComponents(id, stepId)
+ });
+ },
+ [componentsFetcher, id]
+ );
+
+ const onSelectStep = useCallback(
+ (stepId: string, options?: { selectComponents?: boolean }) => {
+ setSelectedStepId(stepId);
+ setDraftComponentNodeIds(null);
+ setIsAddingComponents(false);
+ // Leave any open motion-path edit session when moving to another step.
+ setEditingStepId(null);
+ setDraftMotion(null);
+ // Selecting a step makes its components the active selection — red in the
+ // viewer, marked in the Components panel. Viewer-driven changes (playback,
+ // scrub, on-screen nav) pass selectComponents:false so auto-advance doesn't
+ // stomp the selection the user is working with.
+ if (options?.selectComponents !== false) {
+ const step = stepsRef.current.find(
+ (candidate) => candidate.id === stepId
+ );
+ if (step) setSelectedNodeIds(step.componentNodeIds ?? []);
+ }
+ },
+ []
+ );
+
+ // Picking components (in the viewer or the Components panel) drives the shared
+ // selection. It only touches the active step's components while add-mode is on —
+ // then each selection is appended (union) and autosaved immediately.
+ const onSelectComponents = useCallback(
+ (nodeIds: string[]) => {
+ setSelectedNodeIds(nodeIds);
+ if (isAddingComponents && !isDisabled && selectedStep) {
+ const base =
+ draftComponentNodeIds ?? selectedStep.componentNodeIds ?? [];
+ const next = Array.from(new Set([...base, ...nodeIds]));
+ setDraftComponentNodeIds(next);
+ saveComponentNodeIds(selectedStep.id, next);
+ }
+ },
+ [
+ isAddingComponents,
+ isDisabled,
+ selectedStep,
+ draftComponentNodeIds,
+ saveComponentNodeIds
+ ]
+ );
+
+ // Enter add-mode with a clean slate: clear the selection so the components picked
+ // *next* are the ones added, not whatever happened to be highlighted.
+ const onStartAddComponents = useCallback(() => {
+ setIsAddingComponents(true);
+ setSelectedNodeIds([]);
+ }, []);
+
+ const onStopAddComponents = useCallback(
+ () => setIsAddingComponents(false),
+ []
+ );
+
+ // Remove a component group from the active step (autosaved), dropping it from the
+ // current selection so the viewer highlight stays in sync.
+ const onRemoveComponents = useCallback(
+ (nodeIds: string[]) => {
+ if (isDisabled || !selectedStep) return;
+ const remove = new Set(nodeIds);
+ const base = draftComponentNodeIds ?? selectedStep.componentNodeIds ?? [];
+ const next = base.filter((nodeId) => !remove.has(nodeId));
+ setDraftComponentNodeIds(next);
+ saveComponentNodeIds(selectedStep.id, next);
+ setSelectedNodeIds((prev) =>
+ prev.filter((nodeId) => !remove.has(nodeId))
+ );
+ },
+ [isDisabled, selectedStep, draftComponentNodeIds, saveComponentNodeIds]
+ );
+
+ const viewerSteps = useMemo(() => steps.map(toViewerStep), [steps]);
+
+ // Authored subassembly units, normalized for step-title derivation: a step
+ // whose components are exactly a unit is titled by the unit's name ("Add Board").
+ const namedUnits = useMemo(
+ () =>
+ units.map((unit) => ({
+ name: unit.name,
+ componentNodeIds: unit.componentNodeIds ?? []
+ })),
+ [units]
+ );
+
+ const modelUpload = instruction.modelUpload;
+ const glbPath = modelUpload?.glbPath;
+ const graphPath = modelUpload?.graphPath;
+
+ // Conversion is lazy (kicked off when the instruction was created), so the
+ // artifacts may still be in flight — poll until they land. "Idle" without
+ // artifacts covers the window before the queued event is picked up.
+ const isConverting =
+ !glbPath &&
+ (modelUpload?.processingStatus === "Queued" ||
+ modelUpload?.processingStatus === "Processing" ||
+ modelUpload?.processingStatus === "Idle");
+ const revalidator = useRevalidator();
+ useInterval(() => revalidator.revalidate(), isConverting ? 5000 : null);
+ const retryFetcher = useFetcher<{}>();
+
+ // --- Motion path + camera editing (viewer-driven) ------------------------
+ // The 3D viewer edits the active step's motion path (drag waypoints) and
+ // captures its camera; both autosave via a dedicated partial-update route so
+ // they never round-trip the whole step form. `draftMotion` is the controlled
+ // value the viewer renders while editing.
+ const playerRef = useRef<AssemblyPlayerHandle>(null);
+ const motionFetcher = useFetcher<{ success: boolean }>();
+ const [editingStepId, setEditingStepId] = useState<string | null>(null);
+ const [draftMotion, setDraftMotion] = useState<Motion | null>(null);
+ const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const saveMotion = useCallback(
+ (stepId: string, body: { motion?: Motion; camera?: CameraPose | null }) => {
+ const formData = new FormData();
+ if (body.motion !== undefined) {
+ formData.set("motion", JSON.stringify(body.motion));
+ }
+ if (body.camera !== undefined) {
+ formData.set("camera", JSON.stringify(body.camera));
+ }
+ motionFetcher.submit(formData, {
+ method: "post",
+ action: path.to.assemblyInstructionStepMotion(id, stepId)
+ });
+ },
+ [motionFetcher, id]
+ );
+
+ const onEditMotion = useCallback(
+ (stepId: string) => {
+ const viewerStep = viewerSteps.find((s) => s.id === stepId);
+ setSelectedStepId(stepId);
+ setEditingStepId(stepId);
+ setDraftMotion(viewerStep?.motion ?? { type: "none" });
+ },
+ [viewerSteps]
+ );
+
+ const onStopEditMotion = useCallback(() => {
+ setEditingStepId(null);
+ setDraftMotion(null);
+ }, []);
+
+ const onMotionChange = useCallback(
+ (stepId: string, motion: Motion) => {
+ setDraftMotion(motion);
+ if (saveTimer.current) clearTimeout(saveTimer.current);
+ saveTimer.current = setTimeout(() => saveMotion(stepId, { motion }), 400);
+ },
+ [saveMotion]
+ );
+
+ const onSetCamera = useCallback(
+ (stepId: string) => {
+ const pose = playerRef.current?.captureCameraPose();
+ if (!pose) {
+ toast.error("The model isn't ready yet");
+ return;
+ }
+ saveMotion(stepId, { camera: pose });
+ },
+ [saveMotion]
+ );
+
+ const onClearCamera = useCallback(
+ (stepId: string) => saveMotion(stepId, { camera: null }),
+ [saveMotion]
+ );
+
+ const isEditingSelectedMotion =
+ editingStepId !== null && selectedStep?.id === editingStepId;
+
+ return (
+ <PanelProvider key={id}>
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ <AssemblyInstructionHeader />
+ <div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
+ <div className="flex grow overflow-hidden">
+ <ResizablePanels
+ explorer={
+ <AssemblyInstructionExplorer
+ steps={steps}
+ units={units}
+ selectedStepId={selectedStep?.id ?? null}
+ isDisabled={isDisabled}
+ isConverting={isConverting}
+ graphIndex={graphIndex}
+ hasPlan={Boolean(plan)}
+ planJob={planJob}
+ modelUploadId={instruction.modelUploadId}
+ componentMappings={componentMappings}
+ bomMaterials={bomMaterials}
+ selectedNodeIds={selectedNodeIds}
+ onSelectStep={onSelectStep}
+ onHighlightComponents={onSelectComponents}
+ onHideComponents={setHiddenNodeIds}
+ />
+ }
+ content={
+ <div className="relative bg-background h-[calc(100dvh-99px)] w-full">
+ {glbPath && graphPath && isPlanning && (
+ <div className="pointer-events-none absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-2 rounded-full border border-border bg-background/90 px-3 py-1.5 shadow-sm">
+ <Spinner className="h-3.5 w-3.5" />
+ <span className="whitespace-nowrap text-xs text-muted-foreground">
+ Planning motion
+ </span>
+ </div>
+ )}
+ {glbPath && graphPath ? (
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ {() => (
+ <AssemblyPlayer
+ ref={playerRef}
+ glbUrl={getPrivateUrl(glbPath)}
+ graphUrl={getPrivateUrl(graphPath)}
+ steps={viewerSteps}
+ activeStepIndex={Math.max(activeStepIndex, 0)}
+ onStepChange={(index) => {
+ const step = steps[index];
+ if (step)
+ onSelectStep(step.id, {
+ selectComponents: false
+ });
+ }}
+ onSelectComponents={onSelectComponents}
+ onGraphLoaded={setGraph}
+ highlightedNodeIds={selectedNodeIds}
+ hiddenNodeIds={hiddenNodeIds}
+ readOnly={isDisabled}
+ editMotion={
+ editingStepId &&
+ selectedStep?.id === editingStepId &&
+ draftMotion
+ ? { stepId: editingStepId, motion: draftMotion }
+ : null
+ }
+ onMotionChange={onMotionChange}
+ units={namedUnits}
+ suppressFallbackMotions={isPlanning}
+ autoPlay={false}
+ mode={mode}
+ className="h-full"
+ />
+ )}
+ </ClientOnly>
+ ) : isConverting ? (
+ <div className="flex flex-col h-full w-full items-center justify-center gap-4">
+ <Spinner className="h-10 w-10" />
+ <p className="text-sm text-muted-foreground max-w-[320px] text-center">
+ Converting the model for assembly instructions… this can
+ take a minute.
+ </p>
+ </div>
+ ) : modelUpload?.processingStatus === "Failed" ? (
+ <Empty>
+ <p className="text-sm text-muted-foreground max-w-[320px] text-center">
+ {modelUpload?.processingError ??
+ "Model conversion failed"}
+ </p>
+ <retryFetcher.Form
+ method="post"
+ action={path.to.assemblyModelConvert(id!)}
+ >
+ <Button
+ type="submit"
+ variant="secondary"
+ isLoading={retryFetcher.state !== "idle"}
+ isDisabled={
+ retryFetcher.state !== "idle" ||
+ !permissions.can("update", "production")
+ }
+ >
+ Retry conversion
+ </Button>
+ </retryFetcher.Form>
+ </Empty>
+ ) : (
+ <Empty>
+ <p className="text-sm text-muted-foreground max-w-[320px] text-center">
+ The model has not been processed for assembly
+ instructions yet
+ </p>
+ </Empty>
+ )}
+ </div>
+ }
+ properties={
+ <AssemblyInstructionProperties
+ key={selectedStep?.id ?? "empty"}
+ step={selectedStep}
+ draftComponentNodeIds={draftComponentNodeIds}
+ selectedNodeIds={selectedNodeIds}
+ isAddingComponents={isAddingComponents}
+ isDisabled={isDisabled}
+ graphIndex={graphIndex}
+ units={namedUnits}
+ onSelectComponents={onSelectComponents}
+ onStartAddComponents={onStartAddComponents}
+ onStopAddComponents={onStopAddComponents}
+ onRemoveComponents={onRemoveComponents}
+ isEditingMotion={isEditingSelectedMotion}
+ onEditMotion={onEditMotion}
+ onStopEditMotion={onStopEditMotion}
+ onSetCamera={onSetCamera}
+ onClearCamera={onClearCamera}
+ requirements={
+ selectedStep
+ ? requirements.filter(
+ (requirement) =>
+ requirement.stepId === selectedStep.id
+ )
+ : []
+ }
+ stepMaterials={
+ selectedStep
+ ? stepMaterials.filter(
+ (material) => material.stepId === selectedStep.id
+ )
+ : []
+ }
+ bomMaterials={bomMaterials}
+ standardNotes={standardNotes}
+ />
+ }
+ />
+ </div>
+ </div>
+ </div>
+ </PanelProvider>
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.units.$unitId.tsx b/apps/erp/app/routes/x+/assembly+/$id.units.$unitId.tsx
new file mode 100644
index 0000000000..7f46608a26
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.units.$unitId.tsx
@@ -0,0 +1,53 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyUnitValidator,
+ upsertAssemblyUnit
+} from "~/modules/production";
+
+// Edit an authored subassembly unit in place — rename and/or change which parts
+// it groups. Membership feeds the motion planner, so applying a change requires
+// re-running motion planning (the editor nudges the user after saving).
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { unitId } = params;
+ if (!unitId) throw new Error("unitId is not found");
+
+ const validation = await validator(assemblyUnitValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to update unit"))
+ );
+ }
+
+ // The URL param is the source of truth for which unit is edited.
+ const { id: _id, ...rest } = validation.data;
+
+ const update = await upsertAssemblyUnit(client, {
+ ...rest,
+ id: unitId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(request, error(update.error, "Failed to update unit"))
+ );
+ }
+
+ return { success: true, id: update.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx b/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx
new file mode 100644
index 0000000000..8f5ef1975c
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.units.delete.$unitId.tsx
@@ -0,0 +1,28 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyUnit } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { unitId } = params;
+ if (!unitId) throw new Error("unitId is not found");
+
+ const remove = await deleteAssemblyUnit(client, unitId);
+ if (remove.error) {
+ return data(
+ { success: false },
+ await flash(request, error(remove.error, "Failed to delete unit"))
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Successfully deleted unit"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/$id.units.new.tsx b/apps/erp/app/routes/x+/assembly+/$id.units.new.tsx
new file mode 100644
index 0000000000..68dcb3074d
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/$id.units.new.tsx
@@ -0,0 +1,45 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyUnitValidator,
+ upsertAssemblyUnit
+} from "~/modules/production";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const validation = await validator(assemblyUnitValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return data(
+ { success: false },
+ await flash(request, error(validation.error, "Failed to create unit"))
+ );
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
+ const { id, ...rest } = validation.data;
+
+ const create = await upsertAssemblyUnit(client, {
+ ...rest,
+ companyId,
+ createdBy: userId
+ });
+ if (create.error) {
+ return data(
+ { success: false },
+ await flash(request, error(create.error, "Failed to create unit"))
+ );
+ }
+
+ return { success: true, id: create.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/_layout.tsx b/apps/erp/app/routes/x+/assembly+/_layout.tsx
new file mode 100644
index 0000000000..0fbed5d46b
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/_layout.tsx
@@ -0,0 +1,30 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs, MetaFunction } from "react-router";
+import { Outlet } from "react-router";
+import { requireAssembliesInternal } from "~/modules/production/production.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Assembly" }];
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { email } = await requirePermissions(request, {
+ view: "production"
+ });
+ requireAssembliesInternal(email);
+
+ return null;
+}
+
+export const handle: Handle = {
+ breadcrumb: msg`Production`,
+ to: path.to.production,
+ module: "production"
+};
+
+export default function AssemblyRoute() {
+ return <Outlet />;
+}
diff --git a/apps/erp/app/routes/x+/assembly+/delete.$id.tsx b/apps/erp/app/routes/x+/assembly+/delete.$id.tsx
new file mode 100644
index 0000000000..8ccf57bcfc
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/delete.$id.tsx
@@ -0,0 +1,34 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { deleteAssemblyInstruction } from "~/modules/production";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("id is not found");
+
+ const mutation = await deleteAssemblyInstruction(client, id);
+ if (mutation.error) {
+ return data(
+ {
+ success: false
+ },
+ await flash(
+ request,
+ error(mutation.error, "Failed to delete assembly instruction")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.assemblyInstructions,
+ await flash(request, success("Successfully deleted assembly instruction"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx b/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx
new file mode 100644
index 0000000000..075aab5328
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/standard-notes.$noteId.tsx
@@ -0,0 +1,48 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStandardNoteValidator,
+ upsertAssemblyStandardNote
+} from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { noteId } = params;
+ if (!noteId) throw new Error("noteId is not found");
+
+ const validation = await validator(assemblyStandardNoteValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const update = await upsertAssemblyStandardNote(client, {
+ ...validation.data,
+ id: noteId,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ });
+
+ if (update.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(update.error, "Failed to update standard note")
+ )
+ );
+ }
+
+ return { success: true };
+}
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx b/apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx
new file mode 100644
index 0000000000..235294bdeb
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/standard-notes.delete.$noteId.tsx
@@ -0,0 +1,31 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { deleteAssemblyStandardNote } from "~/modules/production";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "production"
+ });
+
+ const { noteId } = params;
+ if (!noteId) throw new Error("noteId is not found");
+
+ const deleteNote = await deleteAssemblyStandardNote(client, noteId);
+ if (deleteNote.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(deleteNote.error, "Failed to delete standard note")
+ )
+ );
+ }
+
+ return data(
+ { success: true },
+ await flash(request, success("Successfully deleted standard note"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx b/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx
new file mode 100644
index 0000000000..5664363f7a
--- /dev/null
+++ b/apps/erp/app/routes/x+/assembly+/standard-notes.new.tsx
@@ -0,0 +1,45 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
+import {
+ assemblyStandardNoteValidator,
+ upsertAssemblyStandardNote
+} from "~/modules/production";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production"
+ });
+
+ const validation = await validator(assemblyStandardNoteValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: id is never set on create
+ const { id, ...rest } = validation.data;
+
+ const create = await upsertAssemblyStandardNote(client, {
+ ...rest,
+ companyId,
+ createdBy: userId
+ });
+ if (create.error) {
+ return data(
+ { success: false },
+ await flash(
+ request,
+ error(create.error, "Failed to create standard note")
+ )
+ );
+ }
+
+ return { success: true, id: create.data?.id };
+}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
index ff3abcf210..50fef5ad1e 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx
@@ -60,13 +60,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const url = new URL(request.url);
const requestedMethodId = url.searchParams.get("methodId");
- const [makeMethods] = await Promise.all([
- getMakeMethods(client, itemId, companyId)
- // client.storage
- // .from("private")
- // .list(`${companyId}/default-attachments/item/${itemId}`)
- ]);
- // const defaultAttachments = defaultAttachmentsResult.data ?? [];
+ const makeMethods = await getMakeMethods(client, itemId, companyId);
const makeMethod = requestedMethodId
? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??
diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsx
index 0f0f6f1968..b6f8ecc3d8 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx
@@ -253,6 +253,7 @@ export default function PartRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ assemblyInstructions,
jobMaterialUsage
} = resolvedUsedIn;
@@ -348,6 +349,16 @@ export default function PartRoute() {
}
];
+ // Assembly instructions only exist for make parts
+ if (isManufactured) {
+ tree.splice(2, 0, {
+ key: "assemblyInstructions",
+ name: t`Assembly Instructions`,
+ module: "production",
+ children: assemblyInstructions
+ });
+ }
+
return (
<UsedInTree
tree={tree}
@@ -401,6 +412,7 @@ export default function PartRoute() {
salesOrderLines,
shipmentLines,
supplierQuotes,
+ assemblyInstructions,
jobMaterialUsage
} = resolvedUsedIn;
@@ -496,6 +508,16 @@ export default function PartRoute() {
}
];
+ // Assembly instructions only exist for make parts
+ if (isManufactured) {
+ tree.splice(2, 0, {
+ key: "assemblyInstructions",
+ name: "Assembly Instructions",
+ module: "production",
+ children: assemblyInstructions
+ });
+ }
+
return (
<UsedInTree
tree={tree}
diff --git a/apps/erp/app/routes/x+/production+/assemblies.new.tsx b/apps/erp/app/routes/x+/production+/assemblies.new.tsx
new file mode 100644
index 0000000000..579c2d2320
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/assemblies.new.tsx
@@ -0,0 +1,171 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { trigger } from "@carbon/jobs";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData, useNavigate } from "react-router";
+import {
+ assemblyInstructionFromItemValidator,
+ createAssemblyPlanJob,
+ getAssemblyModelState,
+ getLatestAssemblyPlanJob,
+ getModelForItem,
+ upsertAssemblyInstruction
+} from "~/modules/production";
+import { requireAssembliesInternal } from "~/modules/production/production.server";
+import AssemblyInstructionForm from "~/modules/production/ui/Assemblies/AssemblyInstructionForm";
+import { path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { email } = await requirePermissions(request, {
+ create: "production"
+ });
+ requireAssembliesInternal(email);
+
+ const url = new URL(request.url);
+
+ return {
+ initialValues: {
+ itemId: url.searchParams.get("itemId") ?? ""
+ }
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId, email } = await requirePermissions(
+ request,
+ {
+ create: "production"
+ }
+ );
+ requireAssembliesInternal(email);
+
+ const validation = await validator(
+ assemblyInstructionFromItemValidator
+ ).validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { itemId, modelUploadId } = validation.data;
+
+ // An explicitly provided model (e.g. from the part details page) wins when
+ // it is usable; otherwise derive it from the item's CAD files
+ let model: { id: string } | null = null;
+ let modelState: ReturnType<typeof getAssemblyModelState> = "none";
+
+ if (modelUploadId) {
+ const explicit = await client
+ .from("modelUpload")
+ .select("id, processingStatus, glbPath, graphPath, modelPath")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ const explicitState = getAssemblyModelState(explicit.data ?? null);
+ if (explicit.data && explicitState !== "none") {
+ model = explicit.data;
+ modelState = explicitState;
+ }
+ }
+
+ const derived = await getModelForItem(client, itemId, companyId);
+ if (!derived.item) {
+ return data(
+ {},
+ await flash(request, error(null, "Failed to load the selected item"))
+ );
+ }
+ if (!model && derived.model && derived.modelState !== "none") {
+ model = derived.model;
+ modelState = derived.modelState;
+ }
+
+ if (!model) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(
+ null,
+ "The selected item has no 3D model. Upload a STEP file on the item's Model tab first."
+ )
+ )
+ );
+ }
+
+ const create = await upsertAssemblyInstruction(client, {
+ name: derived.item.name || "Assembly",
+ modelUploadId: model.id,
+ itemId,
+ companyId,
+ createdBy: userId
+ });
+
+ if (create.error || !create.data?.id) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(create.error, "Failed to create assembly instruction")
+ )
+ );
+ }
+
+ // Lazy conversion: the geometry pipeline only runs for models that are
+ // actually used in an assembly. "processing" means a job is already in
+ // flight, so only kick one off for unconverted or previously failed models.
+ if (modelState === "convertible" || modelState === "failed") {
+ await trigger("assembly-convert", {
+ companyId,
+ modelUploadId: model.id,
+ userId
+ });
+ } else if (modelState === "converted") {
+ // Conversion chains motion planning, but a model converted before this
+ // instruction existed may have no plan yet — start planning now so the
+ // plan is ready by the time the author clicks Generate Steps.
+ const planJob = await getLatestAssemblyPlanJob(client, model.id);
+ const planStatus = planJob.data?.status;
+ if (
+ !planJob.data ||
+ (planStatus !== "Success" &&
+ planStatus !== "Processing" &&
+ planStatus !== "Queued")
+ ) {
+ // Pre-create the job row so the instruction page shows "planning" on
+ // first load; the worker adopts it via planJobId
+ const created = await createAssemblyPlanJob(client, {
+ modelUploadId: model.id,
+ companyId,
+ userId
+ });
+
+ await trigger("assembly-plan", {
+ companyId,
+ modelUploadId: model.id,
+ userId,
+ ...(created.data?.id ? { planJobId: created.data.id } : {})
+ });
+ }
+ }
+
+ throw redirect(
+ path.to.assemblyInstruction(create.data.id),
+ await flash(request, success("Assembly instruction created"))
+ );
+}
+
+export default function NewAssemblyInstructionRoute() {
+ const { initialValues } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ return (
+ <AssemblyInstructionForm
+ initialValues={initialValues}
+ onClose={() => navigate(path.to.assemblyInstructions)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/assemblies.tsx b/apps/erp/app/routes/x+/production+/assemblies.tsx
new file mode 100644
index 0000000000..a708bb8c19
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/assemblies.tsx
@@ -0,0 +1,52 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { VStack } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, useLoaderData } from "react-router";
+import { getAssemblyInstructions } from "~/modules/production";
+import { requireAssembliesInternal } from "~/modules/production/production.server";
+import AssemblyInstructionsTable from "~/modules/production/ui/Assemblies/AssemblyInstructionsTable";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: msg`Assemblies`,
+ to: path.to.assemblyInstructions
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, email } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+ requireAssembliesInternal(email);
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset } = getGenericQueryFilters(searchParams);
+
+ const instructions = await getAssemblyInstructions(client, {
+ companyId,
+ search: search ?? undefined,
+ limit,
+ offset
+ });
+
+ return {
+ instructions: instructions.data ?? [],
+ count: instructions.count ?? 0
+ };
+}
+
+export default function AssemblyInstructionsRoute() {
+ const { instructions, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <AssemblyInstructionsTable data={instructions} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index df7bd0e519..fbc5907d60 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -522,6 +522,68 @@ export const path = {
generatePath(`${x}/items/methods/versions/activate/${id}`),
activateGauge: (id: string) =>
generatePath(`${x}/quality/gauges/activate/${id}`),
+ assemblyInstruction: (id: string) => generatePath(`${x}/assembly/${id}`),
+ assemblyInstructions: `${x}/production/assemblies`,
+ assemblyInstructionStatus: (id: string) =>
+ generatePath(`${x}/assembly/${id}/status`),
+ assemblyModelConvert: (id: string) =>
+ generatePath(`${x}/assembly/${id}/model/convert`),
+ assemblyPlanRerun: (id: string) =>
+ generatePath(`${x}/assembly/${id}/plan/rerun`),
+ deleteAssemblyInstruction: (id: string) =>
+ generatePath(`${x}/assembly/delete/${id}`),
+ newAssemblyInstruction: `${x}/production/assemblies/new`,
+ newAssemblyInstructionStep: (id: string) =>
+ generatePath(`${x}/assembly/${id}/steps/new`),
+ assemblyInstructionStep: (id: string, stepId: string) =>
+ generatePath(`${x}/assembly/${id}/steps/${stepId}`),
+ assemblyInstructionStepMotion: (id: string, stepId: string) =>
+ generatePath(`${x}/assembly/${id}/steps/motion/${stepId}`),
+ assemblyInstructionStepComponents: (id: string, stepId: string) =>
+ generatePath(`${x}/assembly/${id}/steps/components/${stepId}`),
+ deleteAssemblyInstructionStep: (id: string, stepId: string) =>
+ generatePath(`${x}/assembly/${id}/steps/delete/${stepId}`),
+ assemblyInstructionStepOrder: (id: string) =>
+ generatePath(`${x}/assembly/${id}/steps/order`),
+ assemblyInstructionStepStatus: (id: string, stepId: string) =>
+ generatePath(`${x}/assembly/${id}/steps/status/${stepId}`),
+ generateAssemblyInstructionSteps: (id: string) =>
+ generatePath(`${x}/assembly/${id}/steps/generate`),
+ newAssemblyStepRequirement: (id: string) =>
+ generatePath(`${x}/assembly/${id}/requirements/new`),
+ assemblyStepRequirement: (id: string, requirementId: string) =>
+ generatePath(`${x}/assembly/${id}/requirements/${requirementId}`),
+ deleteAssemblyStepRequirement: (id: string, requirementId: string) =>
+ generatePath(`${x}/assembly/${id}/requirements/delete/${requirementId}`),
+ assemblyStepRequirementOrder: (id: string) =>
+ generatePath(`${x}/assembly/${id}/requirements/order`),
+ newAssemblyStepMaterial: (id: string) =>
+ generatePath(`${x}/assembly/${id}/materials/new`),
+ assemblyStepMaterial: (id: string, materialId: string) =>
+ generatePath(`${x}/assembly/${id}/materials/${materialId}`),
+ deleteAssemblyStepMaterial: (id: string, materialId: string) =>
+ generatePath(`${x}/assembly/${id}/materials/delete/${materialId}`),
+ assemblyStepMaterialOrder: (id: string) =>
+ generatePath(`${x}/assembly/${id}/materials/order`),
+ newAssemblyUnit: (id: string) =>
+ generatePath(`${x}/assembly/${id}/units/new`),
+ updateAssemblyUnit: (id: string, unitId: string) =>
+ generatePath(`${x}/assembly/${id}/units/${unitId}`),
+ newAssemblyComponentMapping: (id: string) =>
+ generatePath(`${x}/assembly/${id}/component-mappings/new`),
+ deleteAssemblyComponentMapping: (id: string, mappingId: string) =>
+ generatePath(
+ `${x}/assembly/${id}/component-mappings/delete/${mappingId}`
+ ),
+ autoMatchAssemblyComponents: (id: string) =>
+ generatePath(`${x}/assembly/${id}/component-mappings/auto`),
+ deleteAssemblyUnit: (id: string, unitId: string) =>
+ generatePath(`${x}/assembly/${id}/units/delete/${unitId}`),
+ newAssemblyStandardNote: `${x}/assembly/standard-notes/new`,
+ assemblyStandardNote: (noteId: string) =>
+ generatePath(`${x}/assembly/standard-notes/${noteId}`),
+ deleteAssemblyStandardNote: (noteId: string) =>
+ generatePath(`${x}/assembly/standard-notes/delete/${noteId}`),
attribute: (id: string) => generatePath(`${x}/people/attribute/${id}`),
attributes: `${x}/people/attributes`,
apiDocs: "https://docs.carbon.ms/api-reference",
diff --git a/apps/erp/package.json b/apps/erp/package.json
index 1d708d84a4..1d0d6df767 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -29,6 +29,7 @@
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
+ "@carbon/viewer": "workspace:*",
"@dagrejs/dagre": "^1.1.4",
"@dnd-kit/core": "catalog:",
"@dnd-kit/sortable": "catalog:",
diff --git a/apps/mes/app/components/JobOperation/components/Assembly.tsx b/apps/mes/app/components/JobOperation/components/Assembly.tsx
new file mode 100644
index 0000000000..002aac7b93
--- /dev/null
+++ b/apps/mes/app/components/JobOperation/components/Assembly.tsx
@@ -0,0 +1,255 @@
+import type { Json } from "@carbon/database";
+import { Badge, Button, ClientOnly, cn, Spinner } from "@carbon/react";
+import type {
+ AssemblyStep,
+ CameraPose,
+ Fastener,
+ Motion
+} from "@carbon/viewer";
+import { AssemblyPlayer } from "@carbon/viewer";
+import { Trans } from "@lingui/react/macro";
+import { useMemo, useState } from "react";
+import {
+ LuChevronLeft,
+ LuChevronRight,
+ LuFileVideo,
+ LuInfo,
+ LuOctagonAlert,
+ LuTriangleAlert,
+ LuWrench
+} from "react-icons/lu";
+import { getPrivateUrl } from "~/utils/path";
+
+export type AssemblyInstructionData = {
+ name: string | null;
+ glbPath: string;
+ graphPath: string;
+ steps: {
+ id: string;
+ title: string | null;
+ instructionText: string | null;
+ componentNodeIds: string[];
+ motion: Json;
+ camera: Json | null;
+ fastener: Json | null;
+ durationSeconds: number | null;
+ warnings: Json | null;
+ }[];
+ requirements: {
+ id: string;
+ stepId: string;
+ type: "Tool" | "Fixture" | "Consumable" | "Note" | "Media";
+ name: string | null;
+ text: string | null;
+ severity: "Info" | "Caution" | "Warning" | null;
+ filePath: string | null;
+ quantity: number;
+ }[];
+};
+
+type StepRequirement = AssemblyInstructionData["requirements"][number];
+
+const motionTypes = ["linear", "L", "helix", "path", "none"];
+
+function toViewerStep(
+ step: AssemblyInstructionData["steps"][number]
+): AssemblyStep {
+ const motion = step.motion as Motion | null;
+ // Planner flag: no collision-free path — the player fades the components in
+ const warnings = step.warnings as { flagged?: boolean } | null;
+ return {
+ id: step.id,
+ title: step.title,
+ instructionText: step.instructionText,
+ componentNodeIds: step.componentNodeIds ?? [],
+ motion:
+ motion && typeof motion === "object" && motionTypes.includes(motion.type)
+ ? motion
+ : { type: "none" },
+ camera: (step.camera as CameraPose | null) ?? null,
+ fastener: (step.fastener as Fastener | null) ?? null,
+ durationSeconds: step.durationSeconds,
+ flagged: warnings?.flagged === true ? true : undefined
+ };
+}
+
+type AssemblyInstructionsProps = {
+ assembly: AssemblyInstructionData;
+ mode: "light" | "dark";
+};
+
+export function AssemblyInstructions({
+ assembly,
+ mode
+}: AssemblyInstructionsProps) {
+ const [activeStepIndex, setActiveStepIndex] = useState(0);
+
+ const steps = useMemo(
+ () => assembly.steps.map(toViewerStep),
+ [assembly.steps]
+ );
+
+ const stepCount = steps.length;
+ const activeStepId = assembly.steps[activeStepIndex]?.id;
+ const activeRequirements = useMemo(
+ () =>
+ (assembly.requirements ?? []).filter(
+ (requirement) => requirement.stepId === activeStepId
+ ),
+ [assembly.requirements, activeStepId]
+ );
+
+ return (
+ <div className="flex h-full w-full flex-col">
+ <div className="min-h-0 flex-1">
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ {() => (
+ <AssemblyPlayer
+ glbUrl={getPrivateUrl(assembly.glbPath)}
+ graphUrl={getPrivateUrl(assembly.graphPath)}
+ steps={steps}
+ activeStepIndex={activeStepIndex}
+ onStepChange={setActiveStepIndex}
+ readOnly
+ mode={mode}
+ className="h-full"
+ />
+ )}
+ </ClientOnly>
+ </div>
+ {activeRequirements.length > 0 && (
+ <StepRequirements requirements={activeRequirements} />
+ )}
+ <div className="grid grid-cols-2 gap-2 border-t border-border bg-background p-3">
+ <Button
+ size="lg"
+ variant="secondary"
+ className="h-16 text-lg active:scale-[0.96] transition-transform"
+ leftIcon={<LuChevronLeft className="size-6" />}
+ isDisabled={activeStepIndex <= 0}
+ onClick={() => setActiveStepIndex((index) => Math.max(index - 1, 0))}
+ >
+ <Trans>Previous</Trans>
+ </Button>
+ <Button
+ size="lg"
+ className="h-16 text-lg active:scale-[0.96] transition-transform"
+ rightIcon={<LuChevronRight className="size-6" />}
+ isDisabled={activeStepIndex >= stepCount - 1}
+ onClick={() =>
+ setActiveStepIndex((index) => Math.min(index + 1, stepCount - 1))
+ }
+ >
+ <Trans>Next</Trans>
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+const severityStyles = {
+ Info: { icon: LuInfo, className: "border-blue-500/40 text-blue-600" },
+ Caution: {
+ icon: LuTriangleAlert,
+ className: "border-yellow-500/40 text-yellow-600"
+ },
+ Warning: {
+ icon: LuOctagonAlert,
+ className: "border-red-500/40 text-red-600"
+ }
+} as const;
+
+/** The active step's process data: notes, tools/fixtures/consumables, media */
+function StepRequirements({
+ requirements
+}: {
+ requirements: StepRequirement[];
+}) {
+ const notes = requirements.filter((r) => r.type === "Note");
+ const resources = requirements.filter((r) =>
+ ["Tool", "Fixture", "Consumable"].includes(r.type)
+ );
+ const media = requirements.filter((r) => r.type === "Media" && r.filePath);
+
+ return (
+ <div className="max-h-56 overflow-y-auto border-t border-border bg-background px-3 py-2">
+ <div className="flex flex-col gap-2">
+ {notes.map((note) => {
+ const { icon: Icon, className } =
+ severityStyles[note.severity ?? "Info"];
+ return (
+ <div
+ key={note.id}
+ className={cn(
+ "flex items-start gap-2 rounded-md border px-3 py-2 text-sm",
+ className
+ )}
+ >
+ <Icon className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
+ <span className="whitespace-pre-wrap text-foreground">
+ {note.text}
+ </span>
+ </div>
+ );
+ })}
+ {resources.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <LuWrench
+ className="h-4 w-4 shrink-0 text-muted-foreground"
+ aria-hidden
+ />
+ {resources.map((resource) => (
+ <Badge key={resource.id} variant="secondary">
+ {resource.name}
+ {resource.quantity > 1 ? ` ×${resource.quantity}` : ""}
+ {resource.type !== "Tool" && (
+ <span className="ml-1 text-muted-foreground">
+ · {resource.type}
+ </span>
+ )}
+ </Badge>
+ ))}
+ </div>
+ )}
+ {media.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {media.map((item) => {
+ const url = getPrivateUrl(item.filePath ?? "");
+ const isVideo = /\.(mp4|mov|webm|avi|mkv)$/i.test(
+ item.filePath ?? ""
+ );
+ return (
+ <a
+ key={item.id}
+ href={url}
+ target="_blank"
+ rel="noreferrer"
+ className="block"
+ title={item.name ?? undefined}
+ >
+ {isVideo ? (
+ <span className="flex h-16 w-16 items-center justify-center rounded-md border border-border">
+ <LuFileVideo className="h-6 w-6 text-muted-foreground" />
+ </span>
+ ) : (
+ <img
+ src={url}
+ alt={item.name ?? "Attachment"}
+ className="h-16 w-16 rounded-md border border-border object-cover"
+ />
+ )}
+ </a>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 217df380c9..82d50acae7 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -17,6 +17,7 @@
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
+ "@carbon/viewer": "workspace:*",
"@dagrejs/dagre": "^1.1.4",
"@xyflow/react": "12.10.2",
"@dnd-kit/core": "catalog:",
diff --git a/package.json b/package.json
index f18c181a20..24956c5a66 100755
--- a/package.json
+++ b/package.json
@@ -63,9 +63,7 @@
"install-skills": "bash .ai/scripts/install-skills.sh",
"prepare": "pnpm exec husky install; if [ -f .ai/scripts/install-skills.sh ]; then bash .ai/scripts/install-skills.sh; fi",
"test": "turbo run test",
- "tool:new": "tsx scripts/create-tool.ts",
"translate": "pnpm run lingui:extract && pnpm exec linguito translate --llm && pnpm lingui:clean",
- "agent:new": "tsx scripts/create-agent.ts",
"typecheck": "turbo run typecheck --filter='*'",
"typegen": "turbo run typegen"
},
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 26ca1a8a49..50eca67379 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2014,6 +2014,1501 @@ export type Database = {
},
]
}
+ assemblyUnit: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string | null
+ modelUploadId: string
+ name: string
+ componentNodeIds: string[]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId?: string | null
+ modelUploadId: string
+ name: string
+ componentNodeIds?: string[]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string | null
+ modelUploadId?: string
+ name?: string
+ componentNodeIds?: string[]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstruction: {
+ Row: {
+ assemblyPlanJobId: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json | null
+ id: string
+ itemId: string | null
+ modelUploadId: string
+ name: string
+ publishedAt: string | null
+ settings: Json | null
+ status: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags: string[] | null
+ updatedAt: string | null
+ updatedBy: string | null
+ version: number
+ }
+ Insert: {
+ assemblyPlanJobId?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string | null
+ modelUploadId: string
+ name: string
+ publishedAt?: string | null
+ settings?: Json | null
+ status?: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags?: string[] | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ version?: number
+ }
+ Update: {
+ assemblyPlanJobId?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string | null
+ modelUploadId?: string
+ name?: string
+ publishedAt?: string | null
+ settings?: Json | null
+ status?: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags?: string[] | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ version?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstruction_assemblyPlanJobId_fkey"
+ columns: ["assemblyPlanJobId"]
+ isOneToOne: false
+ referencedRelation: "assemblyPlanJob"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStep: {
+ Row: {
+ assemblyInstructionId: string
+ camera: Json | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: Json | null
+ durationSeconds: number | null
+ explode: Json | null
+ fastener: Json | null
+ fileTypes: string[] | null
+ id: string
+ instructionText: string | null
+ listValues: string[] | null
+ maxValue: number | null
+ minValue: number | null
+ motion: Json
+ notes: Json | null
+ parentStepId: string | null
+ componentNodeIds: string[]
+ planConfidence: string
+ required: boolean | null
+ sortOrder: number
+ status: Database["public"]["Enums"]["assemblyStepStatus"]
+ title: string | null
+ type: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ warnings: Json | null
+ }
+ Insert: {
+ assemblyInstructionId: string
+ camera?: Json | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: Json | null
+ durationSeconds?: number | null
+ explode?: Json | null
+ fastener?: Json | null
+ fileTypes?: string[] | null
+ id?: string
+ instructionText?: string | null
+ listValues?: string[] | null
+ maxValue?: number | null
+ minValue?: number | null
+ motion?: Json
+ notes?: Json | null
+ parentStepId?: string | null
+ componentNodeIds?: string[]
+ planConfidence?: string
+ required?: boolean | null
+ sortOrder?: number
+ status?: Database["public"]["Enums"]["assemblyStepStatus"]
+ title?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ warnings?: Json | null
+ }
+ Update: {
+ assemblyInstructionId?: string
+ camera?: Json | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: Json | null
+ durationSeconds?: number | null
+ explode?: Json | null
+ fastener?: Json | null
+ fileTypes?: string[] | null
+ id?: string
+ instructionText?: string | null
+ listValues?: string[] | null
+ maxValue?: number | null
+ minValue?: number | null
+ motion?: Json
+ notes?: Json | null
+ parentStepId?: string | null
+ componentNodeIds?: string[]
+ planConfidence?: string
+ required?: boolean | null
+ sortOrder?: number
+ status?: Database["public"]["Enums"]["assemblyStepStatus"]
+ title?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ warnings?: Json | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStep_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_parentStepId_fkey"
+ columns: ["parentStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStepMaterial: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ quantity: number | null
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ quantity?: number | null
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ quantity?: number | null
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStepRequirement: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ filePath: string | null
+ id: string
+ itemId: string | null
+ name: string | null
+ quantity: number
+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder: number
+ stepId: string
+ text: string | null
+ type: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ filePath?: string | null
+ id?: string
+ itemId?: string | null
+ name?: string | null
+ quantity?: number
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder?: number
+ stepId: string
+ text?: string | null
+ type: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ filePath?: string | null
+ id?: string
+ itemId?: string | null
+ name?: string | null
+ quantity?: number
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder?: number
+ stepId?: string
+ text?: string | null
+ type?: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyComponentMapping: {
+ Row: {
+ companyId: string
+ confidence: string
+ createdAt: string
+ createdBy: string
+ geometryHash: string
+ id: string
+ itemId: string
+ modelUploadId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ confidence?: string
+ createdAt?: string
+ createdBy: string
+ geometryHash: string
+ id?: string
+ itemId: string
+ modelUploadId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ confidence?: string
+ createdAt?: string
+ createdBy?: string
+ geometryHash?: string
+ id?: string
+ itemId?: string
+ modelUploadId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyPlanJob: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ error: string | null
+ id: string
+ kind: string
+ modelUploadId: string
+ planPath: string | null
+ stats: Json | null
+ status: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ error?: string | null
+ id?: string
+ kind: string
+ modelUploadId: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ error?: string | null
+ id?: string
+ kind?: string
+ modelUploadId?: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ ]
+ }
+ assemblyStandardNote: {
+ Row: {
+ companyId: string
+ content: string
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ content: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ content?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
attributeDataType: {
Row: {
id: number
@@ -18003,6 +19498,7 @@ export type Database = {
}
jobOperation: {
Row: {
+ assemblyInstructionId: string | null
assignee: string | null
companyId: string
conflictReason: string | null
@@ -18050,6 +19546,7 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
assignee?: string | null
companyId: string
conflictReason?: string | null
@@ -18097,6 +19594,7 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
assignee?: string | null
companyId?: string
conflictReason?: string | null
@@ -18144,6 +19642,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_assignee_fkey"
columns: ["assignee"]
@@ -23646,6 +25151,7 @@ export type Database = {
}
methodOperation: {
Row: {
+ assemblyInstructionId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -23675,6 +25181,7 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -23704,6 +25211,7 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -23733,6 +25241,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "methodOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperation_companyId_fkey"
columns: ["companyId"]
@@ -24373,9 +25888,15 @@ export type Database = {
companyId: string
createdAt: string | null
createdBy: string
+ glbPath: string | null
+ graphPath: string | null
id: string
modelPath: string
name: string | null
+ componentCount: number | null
+ processedAt: string | null
+ processingError: string | null
+ processingStatus: Database["public"]["Enums"]["modelProcessingStatus"]
size: number | null
thumbnailPath: string | null
updatedAt: string | null
@@ -24386,9 +25907,15 @@ export type Database = {
companyId: string
createdAt?: string | null
createdBy: string
+ glbPath?: string | null
+ graphPath?: string | null
id?: string
modelPath: string
name?: string | null
+ componentCount?: number | null
+ processedAt?: string | null
+ processingError?: string | null
+ processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
size?: number | null
thumbnailPath?: string | null
updatedAt?: string | null
@@ -24399,9 +25926,15 @@ export type Database = {
companyId?: string
createdAt?: string | null
createdBy?: string
+ glbPath?: string | null
+ graphPath?: string | null
id?: string
modelPath?: string
name?: string | null
+ componentCount?: number | null
+ processedAt?: string | null
+ processingError?: string | null
+ processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
size?: number | null
thumbnailPath?: string | null
updatedAt?: string | null
@@ -41892,6 +43425,48 @@ export type Database = {
},
]
}
+ searchIndex_d92ruirr60h02dftaka0: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -55530,6 +57105,7 @@ export type Database = {
}
jobOperationsWithDependencies: {
Row: {
+ assemblyInstructionId: string | null
assignee: string | null
companyId: string | null
conflictReason: string | null
@@ -55579,399 +57155,416 @@ export type Database = {
workCenterId: string | null
workInstruction: Json | null
}
- Insert: {
- assignee?: string | null
- companyId?: string | null
- conflictReason?: string | null
- createdAt?: string | null
- createdBy?: string | null
- customFields?: Json | null
- dependencies?: never
- description?: string | null
- dueDate?: string | null
- hasConflict?: boolean | null
- id?: string | null
- jobId?: string | null
- jobMakeMethodId?: string | null
- laborRate?: number | null
- laborTime?: number | null
- laborUnit?: Database["public"]["Enums"]["factor"] | null
- machineRate?: number | null
- machineTime?: number | null
- machineUnit?: Database["public"]["Enums"]["factor"] | null
- manuallyScheduled?: boolean | null
- operationLeadTime?: number | null
- operationMinimumCost?: number | null
- operationOrder?:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity?: number | null
- operationSupplierProcessId?: string | null
- operationType?: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost?: number | null
- order?: number | null
- overheadRate?: number | null
- priority?: number | null
- procedureId?: string | null
- processId?: string | null
- quantityComplete?: number | null
- quantityReworked?: number | null
- quantityScrapped?: number | null
- reworkId?: string | null
- setupTime?: number | null
- setupUnit?: Database["public"]["Enums"]["factor"] | null
- startDate?: string | null
- status?: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags?: string[] | null
- targetQuantity?: number | null
- updatedAt?: string | null
- updatedBy?: string | null
- workCenterId?: string | null
- workInstruction?: Json | null
- }
- Update: {
- assignee?: string | null
- companyId?: string | null
- conflictReason?: string | null
- createdAt?: string | null
- createdBy?: string | null
- customFields?: Json | null
- dependencies?: never
- description?: string | null
- dueDate?: string | null
- hasConflict?: boolean | null
- id?: string | null
- jobId?: string | null
- jobMakeMethodId?: string | null
- laborRate?: number | null
- laborTime?: number | null
- laborUnit?: Database["public"]["Enums"]["factor"] | null
- machineRate?: number | null
- machineTime?: number | null
- machineUnit?: Database["public"]["Enums"]["factor"] | null
- manuallyScheduled?: boolean | null
- operationLeadTime?: number | null
- operationMinimumCost?: number | null
- operationOrder?:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity?: number | null
- operationSupplierProcessId?: string | null
- operationType?: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost?: number | null
- order?: number | null
- overheadRate?: number | null
- priority?: number | null
- procedureId?: string | null
- processId?: string | null
- quantityComplete?: number | null
- quantityReworked?: number | null
- quantityScrapped?: number | null
- reworkId?: string | null
- setupTime?: number | null
- setupUnit?: Database["public"]["Enums"]["factor"] | null
- startDate?: string | null
- status?: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags?: string[] | null
- targetQuantity?: number | null
- updatedAt?: string | null
- updatedBy?: string | null
- workCenterId?: string | null
- workInstruction?: Json | null
- }
+ Insert: {
+ assemblyInstructionId?: string | null
+ assignee?: string | null
+ companyId?: string | null
+ conflictReason?: string | null
+ createdAt?: string | null
+ createdBy?: string | null
+ customFields?: Json | null
+ dependencies?: never
+ description?: string | null
+ dueDate?: string | null
+ hasConflict?: boolean | null
+ id?: string | null
+ jobId?: string | null
+ jobMakeMethodId?: string | null
+ laborRate?: number | null
+ laborTime?: number | null
+ laborUnit?: Database["public"]["Enums"]["factor"] | null
+ machineRate?: number | null
+ machineTime?: number | null
+ machineUnit?: Database["public"]["Enums"]["factor"] | null
+ manuallyScheduled?: boolean | null
+ operationLeadTime?: number | null
+ operationMinimumCost?: number | null
+ operationOrder?:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity?: number | null
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost?: number | null
+ order?: number | null
+ overheadRate?: number | null
+ priority?: number | null
+ procedureId?: string | null
+ processId?: string | null
+ quantityComplete?: number | null
+ quantityReworked?: number | null
+ quantityScrapped?: number | null
+ reworkId?: string | null
+ setupTime?: number | null
+ setupUnit?: Database["public"]["Enums"]["factor"] | null
+ startDate?: string | null
+ status?: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags?: string[] | null
+ targetQuantity?: number | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string | null
+ workInstruction?: Json | null
+ }
+ Update: {
+ assemblyInstructionId?: string | null
+ assignee?: string | null
+ companyId?: string | null
+ conflictReason?: string | null
+ createdAt?: string | null
+ createdBy?: string | null
+ customFields?: Json | null
+ dependencies?: never
+ description?: string | null
+ dueDate?: string | null
+ hasConflict?: boolean | null
+ id?: string | null
+ jobId?: string | null
+ jobMakeMethodId?: string | null
+ laborRate?: number | null
+ laborTime?: number | null
+ laborUnit?: Database["public"]["Enums"]["factor"] | null
+ machineRate?: number | null
+ machineTime?: number | null
+ machineUnit?: Database["public"]["Enums"]["factor"] | null
+ manuallyScheduled?: boolean | null
+ operationLeadTime?: number | null
+ operationMinimumCost?: number | null
+ operationOrder?:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity?: number | null
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost?: number | null
+ order?: number | null
+ overheadRate?: number | null
+ priority?: number | null
+ procedureId?: string | null
+ processId?: string | null
+ quantityComplete?: number | null
+ quantityReworked?: number | null
+ quantityScrapped?: number | null
+ reworkId?: string | null
+ setupTime?: number | null
+ setupUnit?: Database["public"]["Enums"]["factor"] | null
+ startDate?: string | null
+ status?: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags?: string[] | null
+ targetQuantity?: number | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string | null
+ workInstruction?: Json | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["jobMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "process"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "processes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_reworkId_fkey"
+ columns: ["reworkId"]
+ isOneToOne: false
+ referencedRelation: "rework"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "riskRegisters"
+ referencedColumns: ["workCenterId"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ jobOperationsWithMakeMethods: {
+ Row: {
+ assemblyInstructionId: string | null
+ assignee: string | null
+ companyId: string | null
+ conflictReason: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ description: string | null
+ dueDate: string | null
+ hasConflict: boolean | null
+ id: string | null
+ jobId: string | null
+ jobMakeMethodId: string | null
+ laborRate: number | null
+ laborTime: number | null
+ laborUnit: Database["public"]["Enums"]["factor"] | null
+ machineRate: number | null
+ machineTime: number | null
+ machineUnit: Database["public"]["Enums"]["factor"] | null
+ makeMethodId: string | null
+ manuallyScheduled: boolean | null
+ operationLeadTime: number | null
+ operationMinimumCost: number | null
+ operationOrder:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity: number | null
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost: number | null
+ order: number | null
+ overheadRate: number | null
+ priority: number | null
+ procedureId: string | null
+ processId: string | null
+ quantityComplete: number | null
+ quantityReworked: number | null
+ quantityScrapped: number | null
+ reworkId: string | null
+ setupTime: number | null
+ setupUnit: Database["public"]["Enums"]["factor"] | null
+ startDate: string | null
+ status: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags: string[] | null
+ targetQuantity: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string | null
+ workInstruction: Json | null
+ }
Relationships: [
{
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "job"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "openProductionOrders"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobMakeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobMaterialWithMakeMethodId"
- referencedColumns: ["jobMaterialMakeMethodId"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["jobMakeMethodId"]
- },
- {
- foreignKeyName: "jobOperation_procedureId_fkey"
- columns: ["procedureId"]
- isOneToOne: false
- referencedRelation: "procedure"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_procedureId_fkey"
- columns: ["procedureId"]
- isOneToOne: false
- referencedRelation: "procedures"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_processId_fkey"
- columns: ["processId"]
- isOneToOne: false
- referencedRelation: "process"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_processId_fkey"
- columns: ["processId"]
- isOneToOne: false
- referencedRelation: "processes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_reworkId_fkey"
- columns: ["reworkId"]
- isOneToOne: false
- referencedRelation: "rework"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
+ referencedRelation: "assemblyInstruction"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "riskRegisters"
- referencedColumns: ["workCenterId"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenter"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenters"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCentersWithBlockingStatus"
- referencedColumns: ["id"]
- },
- ]
- }
- jobOperationsWithMakeMethods: {
- Row: {
- assignee: string | null
- companyId: string | null
- conflictReason: string | null
- createdAt: string | null
- createdBy: string | null
- customFields: Json | null
- description: string | null
- dueDate: string | null
- hasConflict: boolean | null
- id: string | null
- jobId: string | null
- jobMakeMethodId: string | null
- laborRate: number | null
- laborTime: number | null
- laborUnit: Database["public"]["Enums"]["factor"] | null
- machineRate: number | null
- machineTime: number | null
- machineUnit: Database["public"]["Enums"]["factor"] | null
- makeMethodId: string | null
- manuallyScheduled: boolean | null
- operationLeadTime: number | null
- operationMinimumCost: number | null
- operationOrder:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity: number | null
- operationSupplierProcessId: string | null
- operationType: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost: number | null
- order: number | null
- overheadRate: number | null
- priority: number | null
- procedureId: string | null
- processId: string | null
- quantityComplete: number | null
- quantityReworked: number | null
- quantityScrapped: number | null
- reworkId: string | null
- setupTime: number | null
- setupUnit: Database["public"]["Enums"]["factor"] | null
- startDate: string | null
- status: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags: string[] | null
- targetQuantity: number | null
- updatedAt: string | null
- updatedBy: string | null
- workCenterId: string | null
- workInstruction: Json | null
- }
- Relationships: [
{
foreignKeyName: "jobOperation_assignee_fkey"
columns: ["assignee"]
@@ -69557,6 +71150,15 @@ export type Database = {
| "Investments"
approvalDocumentType: "purchaseOrder" | "qualityDocument" | "supplier"
approvalStatus: "Pending" | "Approved" | "Rejected" | "Cancelled"
+ assemblyInstructionStatus: "Draft" | "Published" | "Archived"
+ assemblyNoteSeverity: "Info" | "Caution" | "Warning"
+ assemblyRequirementType:
+ | "Tool"
+ | "Fixture"
+ | "Consumable"
+ | "Note"
+ | "Media"
+ assemblyStepStatus: "Todo" | "Review" | "Done"
configurationParameterDataType:
| "text"
| "numeric"
@@ -69877,6 +71479,12 @@ export type Database = {
memoStatus: "Draft" | "Posted" | "Voided"
methodOperationOrder: "After Previous" | "With Previous"
methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order"
+ modelProcessingStatus:
+ | "Idle"
+ | "Queued"
+ | "Processing"
+ | "Success"
+ | "Failed"
module:
| "Accounting"
| "Documents"
@@ -70871,6 +72479,16 @@ export const Constants = {
],
approvalDocumentType: ["purchaseOrder", "qualityDocument", "supplier"],
approvalStatus: ["Pending", "Approved", "Rejected", "Cancelled"],
+ assemblyInstructionStatus: ["Draft", "Published", "Archived"],
+ assemblyNoteSeverity: ["Info", "Caution", "Warning"],
+ assemblyRequirementType: [
+ "Tool",
+ "Fixture",
+ "Consumable",
+ "Note",
+ "Media",
+ ],
+ assemblyStepStatus: ["Todo", "Review", "Done"],
configurationParameterDataType: [
"text",
"numeric",
@@ -71222,6 +72840,13 @@ export const Constants = {
memoStatus: ["Draft", "Posted", "Voided"],
methodOperationOrder: ["After Previous", "With Previous"],
methodType: ["Purchase to Order", "Pull from Inventory", "Make to Order"],
+ modelProcessingStatus: [
+ "Idle",
+ "Queued",
+ "Processing",
+ "Success",
+ "Failed",
+ ],
module: [
"Accounting",
"Documents",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 26ca1a8a49..50eca67379 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2014,6 +2014,1501 @@ export type Database = {
},
]
}
+ assemblyUnit: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string | null
+ modelUploadId: string
+ name: string
+ componentNodeIds: string[]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId?: string | null
+ modelUploadId: string
+ name: string
+ componentNodeIds?: string[]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string | null
+ modelUploadId?: string
+ name?: string
+ componentNodeIds?: string[]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyUnit_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstruction: {
+ Row: {
+ assemblyPlanJobId: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json | null
+ id: string
+ itemId: string | null
+ modelUploadId: string
+ name: string
+ publishedAt: string | null
+ settings: Json | null
+ status: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags: string[] | null
+ updatedAt: string | null
+ updatedBy: string | null
+ version: number
+ }
+ Insert: {
+ assemblyPlanJobId?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string | null
+ modelUploadId: string
+ name: string
+ publishedAt?: string | null
+ settings?: Json | null
+ status?: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags?: string[] | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ version?: number
+ }
+ Update: {
+ assemblyPlanJobId?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string | null
+ modelUploadId?: string
+ name?: string
+ publishedAt?: string | null
+ settings?: Json | null
+ status?: Database["public"]["Enums"]["assemblyInstructionStatus"]
+ tags?: string[] | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ version?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstruction_assemblyPlanJobId_fkey"
+ columns: ["assemblyPlanJobId"]
+ isOneToOne: false
+ referencedRelation: "assemblyPlanJob"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStep: {
+ Row: {
+ assemblyInstructionId: string
+ camera: Json | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ description: Json | null
+ durationSeconds: number | null
+ explode: Json | null
+ fastener: Json | null
+ fileTypes: string[] | null
+ id: string
+ instructionText: string | null
+ listValues: string[] | null
+ maxValue: number | null
+ minValue: number | null
+ motion: Json
+ notes: Json | null
+ parentStepId: string | null
+ componentNodeIds: string[]
+ planConfidence: string
+ required: boolean | null
+ sortOrder: number
+ status: Database["public"]["Enums"]["assemblyStepStatus"]
+ title: string | null
+ type: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ warnings: Json | null
+ }
+ Insert: {
+ assemblyInstructionId: string
+ camera?: Json | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ description?: Json | null
+ durationSeconds?: number | null
+ explode?: Json | null
+ fastener?: Json | null
+ fileTypes?: string[] | null
+ id?: string
+ instructionText?: string | null
+ listValues?: string[] | null
+ maxValue?: number | null
+ minValue?: number | null
+ motion?: Json
+ notes?: Json | null
+ parentStepId?: string | null
+ componentNodeIds?: string[]
+ planConfidence?: string
+ required?: boolean | null
+ sortOrder?: number
+ status?: Database["public"]["Enums"]["assemblyStepStatus"]
+ title?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ warnings?: Json | null
+ }
+ Update: {
+ assemblyInstructionId?: string
+ camera?: Json | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ description?: Json | null
+ durationSeconds?: number | null
+ explode?: Json | null
+ fastener?: Json | null
+ fileTypes?: string[] | null
+ id?: string
+ instructionText?: string | null
+ listValues?: string[] | null
+ maxValue?: number | null
+ minValue?: number | null
+ motion?: Json
+ notes?: Json | null
+ parentStepId?: string | null
+ componentNodeIds?: string[]
+ planConfidence?: string
+ required?: boolean | null
+ sortOrder?: number
+ status?: Database["public"]["Enums"]["assemblyStepStatus"]
+ title?: string | null
+ type?: Database["public"]["Enums"]["procedureStepType"]
+ unitOfMeasureCode?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ warnings?: Json | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStep_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_parentStepId_fkey"
+ columns: ["parentStepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStep_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStepMaterial: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ itemId: string
+ quantity: number | null
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ itemId: string
+ quantity?: number | null
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ itemId?: string
+ quantity?: number | null
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyInstructionStepRequirement: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ filePath: string | null
+ id: string
+ itemId: string | null
+ name: string | null
+ quantity: number
+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder: number
+ stepId: string
+ text: string | null
+ type: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ filePath?: string | null
+ id?: string
+ itemId?: string | null
+ name?: string | null
+ quantity?: number
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder?: number
+ stepId: string
+ text?: string | null
+ type: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ filePath?: string | null
+ id?: string
+ itemId?: string | null
+ name?: string | null
+ quantity?: number
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"] | null
+ sortOrder?: number
+ stepId?: string
+ text?: string | null
+ type?: Database["public"]["Enums"]["assemblyRequirementType"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructionStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyInstructionStepRequirement_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyComponentMapping: {
+ Row: {
+ companyId: string
+ confidence: string
+ createdAt: string
+ createdBy: string
+ geometryHash: string
+ id: string
+ itemId: string
+ modelUploadId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ confidence?: string
+ createdAt?: string
+ createdBy: string
+ geometryHash: string
+ id?: string
+ itemId: string
+ modelUploadId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ confidence?: string
+ createdAt?: string
+ createdBy?: string
+ geometryHash?: string
+ id?: string
+ itemId?: string
+ modelUploadId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ assemblyPlanJob: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ error: string | null
+ id: string
+ kind: string
+ modelUploadId: string
+ planPath: string | null
+ stats: Json | null
+ status: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ error?: string | null
+ id?: string
+ kind: string
+ modelUploadId: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ error?: string | null
+ id?: string
+ kind?: string
+ modelUploadId?: string
+ planPath?: string | null
+ stats?: Json | null
+ status?: Database["public"]["Enums"]["modelProcessingStatus"]
+ updatedAt?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["modelId"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "modelUpload"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"
+ columns: ["modelUploadId"]
+ isOneToOne: false
+ referencedRelation: "salesRfqLines"
+ referencedColumns: ["modelId"]
+ },
+ ]
+ }
+ assemblyStandardNote: {
+ Row: {
+ companyId: string
+ content: string
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ content: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ content?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
attributeDataType: {
Row: {
id: number
@@ -18003,6 +19498,7 @@ export type Database = {
}
jobOperation: {
Row: {
+ assemblyInstructionId: string | null
assignee: string | null
companyId: string
conflictReason: string | null
@@ -18050,6 +19546,7 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
assignee?: string | null
companyId: string
conflictReason?: string | null
@@ -18097,6 +19594,7 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
assignee?: string | null
companyId?: string
conflictReason?: string | null
@@ -18144,6 +19642,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_assignee_fkey"
columns: ["assignee"]
@@ -23646,6 +25151,7 @@ export type Database = {
}
methodOperation: {
Row: {
+ assemblyInstructionId: string | null
companyId: string
createdAt: string
createdBy: string
@@ -23675,6 +25181,7 @@ export type Database = {
workInstruction: Json
}
Insert: {
+ assemblyInstructionId?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -23704,6 +25211,7 @@ export type Database = {
workInstruction?: Json
}
Update: {
+ assemblyInstructionId?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -23733,6 +25241,13 @@ export type Database = {
workInstruction?: Json
}
Relationships: [
+ {
+ foreignKeyName: "methodOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperation_companyId_fkey"
columns: ["companyId"]
@@ -24373,9 +25888,15 @@ export type Database = {
companyId: string
createdAt: string | null
createdBy: string
+ glbPath: string | null
+ graphPath: string | null
id: string
modelPath: string
name: string | null
+ componentCount: number | null
+ processedAt: string | null
+ processingError: string | null
+ processingStatus: Database["public"]["Enums"]["modelProcessingStatus"]
size: number | null
thumbnailPath: string | null
updatedAt: string | null
@@ -24386,9 +25907,15 @@ export type Database = {
companyId: string
createdAt?: string | null
createdBy: string
+ glbPath?: string | null
+ graphPath?: string | null
id?: string
modelPath: string
name?: string | null
+ componentCount?: number | null
+ processedAt?: string | null
+ processingError?: string | null
+ processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
size?: number | null
thumbnailPath?: string | null
updatedAt?: string | null
@@ -24399,9 +25926,15 @@ export type Database = {
companyId?: string
createdAt?: string | null
createdBy?: string
+ glbPath?: string | null
+ graphPath?: string | null
id?: string
modelPath?: string
name?: string | null
+ componentCount?: number | null
+ processedAt?: string | null
+ processingError?: string | null
+ processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
size?: number | null
thumbnailPath?: string | null
updatedAt?: string | null
@@ -41892,6 +43425,48 @@ export type Database = {
},
]
}
+ searchIndex_d92ruirr60h02dftaka0: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -55530,6 +57105,7 @@ export type Database = {
}
jobOperationsWithDependencies: {
Row: {
+ assemblyInstructionId: string | null
assignee: string | null
companyId: string | null
conflictReason: string | null
@@ -55579,399 +57155,416 @@ export type Database = {
workCenterId: string | null
workInstruction: Json | null
}
- Insert: {
- assignee?: string | null
- companyId?: string | null
- conflictReason?: string | null
- createdAt?: string | null
- createdBy?: string | null
- customFields?: Json | null
- dependencies?: never
- description?: string | null
- dueDate?: string | null
- hasConflict?: boolean | null
- id?: string | null
- jobId?: string | null
- jobMakeMethodId?: string | null
- laborRate?: number | null
- laborTime?: number | null
- laborUnit?: Database["public"]["Enums"]["factor"] | null
- machineRate?: number | null
- machineTime?: number | null
- machineUnit?: Database["public"]["Enums"]["factor"] | null
- manuallyScheduled?: boolean | null
- operationLeadTime?: number | null
- operationMinimumCost?: number | null
- operationOrder?:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity?: number | null
- operationSupplierProcessId?: string | null
- operationType?: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost?: number | null
- order?: number | null
- overheadRate?: number | null
- priority?: number | null
- procedureId?: string | null
- processId?: string | null
- quantityComplete?: number | null
- quantityReworked?: number | null
- quantityScrapped?: number | null
- reworkId?: string | null
- setupTime?: number | null
- setupUnit?: Database["public"]["Enums"]["factor"] | null
- startDate?: string | null
- status?: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags?: string[] | null
- targetQuantity?: number | null
- updatedAt?: string | null
- updatedBy?: string | null
- workCenterId?: string | null
- workInstruction?: Json | null
- }
- Update: {
- assignee?: string | null
- companyId?: string | null
- conflictReason?: string | null
- createdAt?: string | null
- createdBy?: string | null
- customFields?: Json | null
- dependencies?: never
- description?: string | null
- dueDate?: string | null
- hasConflict?: boolean | null
- id?: string | null
- jobId?: string | null
- jobMakeMethodId?: string | null
- laborRate?: number | null
- laborTime?: number | null
- laborUnit?: Database["public"]["Enums"]["factor"] | null
- machineRate?: number | null
- machineTime?: number | null
- machineUnit?: Database["public"]["Enums"]["factor"] | null
- manuallyScheduled?: boolean | null
- operationLeadTime?: number | null
- operationMinimumCost?: number | null
- operationOrder?:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity?: number | null
- operationSupplierProcessId?: string | null
- operationType?: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost?: number | null
- order?: number | null
- overheadRate?: number | null
- priority?: number | null
- procedureId?: string | null
- processId?: string | null
- quantityComplete?: number | null
- quantityReworked?: number | null
- quantityScrapped?: number | null
- reworkId?: string | null
- setupTime?: number | null
- setupUnit?: Database["public"]["Enums"]["factor"] | null
- startDate?: string | null
- status?: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags?: string[] | null
- targetQuantity?: number | null
- updatedAt?: string | null
- updatedBy?: string | null
- workCenterId?: string | null
- workInstruction?: Json | null
- }
+ Insert: {
+ assemblyInstructionId?: string | null
+ assignee?: string | null
+ companyId?: string | null
+ conflictReason?: string | null
+ createdAt?: string | null
+ createdBy?: string | null
+ customFields?: Json | null
+ dependencies?: never
+ description?: string | null
+ dueDate?: string | null
+ hasConflict?: boolean | null
+ id?: string | null
+ jobId?: string | null
+ jobMakeMethodId?: string | null
+ laborRate?: number | null
+ laborTime?: number | null
+ laborUnit?: Database["public"]["Enums"]["factor"] | null
+ machineRate?: number | null
+ machineTime?: number | null
+ machineUnit?: Database["public"]["Enums"]["factor"] | null
+ manuallyScheduled?: boolean | null
+ operationLeadTime?: number | null
+ operationMinimumCost?: number | null
+ operationOrder?:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity?: number | null
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost?: number | null
+ order?: number | null
+ overheadRate?: number | null
+ priority?: number | null
+ procedureId?: string | null
+ processId?: string | null
+ quantityComplete?: number | null
+ quantityReworked?: number | null
+ quantityScrapped?: number | null
+ reworkId?: string | null
+ setupTime?: number | null
+ setupUnit?: Database["public"]["Enums"]["factor"] | null
+ startDate?: string | null
+ status?: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags?: string[] | null
+ targetQuantity?: number | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string | null
+ workInstruction?: Json | null
+ }
+ Update: {
+ assemblyInstructionId?: string | null
+ assignee?: string | null
+ companyId?: string | null
+ conflictReason?: string | null
+ createdAt?: string | null
+ createdBy?: string | null
+ customFields?: Json | null
+ dependencies?: never
+ description?: string | null
+ dueDate?: string | null
+ hasConflict?: boolean | null
+ id?: string | null
+ jobId?: string | null
+ jobMakeMethodId?: string | null
+ laborRate?: number | null
+ laborTime?: number | null
+ laborUnit?: Database["public"]["Enums"]["factor"] | null
+ machineRate?: number | null
+ machineTime?: number | null
+ machineUnit?: Database["public"]["Enums"]["factor"] | null
+ manuallyScheduled?: boolean | null
+ operationLeadTime?: number | null
+ operationMinimumCost?: number | null
+ operationOrder?:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity?: number | null
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost?: number | null
+ order?: number | null
+ overheadRate?: number | null
+ priority?: number | null
+ procedureId?: string | null
+ processId?: string | null
+ quantityComplete?: number | null
+ quantityReworked?: number | null
+ quantityScrapped?: number | null
+ reworkId?: string | null
+ setupTime?: number | null
+ setupUnit?: Database["public"]["Enums"]["factor"] | null
+ startDate?: string | null
+ status?: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags?: string[] | null
+ targetQuantity?: number | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string | null
+ workInstruction?: Json | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperation_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["jobMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedure"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_procedureId_fkey"
+ columns: ["procedureId"]
+ isOneToOne: false
+ referencedRelation: "procedures"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "process"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "processes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_reworkId_fkey"
+ columns: ["reworkId"]
+ isOneToOne: false
+ referencedRelation: "rework"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "riskRegisters"
+ referencedColumns: ["workCenterId"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_workCenterId_fkey"
+ columns: ["workCenterId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ jobOperationsWithMakeMethods: {
+ Row: {
+ assemblyInstructionId: string | null
+ assignee: string | null
+ companyId: string | null
+ conflictReason: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ description: string | null
+ dueDate: string | null
+ hasConflict: boolean | null
+ id: string | null
+ jobId: string | null
+ jobMakeMethodId: string | null
+ laborRate: number | null
+ laborTime: number | null
+ laborUnit: Database["public"]["Enums"]["factor"] | null
+ machineRate: number | null
+ machineTime: number | null
+ machineUnit: Database["public"]["Enums"]["factor"] | null
+ makeMethodId: string | null
+ manuallyScheduled: boolean | null
+ operationLeadTime: number | null
+ operationMinimumCost: number | null
+ operationOrder:
+ | Database["public"]["Enums"]["methodOperationOrder"]
+ | null
+ operationQuantity: number | null
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost: number | null
+ order: number | null
+ overheadRate: number | null
+ priority: number | null
+ procedureId: string | null
+ processId: string | null
+ quantityComplete: number | null
+ quantityReworked: number | null
+ quantityScrapped: number | null
+ reworkId: string | null
+ setupTime: number | null
+ setupUnit: Database["public"]["Enums"]["factor"] | null
+ startDate: string | null
+ status: Database["public"]["Enums"]["jobOperationStatus"] | null
+ tags: string[] | null
+ targetQuantity: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string | null
+ workInstruction: Json | null
+ }
Relationships: [
{
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_assignee_fkey"
- columns: ["assignee"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperation_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "job"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobId_fkey"
- columns: ["jobId"]
- isOneToOne: false
- referencedRelation: "openProductionOrders"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobMakeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobMaterialWithMakeMethodId"
- referencedColumns: ["jobMaterialMakeMethodId"]
- },
- {
- foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
- columns: ["jobMakeMethodId"]
- isOneToOne: false
- referencedRelation: "jobs"
- referencedColumns: ["jobMakeMethodId"]
- },
- {
- foreignKeyName: "jobOperation_procedureId_fkey"
- columns: ["procedureId"]
- isOneToOne: false
- referencedRelation: "procedure"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_procedureId_fkey"
- columns: ["procedureId"]
- isOneToOne: false
- referencedRelation: "procedures"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_processId_fkey"
- columns: ["processId"]
- isOneToOne: false
- referencedRelation: "process"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_processId_fkey"
- columns: ["processId"]
- isOneToOne: false
- referencedRelation: "processes"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_reworkId_fkey"
- columns: ["reworkId"]
- isOneToOne: false
- referencedRelation: "rework"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
+ foreignKeyName: "jobOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
+ referencedRelation: "assemblyInstruction"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "jobOperation_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "riskRegisters"
- referencedColumns: ["workCenterId"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenter"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCenters"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "jobOperation_workCenterId_fkey"
- columns: ["workCenterId"]
- isOneToOne: false
- referencedRelation: "workCentersWithBlockingStatus"
- referencedColumns: ["id"]
- },
- ]
- }
- jobOperationsWithMakeMethods: {
- Row: {
- assignee: string | null
- companyId: string | null
- conflictReason: string | null
- createdAt: string | null
- createdBy: string | null
- customFields: Json | null
- description: string | null
- dueDate: string | null
- hasConflict: boolean | null
- id: string | null
- jobId: string | null
- jobMakeMethodId: string | null
- laborRate: number | null
- laborTime: number | null
- laborUnit: Database["public"]["Enums"]["factor"] | null
- machineRate: number | null
- machineTime: number | null
- machineUnit: Database["public"]["Enums"]["factor"] | null
- makeMethodId: string | null
- manuallyScheduled: boolean | null
- operationLeadTime: number | null
- operationMinimumCost: number | null
- operationOrder:
- | Database["public"]["Enums"]["methodOperationOrder"]
- | null
- operationQuantity: number | null
- operationSupplierProcessId: string | null
- operationType: Database["public"]["Enums"]["operationType"] | null
- operationUnitCost: number | null
- order: number | null
- overheadRate: number | null
- priority: number | null
- procedureId: string | null
- processId: string | null
- quantityComplete: number | null
- quantityReworked: number | null
- quantityScrapped: number | null
- reworkId: string | null
- setupTime: number | null
- setupUnit: Database["public"]["Enums"]["factor"] | null
- startDate: string | null
- status: Database["public"]["Enums"]["jobOperationStatus"] | null
- tags: string[] | null
- targetQuantity: number | null
- updatedAt: string | null
- updatedBy: string | null
- workCenterId: string | null
- workInstruction: Json | null
- }
- Relationships: [
{
foreignKeyName: "jobOperation_assignee_fkey"
columns: ["assignee"]
@@ -69557,6 +71150,15 @@ export type Database = {
| "Investments"
approvalDocumentType: "purchaseOrder" | "qualityDocument" | "supplier"
approvalStatus: "Pending" | "Approved" | "Rejected" | "Cancelled"
+ assemblyInstructionStatus: "Draft" | "Published" | "Archived"
+ assemblyNoteSeverity: "Info" | "Caution" | "Warning"
+ assemblyRequirementType:
+ | "Tool"
+ | "Fixture"
+ | "Consumable"
+ | "Note"
+ | "Media"
+ assemblyStepStatus: "Todo" | "Review" | "Done"
configurationParameterDataType:
| "text"
| "numeric"
@@ -69877,6 +71479,12 @@ export type Database = {
memoStatus: "Draft" | "Posted" | "Voided"
methodOperationOrder: "After Previous" | "With Previous"
methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order"
+ modelProcessingStatus:
+ | "Idle"
+ | "Queued"
+ | "Processing"
+ | "Success"
+ | "Failed"
module:
| "Accounting"
| "Documents"
@@ -70871,6 +72479,16 @@ export const Constants = {
],
approvalDocumentType: ["purchaseOrder", "qualityDocument", "supplier"],
approvalStatus: ["Pending", "Approved", "Rejected", "Cancelled"],
+ assemblyInstructionStatus: ["Draft", "Published", "Archived"],
+ assemblyNoteSeverity: ["Info", "Caution", "Warning"],
+ assemblyRequirementType: [
+ "Tool",
+ "Fixture",
+ "Consumable",
+ "Note",
+ "Media",
+ ],
+ assemblyStepStatus: ["Todo", "Review", "Done"],
configurationParameterDataType: [
"text",
"numeric",
@@ -71222,6 +72840,13 @@ export const Constants = {
memoStatus: ["Draft", "Posted", "Voided"],
methodOperationOrder: ["After Previous", "With Previous"],
methodType: ["Purchase to Order", "Pull from Inventory", "Make to Order"],
+ modelProcessingStatus: [
+ "Idle",
+ "Queued",
+ "Processing",
+ "Success",
+ "Failed",
+ ],
module: [
"Accounting",
"Documents",
diff --git a/packages/database/supabase/migrations/20260610143217_assembly-foundations.sql b/packages/database/supabase/migrations/20260610143217_assembly-foundations.sql
new file mode 100644
index 0000000000..a9f8307302
--- /dev/null
+++ b/packages/database/supabase/migrations/20260610143217_assembly-foundations.sql
@@ -0,0 +1,73 @@
+-- Assembly instructions (production module): automated/animated 3D work
+-- instructions from CAD models. Foundations: model processing columns and
+-- the plan job table. Access is governed by the existing production_*
+-- permissions.
+
+-- 1. Server-side model processing state on modelUpload
+CREATE TYPE "modelProcessingStatus" AS ENUM (
+ 'Idle',
+ 'Queued',
+ 'Processing',
+ 'Success',
+ 'Failed'
+);
+
+ALTER TABLE "modelUpload" ADD COLUMN "processingStatus" "modelProcessingStatus" NOT NULL DEFAULT 'Idle';
+ALTER TABLE "modelUpload" ADD COLUMN "processingError" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN "glbPath" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN "graphPath" TEXT;
+ALTER TABLE "modelUpload" ADD COLUMN "componentCount" INTEGER;
+ALTER TABLE "modelUpload" ADD COLUMN "processedAt" TIMESTAMP WITH TIME ZONE;
+
+-- 2. Geometry pipeline runs (conversion now, sequence planning later)
+CREATE TABLE "assemblyPlanJob" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "modelUploadId" TEXT NOT NULL,
+ "kind" TEXT NOT NULL CHECK ("kind" IN ('convert', 'plan')),
+ "status" "modelProcessingStatus" NOT NULL DEFAULT 'Queued',
+ "planPath" TEXT,
+ "stats" JSONB,
+ "error" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyPlanJob_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyPlanJob_modelUploadId_fkey" FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyPlanJob_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyPlanJob_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyPlanJob_modelUploadId_idx" ON "assemblyPlanJob"("modelUploadId");
+CREATE INDEX "assemblyPlanJob_companyId_idx" ON "assemblyPlanJob"("companyId");
+
+ALTER TABLE "assemblyPlanJob" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyPlanJob"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyPlanJob"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyPlanJob"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyPlanJob"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
diff --git a/packages/database/supabase/migrations/20260610151942_assembly-instructions.sql b/packages/database/supabase/migrations/20260610151942_assembly-instructions.sql
new file mode 100644
index 0000000000..2861eaf345
--- /dev/null
+++ b/packages/database/supabase/migrations/20260610151942_assembly-instructions.sql
@@ -0,0 +1,183 @@
+-- Assembly instructions: editable, versioned, animated 3D work instructions
+-- authored against a processed model upload.
+
+CREATE TYPE "assemblyInstructionStatus" AS ENUM (
+ 'Draft',
+ 'Published',
+ 'Archived'
+);
+
+CREATE TABLE "assemblyInstruction" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "modelUploadId" TEXT NOT NULL,
+ "itemId" TEXT,
+ "assemblyPlanJobId" TEXT,
+ "status" "assemblyInstructionStatus" NOT NULL DEFAULT 'Draft',
+ "version" INTEGER NOT NULL DEFAULT 1,
+ "publishedAt" TIMESTAMP WITH TIME ZONE,
+ "settings" JSONB,
+ "companyId" TEXT NOT NULL,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstruction_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstruction_modelUploadId_fkey" FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstruction_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE SET NULL,
+ CONSTRAINT "assemblyInstruction_assemblyPlanJobId_fkey" FOREIGN KEY ("assemblyPlanJobId") REFERENCES "assemblyPlanJob"("id") ON DELETE SET NULL,
+ CONSTRAINT "assemblyInstruction_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstruction_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstruction_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyInstruction_companyId_idx" ON "assemblyInstruction"("companyId");
+CREATE INDEX "assemblyInstruction_modelUploadId_idx" ON "assemblyInstruction"("modelUploadId");
+CREATE INDEX "assemblyInstruction_itemId_idx" ON "assemblyInstruction"("itemId");
+
+CREATE TABLE "assemblyInstructionStep" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "assemblyInstructionId" TEXT NOT NULL,
+ "parentStepId" TEXT,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "title" TEXT,
+ -- Typed-step shape mirrors "jobOperationStep" so steps can eventually be
+ -- copied into job operations. "instructionText" is a derived plain-text
+ -- snapshot of "description" (tiptap JSON) consumed by the 3D viewer overlay.
+ "type" "procedureStepType" NOT NULL DEFAULT 'Task',
+ "description" JSON DEFAULT '{}',
+ "instructionText" TEXT,
+ "required" BOOLEAN DEFAULT FALSE,
+ "unitOfMeasureCode" TEXT,
+ "minValue" NUMERIC,
+ "maxValue" NUMERIC,
+ "listValues" TEXT[],
+ "fileTypes" TEXT[],
+ "notes" JSON,
+ "componentNodeIds" TEXT[] NOT NULL DEFAULT '{}',
+ "motion" JSONB NOT NULL DEFAULT '{"type": "none"}',
+ "camera" JSONB,
+ "explode" JSONB,
+ "fastener" JSONB,
+ "warnings" JSONB,
+ "planConfidence" TEXT NOT NULL DEFAULT 'manual' CHECK ("planConfidence" IN ('high', 'low', 'manual')),
+ "durationSeconds" NUMERIC,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstructionStep_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstructionStep_assemblyInstructionId_fkey" FOREIGN KEY ("assemblyInstructionId") REFERENCES "assemblyInstruction"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStep_parentStepId_fkey" FOREIGN KEY ("parentStepId") REFERENCES "assemblyInstructionStep"("id") ON DELETE SET NULL,
+ CONSTRAINT "assemblyInstructionStep_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure"("code", "companyId") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStep_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStep_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStep_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyInstructionStep_assemblyInstructionId_idx" ON "assemblyInstructionStep"("assemblyInstructionId");
+CREATE INDEX "assemblyInstructionStep_assemblyInstructionId_sortOrder_idx" ON "assemblyInstructionStep"("assemblyInstructionId", "sortOrder");
+CREATE INDEX "assemblyInstructionStep_companyId_idx" ON "assemblyInstructionStep"("companyId");
+
+ALTER TABLE "assemblyInstruction" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "assemblyInstructionStep" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyInstruction"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyInstruction"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyInstruction"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyInstruction"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
+
+CREATE POLICY "SELECT" ON "assemblyInstructionStep"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyInstructionStep"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyInstructionStep"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyInstructionStep"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
+
+-- Opt-in linkage for MES playback and method authoring
+DROP VIEW IF EXISTS "jobOperationsWithDependencies";
+DROP VIEW IF EXISTS "jobOperationsWithMakeMethods";
+
+ALTER TABLE "jobOperation" ADD COLUMN "assemblyInstructionId" TEXT;
+ALTER TABLE "jobOperation" ADD CONSTRAINT "jobOperation_assemblyInstructionId_fkey"
+ FOREIGN KEY ("assemblyInstructionId") REFERENCES "assemblyInstruction"("id") ON DELETE SET NULL;
+CREATE INDEX "jobOperation_assemblyInstructionId_idx" ON "jobOperation"("assemblyInstructionId");
+
+ALTER TABLE "methodOperation" ADD COLUMN "assemblyInstructionId" TEXT;
+ALTER TABLE "methodOperation" ADD CONSTRAINT "methodOperation_assemblyInstructionId_fkey"
+ FOREIGN KEY ("assemblyInstructionId") REFERENCES "assemblyInstruction"("id") ON DELETE SET NULL;
+CREATE INDEX "methodOperation_assemblyInstructionId_idx" ON "methodOperation"("assemblyInstructionId");
+
+CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ jo.*
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm
+ ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "makeMethod" mm
+ ON jmm."itemId" = mm."itemId" AND jmm."version" = mm."version";
+
+CREATE VIEW "jobOperationsWithDependencies"
+WITH (security_invoker = true)
+AS
+SELECT
+ jo.*,
+ COALESCE(
+ (
+ SELECT array_agg(jod."dependsOnId")
+ FROM "jobOperationDependency" jod
+ WHERE jod."operationId" = jo.id
+ ),
+ '{}'::text[]
+ ) AS "dependencies"
+FROM "jobOperation" jo;
diff --git a/packages/database/supabase/migrations/20260610183947_assembly-step-status.sql b/packages/database/supabase/migrations/20260610183947_assembly-step-status.sql
new file mode 100644
index 0000000000..d48cacad79
--- /dev/null
+++ b/packages/database/supabase/migrations/20260610183947_assembly-step-status.sql
@@ -0,0 +1,13 @@
+-- Author review status for assembly instruction steps:
+-- Todo = newly added manual step, no content yet
+-- Review = planner-generated, not yet validated by an author
+-- Done = author-validated
+CREATE TYPE "assemblyStepStatus" AS ENUM ('Todo', 'Review', 'Done');
+
+ALTER TABLE "assemblyInstructionStep"
+ ADD COLUMN "status" "assemblyStepStatus" NOT NULL DEFAULT 'Todo';
+
+-- Existing planner-generated steps start in Review; manual steps stay Todo
+UPDATE "assemblyInstructionStep"
+ SET "status" = 'Review'
+ WHERE "planConfidence" IN ('high', 'low');
diff --git a/packages/database/supabase/migrations/20260610191824_assembly-step-requirements.sql b/packages/database/supabase/migrations/20260610191824_assembly-step-requirements.sql
new file mode 100644
index 0000000000..98483ac84c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260610191824_assembly-step-requirements.sql
@@ -0,0 +1,219 @@
+-- Per-step process data for assembly instructions: tools, fixtures,
+-- consumables, notes, and media attachments. Tools/fixtures/consumables can
+-- link to the item catalog (same FK target as jobOperationTool.toolId) or be
+-- free text; "name" is always snapshotted so display never needs a join and
+-- survives catalog item deletion.
+
+CREATE TYPE "assemblyRequirementType" AS ENUM (
+ 'Tool',
+ 'Fixture',
+ 'Consumable',
+ 'Note',
+ 'Media'
+);
+
+CREATE TYPE "assemblyNoteSeverity" AS ENUM ('Info', 'Caution', 'Warning');
+
+CREATE TABLE "assemblyInstructionStepRequirement" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "stepId" TEXT NOT NULL,
+ "type" "assemblyRequirementType" NOT NULL,
+ -- Catalog link for Tool/Fixture/Consumable rows
+ "itemId" TEXT,
+ -- Display name: snapshot of the catalog item name, free text, or media filename
+ "name" TEXT,
+ -- Note body, or an optional caption for other types
+ "text" TEXT,
+ -- Note classification (null for non-notes)
+ "severity" "assemblyNoteSeverity",
+ -- Private-bucket storage path for Media rows
+ "filePath" TEXT,
+ "quantity" INTEGER NOT NULL DEFAULT 1,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstructionStepRequirement_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstructionStepRequirement_stepId_fkey"
+ FOREIGN KEY ("stepId") REFERENCES "assemblyInstructionStep"("id") ON DELETE CASCADE,
+ -- SET NULL (not CASCADE): a deleted catalog item degrades to the snapshotted
+ -- name instead of silently vanishing from authored instructions
+ CONSTRAINT "assemblyInstructionStepRequirement_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE SET NULL,
+ CONSTRAINT "assemblyInstructionStepRequirement_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepRequirement_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepRequirement_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyInstructionStepRequirement_stepId_idx"
+ ON "assemblyInstructionStepRequirement" ("stepId");
+CREATE INDEX "assemblyInstructionStepRequirement_stepId_sortOrder_idx"
+ ON "assemblyInstructionStepRequirement" ("stepId", "sortOrder");
+CREATE INDEX "assemblyInstructionStepRequirement_companyId_idx"
+ ON "assemblyInstructionStepRequirement" ("companyId");
+CREATE INDEX "assemblyInstructionStepRequirement_itemId_idx"
+ ON "assemblyInstructionStepRequirement" ("itemId");
+
+-- Company-level reusable note templates. Inserting one into a step copies its
+-- content into a Note requirement (no FK), so editing a template never
+-- changes already-authored instructions.
+CREATE TABLE "assemblyStandardNote" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "content" TEXT NOT NULL,
+ "severity" "assemblyNoteSeverity" NOT NULL DEFAULT 'Info',
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyStandardNote_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyStandardNote_name_companyId_key" UNIQUE ("name", "companyId"),
+ CONSTRAINT "assemblyStandardNote_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyStandardNote_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyStandardNote_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyStandardNote_companyId_idx"
+ ON "assemblyStandardNote" ("companyId");
+
+ALTER TABLE "assemblyInstructionStepRequirement" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "assemblyStandardNote" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyInstructionStepRequirement"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyInstructionStepRequirement"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyInstructionStepRequirement"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyInstructionStepRequirement"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
+
+CREATE POLICY "SELECT" ON "assemblyStandardNote"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyStandardNote"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyStandardNote"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyStandardNote"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
+
+-- Bill-of-material parts consumed at a step. Stores itemId (not a
+-- methodMaterial FK) so associations survive make-method re-versioning; the
+-- UI picker is limited to items on the instruction item's make-method BOM.
+-- Unlike requirements, these rows are meaningless without the item, so the
+-- FK cascades instead of degrading to a snapshot.
+CREATE TABLE "assemblyInstructionStepMaterial" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "stepId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ -- Quantity consumed at this step; null = "as needed"
+ "quantity" NUMERIC,
+ "sortOrder" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyInstructionStepMaterial_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyInstructionStepMaterial_stepId_fkey"
+ FOREIGN KEY ("stepId") REFERENCES "assemblyInstructionStep"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepMaterial_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyInstructionStepMaterial_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepMaterial_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepMaterial_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyInstructionStepMaterial_stepId_itemId_key"
+ UNIQUE ("stepId", "itemId")
+);
+
+CREATE INDEX "assemblyInstructionStepMaterial_stepId_idx"
+ ON "assemblyInstructionStepMaterial" ("stepId");
+CREATE INDEX "assemblyInstructionStepMaterial_stepId_sortOrder_idx"
+ ON "assemblyInstructionStepMaterial" ("stepId", "sortOrder");
+CREATE INDEX "assemblyInstructionStepMaterial_companyId_idx"
+ ON "assemblyInstructionStepMaterial" ("companyId");
+CREATE INDEX "assemblyInstructionStepMaterial_itemId_idx"
+ ON "assemblyInstructionStepMaterial" ("itemId");
+
+ALTER TABLE "assemblyInstructionStepMaterial" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyInstructionStepMaterial"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyInstructionStepMaterial"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyInstructionStepMaterial"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyInstructionStepMaterial"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
diff --git a/packages/database/supabase/migrations/20260611134652_assembly-editor-parity.sql b/packages/database/supabase/migrations/20260611134652_assembly-editor-parity.sql
new file mode 100644
index 0000000000..7a5814a8cf
--- /dev/null
+++ b/packages/database/supabase/migrations/20260611134652_assembly-editor-parity.sql
@@ -0,0 +1,68 @@
+-- Assembly units: sets of model leaf nodes the motion planner treats as one
+-- rigid body (e.g. a purchased PCB whose CAD model shows every component). A
+-- user override on top of the automatic BOM-driven unit derivation. Scoped to
+-- the model upload (like assemblyComponentMapping) so it survives instruction
+-- delete/recreate; instructions attach to items, so a subassembly with its own
+-- build steps is simply the child item's own instruction — no child link here.
+
+CREATE TABLE "assemblyUnit" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "modelUploadId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "componentNodeIds" TEXT[] NOT NULL DEFAULT '{}',
+ "itemId" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyUnit_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyUnit_modelUploadId_fkey"
+ FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyUnit_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE SET NULL,
+ CONSTRAINT "assemblyUnit_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyUnit_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyUnit_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyUnit_modelUploadId_idx"
+ ON "assemblyUnit" ("modelUploadId");
+CREATE INDEX "assemblyUnit_itemId_idx"
+ ON "assemblyUnit" ("itemId");
+CREATE INDEX "assemblyUnit_companyId_idx"
+ ON "assemblyUnit" ("companyId");
+
+ALTER TABLE "assemblyUnit" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyUnit"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyUnit"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyUnit"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyUnit"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
diff --git a/packages/database/supabase/migrations/20260611194237_assembly-component-mappings.sql b/packages/database/supabase/migrations/20260611194237_assembly-component-mappings.sql
new file mode 100644
index 0000000000..ad8b20c859
--- /dev/null
+++ b/packages/database/supabase/migrations/20260611194237_assembly-component-mappings.sql
@@ -0,0 +1,70 @@
+-- Maps distinct model components (graph.json geometry hashes) to items from the
+-- engineering bill of materials (methodMaterial). Keyed by modelUpload so a
+-- mapping is authored once per model and shared by every instruction using
+-- it; geometryHash identifies a distinct component across all of its instances
+-- (with a "name:<name>" fallback key for components without a hash).
+
+CREATE TABLE "assemblyComponentMapping" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "modelUploadId" TEXT NOT NULL,
+ "geometryHash" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ -- 'high' = exact/strong name match or human-confirmed, 'low' = heuristic
+ "confidence" TEXT NOT NULL DEFAULT 'high' CHECK ("confidence" IN ('high', 'low')),
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "assemblyComponentMapping_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "assemblyComponentMapping_modelUploadId_geometryHash_key"
+ UNIQUE ("modelUploadId", "geometryHash"),
+ CONSTRAINT "assemblyComponentMapping_modelUploadId_fkey"
+ FOREIGN KEY ("modelUploadId") REFERENCES "modelUpload"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyComponentMapping_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "assemblyComponentMapping_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "assemblyComponentMapping_createdBy_fkey"
+ FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "assemblyComponentMapping_updatedBy_fkey"
+ FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "assemblyComponentMapping_modelUploadId_idx"
+ ON "assemblyComponentMapping" ("modelUploadId");
+CREATE INDEX "assemblyComponentMapping_itemId_idx"
+ ON "assemblyComponentMapping" ("itemId");
+CREATE INDEX "assemblyComponentMapping_companyId_idx"
+ ON "assemblyComponentMapping" ("companyId");
+
+ALTER TABLE "assemblyComponentMapping" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "assemblyComponentMapping"
+ FOR SELECT USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_view')::text[]
+ )
+ );
+
+CREATE POLICY "INSERT" ON "assemblyComponentMapping"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_create')::text[]
+ )
+ );
+
+CREATE POLICY "UPDATE" ON "assemblyComponentMapping"
+ FOR UPDATE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_update')::text[]
+ )
+ );
+
+CREATE POLICY "DELETE" ON "assemblyComponentMapping"
+ FOR DELETE USING (
+ "companyId" = ANY (
+ get_companies_with_employee_permission('production_delete')::text[]
+ )
+ );
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 577729fd26..f1d8ad9ad4 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -11,6 +11,7 @@ import {
installDeps,
installSkills,
spawnApps,
+ spawnGeometry,
spawnStripeListener,
syncEnvSymlinks
} from "../services/apps.js";
@@ -194,7 +195,9 @@ export async function up(opts: UpOpts = {}) {
await waitForServices(ctx);
}
await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });
- await seedSmokeTestUser(ctx);
+ // Skip when migrations are skipped: the `user` table may not exist yet, and
+ // seeding would fail with `relation "user" does not exist`.
+ if (shouldMigrate) await seedSmokeTestUser(ctx);
if (portless) {
await setupPortless(ctx, selectedApps);
await ensureHostsFile();
@@ -205,6 +208,10 @@ export async function up(opts: UpOpts = {}) {
log.info("stripe listener spawned (CARBON_EDITION=cloud)");
}
+ if (selectedApps.includes("geometry")) {
+ spawnGeometry({ root, ports: ctx.ports });
+ }
+
box(
summaryLines(
ctx.ports,
@@ -588,7 +595,8 @@ async function runAppsThenTeardown(
portless: boolean,
stripeChild?: ExecaChildProcess
) {
- await spawnApps({ root, apps: selectedApps, ports, portless });
+ const reactRouterApps = selectedApps.filter((id) => id !== "geometry");
+ await spawnApps({ root, apps: reactRouterApps, ports, portless });
// Apps exit on Ctrl+C; auto-`down` so compose stack isn't orphaned.
// Swallow further signals so a second Ctrl+C during teardown doesn't
diff --git a/packages/dev/src/constants.ts b/packages/dev/src/constants.ts
index 61e5efd9ba..3e3b4d2042 100644
--- a/packages/dev/src/constants.ts
+++ b/packages/dev/src/constants.ts
@@ -11,7 +11,8 @@ export const COMPOSE_DEV_FILE_LEGACY = "docker-compose.dev.yml";
/** Apps the CLI knows how to spawn through portless. */
export const APP_CHOICES = [
{ value: "erp", label: "ERP", hint: "main app" },
- { value: "mes", label: "MES", hint: "shop floor" }
+ { value: "mes", label: "MES", hint: "shop floor" },
+ { value: "geometry", label: "Geometry", hint: "3D engine" }
] as const;
export type AppId = (typeof APP_CHOICES)[number]["value"];
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
index 34983f4d2c..7eceef36ac 100644
--- a/packages/dev/src/env.test.ts
+++ b/packages/dev/src/env.test.ts
@@ -9,7 +9,8 @@ const ports: PortMap = {
PORT_INBUCKET: 54003,
PORT_INNGEST: 54004,
PORT_ERP: 54005,
- PORT_MES: 54006
+ PORT_MES: 54006,
+ PORT_GEOMETRY: 54007
};
const jwt: JwtCreds = {
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index 43ef7a50c3..69d0476caf 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -96,6 +96,12 @@ export function renderEnv(opts: {
// `erp.main.dev` host the SDK URL points at).
lines.push(`INNGEST_TLS_HOST=${portless ? host("erp") : "localhost"}`);
lines.push("");
+ lines.push("# Geometry service (assembly model conversion)");
+ lines.push(
+ `GEOMETRY_SERVICE_URL=${portless ? `https://${host("geometry")}` : local(ports.PORT_GEOMETRY)}`
+ );
+ lines.push("GEOMETRY_SERVICE_API_KEY=dev-local-key");
+ lines.push("");
lines.push("# Dev auth bypass");
lines.push("[email protected]");
lines.push("");
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index 0ef3484b09..19a7f9fcd6 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -229,6 +229,86 @@ export function spawnApps(opts: {
});
}
+export function spawnGeometry(opts: {
+ root: string;
+ ports: PortMap;
+}): ExecaChildProcess | null {
+ const { root, ports } = opts;
+ const serviceDir = join(root, "services", "geometry");
+ const venvPython = join(serviceDir, ".venv", "bin", "python");
+
+ if (!existsSync(venvPython)) {
+ const prefix = pc.yellow(pc.bold("geo | "));
+ process.stderr.write(
+ `${prefix}${pc.dim("skipped — no .venv (run: cd services/geometry && python3 -m venv .venv && .venv/bin/pip install -e .)")}\n`
+ );
+ return null;
+ }
+
+ const color = pc.yellow;
+ const port = ports.PORT_GEOMETRY;
+
+ // Trust portless's self-signed CA so the service can fetch signed URLs
+ // from the local Supabase storage (served over HTTPS via portless).
+ const caPath = join(homedir(), ".portless", "ca.pem");
+ const caEnv = existsSync(caPath)
+ ? { SSL_CERT_FILE: caPath, REQUESTS_CA_BUNDLE: caPath }
+ : {};
+
+ const child = execa(
+ venvPython,
+ [
+ "-m",
+ "uvicorn",
+ "app.main:app",
+ "--port",
+ String(port),
+ "--host",
+ "127.0.0.1",
+ "--reload"
+ ],
+ {
+ cwd: serviceDir,
+ env: {
+ ...process.env,
+ ...caEnv,
+ GEOMETRY_SERVICE_API_KEY: "dev-local-key",
+ GEOMETRY_DEV_MODE: "true"
+ },
+ reject: false,
+ stdin: "ignore",
+ detached: true
+ }
+ );
+
+ const prefix = color(pc.bold("geo | "));
+ const pipe = (
+ stream: NodeJS.ReadableStream | null,
+ sink: NodeJS.WriteStream
+ ) => {
+ if (!stream) return;
+ readLines(stream, (line) => {
+ if (isNoiseLine(line)) return;
+ sink.write(`${prefix}${line}\n`);
+ });
+ };
+ pipe(child.stdout, process.stdout);
+ pipe(child.stderr, process.stderr);
+
+ onShutdown(() => {
+ if (child.exitCode !== null || !child.pid) return;
+ try {
+ process.kill(-child.pid, "SIGTERM");
+ } catch {
+ try {
+ child.kill("SIGTERM");
+ } catch {}
+ }
+ });
+
+ return child;
+}
+
// Detached + reject:false so the caller owns the lifecycle: kill the whole
// process group on teardown (apps mode) or `unref()` it to outlive crbn
// (services-only mode). Previously fire-and-forget `.unref()`, which orphaned
diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.ts
index 1de6845911..378f520e35 100644
--- a/packages/dev/src/services/portless.ts
+++ b/packages/dev/src/services/portless.ts
@@ -420,6 +420,7 @@ function aliasMap(
{ name: withPrefix("studio", branchPrefix), port: ports.PORT_STUDIO },
{ name: withPrefix("mail", branchPrefix), port: ports.PORT_INBUCKET },
{ name: withPrefix("inngest", branchPrefix), port: ports.PORT_INNGEST },
+ { name: withPrefix("geometry", branchPrefix), port: ports.PORT_GEOMETRY },
{ name: STABLE_OAUTH_ALIAS, port: ports.PORT_API }
];
}
diff --git a/packages/dev/src/ui.ts b/packages/dev/src/ui.ts
index 2d70247c1c..6ca4aac70b 100644
--- a/packages/dev/src/ui.ts
+++ b/packages/dev/src/ui.ts
@@ -167,6 +167,16 @@ export function summaryLines(
url("inngest", ports.PORT_INNGEST),
branchPrefix ? ports.PORT_INNGEST : undefined
),
+ ...(apps.includes("geometry")
+ ? [
+ row(
+ pc.yellow,
+ "Geometry",
+ url("geometry", ports.PORT_GEOMETRY),
+ branchPrefix ? ports.PORT_GEOMETRY : undefined
+ )
+ ]
+ : []),
`${pc.gray(pc.bold("Postgres".padEnd(8)))} ${pc.gray(dbUrl)}`
);
return lines;
diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.ts
index 369808d632..cdac29514c 100644
--- a/packages/dev/src/worktree.ts
+++ b/packages/dev/src/worktree.ts
@@ -22,7 +22,8 @@ export const PORT_NAMES = [
"PORT_INBUCKET",
"PORT_INNGEST",
"PORT_ERP",
- "PORT_MES"
+ "PORT_MES",
+ "PORT_GEOMETRY"
] as const;
type PortName = (typeof PORT_NAMES)[number];
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 874689d4b8..2f1b5ad4ae 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -195,6 +195,14 @@ export const MES_URL =
getEnv("MES_URL", { isRequired: false, isSecret: false }) ??
"https://mes.carbon.ms";
+export const GEOMETRY_SERVICE_URL = getEnv("GEOMETRY_SERVICE_URL", {
+ isRequired: false
+});
+export const GEOMETRY_SERVICE_API_KEY = getEnv("GEOMETRY_SERVICE_API_KEY", {
+ isRequired: false,
+ isSecret: true
+});
+
export const GOOGLE_PLACES_API_KEY = getEnv("GOOGLE_PLACES_API_KEY", {
isRequired: false
});
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index f68bd492fa..58eb477973 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -13,6 +13,7 @@
"@carbon/printing": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
+ "@carbon/viewer": "workspace:*",
"@internationalized/date": "catalog:",
"@react-email/components": "catalog:",
"@react-pdf/renderer": "catalog:",
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
new file mode 100644
index 0000000000..598d824fdb
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts
@@ -0,0 +1,181 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Json } from "@carbon/database";
+import { GEOMETRY_SERVICE_API_KEY, GEOMETRY_SERVICE_URL } from "@carbon/env";
+import { inngest } from "../../client";
+
+const SIGNED_URL_EXPIRY = 60 * 60; // seconds
+
+/**
+ * Converts an uploaded CAD model (STEP) into web artifacts via the geometry
+ * service: a meshopt-compressed GLB and an assembly graph JSON. See
+ * docs/specs/animated-work-instructions-contracts.md for the API contract.
+ */
+export const assemblyConvertFunction = inngest.createFunction(
+ {
+ id: "assembly-convert",
+ retries: 2,
+ // The geometry service is CPU-bound and rejects work beyond its slot
+ // count with 429s; keep per-company fan-out from starving other tenants.
+ concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 2 }],
+ onFailure: async ({ event }) => {
+ const { modelUploadId } = event.data.event.data;
+ const client = getCarbonServiceRole();
+
+ await client
+ .from("modelUpload")
+ .update({
+ processingStatus: "Failed",
+ processingError: event.data.error.message
+ })
+ .eq("id", modelUploadId);
+
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Failed",
+ error: event.data.error.message,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "convert")
+ .eq("status", "Processing");
+ }
+ },
+ { event: "carbon/assembly-convert" },
+ async ({ event, step }) => {
+ const { modelUploadId, companyId, userId } = event.data;
+
+ const job = await step.run("queue", async () => {
+ const client = getCarbonServiceRole();
+
+ const modelUpload = await client
+ .from("modelUpload")
+ .select("id, modelPath, companyId")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (modelUpload.error || !modelUpload.data?.modelPath) {
+ throw new Error(
+ `Model upload ${modelUploadId} not found or has no file`
+ );
+ }
+
+ const planJob = await client
+ .from("assemblyPlanJob")
+ .insert({
+ modelUploadId,
+ kind: "convert",
+ status: "Processing",
+ companyId,
+ createdBy: userId
+ })
+ .select("id")
+ .single();
+
+ if (planJob.error) {
+ throw new Error(
+ `Failed to create assembly plan job: ${planJob.error.message}`
+ );
+ }
+
+ await client
+ .from("modelUpload")
+ .update({ processingStatus: "Processing", processingError: null })
+ .eq("id", modelUploadId);
+
+ return { id: planJob.data.id, modelPath: modelUpload.data.modelPath };
+ });
+
+ await step.run("convert", async () => {
+ const client = getCarbonServiceRole();
+
+ if (!GEOMETRY_SERVICE_URL) {
+ throw new Error("GEOMETRY_SERVICE_URL is not configured");
+ }
+
+ const glbPath = `${companyId}/models/${modelUploadId}/${job.id}/model.glb`;
+ const graphPath = `${companyId}/models/${modelUploadId}/${job.id}/graph.json`;
+
+ const source = await client.storage
+ .from("private")
+ .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`Failed to sign source URL: ${source.error.message}`);
+ }
+
+ // upsert: Inngest retries re-upload to the same paths; without it the
+ // storage API rejects the second attempt with "resource already exists"
+ const [glbUpload, graphUpload] = await Promise.all([
+ client.storage
+ .from("private")
+ .createSignedUploadUrl(glbPath, { upsert: true }),
+ client.storage
+ .from("private")
+ .createSignedUploadUrl(graphPath, { upsert: true })
+ ]);
+ if (glbUpload.error || graphUpload.error) {
+ throw new Error("Failed to sign artifact upload URLs");
+ }
+
+ const response = await fetch(`${GEOMETRY_SERVICE_URL}/convert`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(GEOMETRY_SERVICE_API_KEY
+ ? { Authorization: `Bearer ${GEOMETRY_SERVICE_API_KEY}` }
+ : {})
+ },
+ body: JSON.stringify({
+ jobId: job.id,
+ source: {
+ url: source.data.signedUrl,
+ format: "step"
+ },
+ outputs: {
+ glb: { url: glbUpload.data.signedUrl },
+ graph: { url: graphUpload.data.signedUrl }
+ }
+ })
+ });
+
+ const result = (await response.json().catch(() => null)) as {
+ ok: boolean;
+ componentCount?: number;
+ stats?: Record<string, unknown>;
+ error?: string;
+ } | null;
+
+ if (!response.ok || !result?.ok) {
+ throw new Error(
+ result?.error ?? `Geometry service returned ${response.status}`
+ );
+ }
+
+ await client
+ .from("modelUpload")
+ .update({
+ processingStatus: "Success",
+ processingError: null,
+ glbPath,
+ graphPath,
+ componentCount: result.componentCount ?? null,
+ processedAt: new Date().toISOString()
+ })
+ .eq("id", modelUploadId);
+
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Success",
+ stats: (result.stats ?? null) as Json,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", job.id);
+ });
+
+ // Planning is NOT chained here — it's expensive (minutes) and the user may
+ // author steps manually. It runs lazily on the first "Generate Steps"
+ // click (or an explicit re-plan), which then auto-creates the steps.
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
new file mode 100644
index 0000000000..09698d90f5
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts
@@ -0,0 +1,302 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Json } from "@carbon/database";
+import { GEOMETRY_SERVICE_API_KEY, GEOMETRY_SERVICE_URL } from "@carbon/env";
+import type { AssemblyPlan } from "@carbon/viewer/steps";
+import { inngest } from "../../client";
+import { loadPlanUnits } from "./plan-units";
+import { updateAssemblyStepMotionsFromPlan } from "./update-step-motions";
+
+const SIGNED_URL_EXPIRY = 60 * 60; // seconds
+// Every geometry HTTP call is now short (submit or a status poll), so a tight
+// per-request timeout is safe and catches a genuinely unreachable service.
+const REQUEST_TIMEOUT_MS = 60 * 1000;
+// Large assemblies can plan for 10+ minutes. Poll the async job on this cadence
+// up to this many times; exceeding it fails the job (→ onFailure → Failed → the
+// UI offers a retry) rather than waiting forever.
+const PLAN_POLL_INTERVAL = "15s";
+const PLAN_MAX_POLLS = 120; // 15s × 120 = 30 min budget
+// The geometry job registry is in-process; a restart drops running jobs. Re-submit
+// the plan on a lost job up to this many times before giving up.
+const PLAN_MAX_RESUBMITS = 3;
+
+const authHeaders: Record<string, string> = GEOMETRY_SERVICE_API_KEY
+ ? { Authorization: `Bearer ${GEOMETRY_SERVICE_API_KEY}` }
+ : {};
+
+/**
+ * Runs the geometry service motion planner over a converted model: computes a
+ * collision-free insertion motion per part plus an assembly sequence, stored
+ * as plan.json next to the model artifacts. See
+ * docs/specs/animated-work-instructions-contracts.md (POST /plan).
+ */
+export const assemblyPlanFunction = inngest.createFunction(
+ {
+ id: "assembly-plan",
+ retries: 2,
+ concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 1 }],
+ onFailure: async ({ event }) => {
+ const { modelUploadId } = event.data.event.data;
+ const client = getCarbonServiceRole();
+
+ // Queued included: a pre-created row (planJobId) stays Queued when the
+ // function fails before its "queue" step promotes it to Processing.
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Failed",
+ error: event.data.error.message,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("modelUploadId", modelUploadId)
+ .eq("kind", "plan")
+ .in("status", ["Queued", "Processing"]);
+ }
+ },
+ { event: "carbon/assembly-plan" },
+ async ({ event, step }) => {
+ const { modelUploadId, companyId, userId, reMotionFor, planJobId } =
+ event.data;
+
+ const job = await step.run("queue", async () => {
+ const client = getCarbonServiceRole();
+
+ const modelUpload = await client
+ .from("modelUpload")
+ .select("id, modelPath, graphPath, processingStatus")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (modelUpload.error || !modelUpload.data?.modelPath) {
+ throw new Error(
+ `Model upload ${modelUploadId} not found or has no file`
+ );
+ }
+
+ // Adopt the trigger's pre-created row when given (created Queued so the
+ // UI shows "planning" from the moment of the click); fall back to
+ // inserting a row when adoption fails.
+ if (planJobId) {
+ const adopted = await client
+ .from("assemblyPlanJob")
+ .update({ status: "Processing", updatedAt: new Date().toISOString() })
+ .eq("id", planJobId)
+ .eq("companyId", companyId)
+ .select("id")
+ .maybeSingle();
+
+ if (adopted.data?.id) {
+ return {
+ id: adopted.data.id,
+ modelPath: modelUpload.data.modelPath,
+ graphPath: modelUpload.data.graphPath
+ };
+ }
+ }
+
+ const planJob = await client
+ .from("assemblyPlanJob")
+ .insert({
+ modelUploadId,
+ kind: "plan",
+ status: "Processing",
+ companyId,
+ createdBy: userId
+ })
+ .select("id")
+ .single();
+
+ if (planJob.error) {
+ throw new Error(
+ `Failed to create assembly plan job: ${planJob.error.message}`
+ );
+ }
+
+ return {
+ id: planJob.data.id,
+ modelPath: modelUpload.data.modelPath,
+ graphPath: modelUpload.data.graphPath
+ };
+ });
+
+ if (!GEOMETRY_SERVICE_URL) {
+ throw new Error("GEOMETRY_SERVICE_URL is not configured");
+ }
+ const geometryUrl = GEOMETRY_SERVICE_URL;
+
+ // Re-motion mode (order-preserving): take the existing step order as the
+ // fixed assembly sequence and let the planner only recompute each step's
+ // motion (forward-collision against earlier steps). Otherwise plan fresh:
+ // collapse the model's leaf soup into rigid-body units so a 400-part model
+ // plans as its ~7 assembled units. Best-effort: no units → every leaf.
+ const sequence = reMotionFor
+ ? await step.run("derive-sequence", async () => {
+ const client = getCarbonServiceRole();
+ const steps = await client
+ .from("assemblyInstructionStep")
+ .select("componentNodeIds")
+ .eq("assemblyInstructionId", reMotionFor)
+ .eq("companyId", companyId)
+ .order("sortOrder", { ascending: true });
+ // Every step's parts (Done included — they're obstacles) in order.
+ return (steps.data ?? [])
+ .map((row) => row.componentNodeIds ?? [])
+ .filter((group) => group.length > 0);
+ })
+ : null;
+ const units =
+ sequence != null
+ ? []
+ : await step.run("derive-units", () =>
+ loadPlanUnits({
+ modelUploadId,
+ companyId,
+ graphPath: job.graphPath
+ })
+ );
+
+ // Kick off the planner. The service starts it in the background and returns
+ // immediately, so the request is short — no connection is held open across
+ // the multi-minute run (which no HTTP hop survives). A fresh signed source
+ // URL is minted per submit so re-submits (below) don't reuse an expired one.
+ const submitPlan = async () => {
+ const client = getCarbonServiceRole();
+
+ const source = await client.storage
+ .from("private")
+ .createSignedUrl(job.modelPath, SIGNED_URL_EXPIRY);
+ if (source.error) {
+ throw new Error(`Failed to sign source URL: ${source.error.message}`);
+ }
+
+ const response = await fetch(`${geometryUrl}/plan`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...authHeaders },
+ body: JSON.stringify({
+ jobId: job.id,
+ source: { url: source.data.signedUrl, format: "step" },
+ ...(sequence != null
+ ? { options: { sequence } }
+ : units.length > 0
+ ? { options: { units } }
+ : {})
+ }),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
+ });
+
+ const result = (await response.json().catch(() => null)) as {
+ ok?: boolean;
+ error?: string;
+ } | null;
+ if (!response.ok || !result?.ok) {
+ throw new Error(
+ result?.error ?? `Geometry service returned ${response.status}`
+ );
+ }
+ return { ok: true };
+ };
+
+ await step.run("start-plan", submitPlan);
+
+ // Poll the async job until it finishes. Each poll is its own short step, so
+ // Inngest sleeps between them rather than holding a request open. The
+ // geometry service keeps its job registry in-process, so a restart (or its
+ // dev `uvicorn --reload`) drops the running job and the poll 404s — recover
+ // by re-submitting rather than failing the whole plan.
+ let plan: Json | null = null;
+ let stats: Json = null;
+ let resubmits = 0;
+ for (let attempt = 0; attempt < PLAN_MAX_POLLS; attempt++) {
+ await step.sleep(`plan-wait-${attempt}`, PLAN_POLL_INTERVAL);
+
+ const status = await step.run(`plan-poll-${attempt}`, async () => {
+ const response = await fetch(`${geometryUrl}/plan/${job.id}`, {
+ headers: authHeaders,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
+ });
+ // 404 = the service no longer knows this job (it restarted).
+ if (response.status === 404) return { status: "missing" as const };
+ const body = (await response.json().catch(() => null)) as {
+ ok?: boolean;
+ status?: string;
+ plan?: Json;
+ stats?: Record<string, unknown>;
+ error?: string;
+ } | null;
+ if (!response.ok || !body?.ok) {
+ throw new Error(
+ body?.error ?? `Geometry status check returned ${response.status}`
+ );
+ }
+ return body;
+ });
+
+ if (status.status === "missing") {
+ if (resubmits >= PLAN_MAX_RESUBMITS) {
+ throw new Error(
+ "The geometry service repeatedly lost the plan job (restarting?)"
+ );
+ }
+ resubmits++;
+ await step.run(`plan-resubmit-${attempt}`, submitPlan);
+ continue;
+ }
+ if (status.status === "done") {
+ if (status.plan == null) {
+ throw new Error("Planner reported done but returned no plan");
+ }
+ plan = status.plan;
+ stats = (status.stats ?? null) as Json;
+ break;
+ }
+ if (status.status === "error") {
+ throw new Error(status.error ?? "Motion planning failed");
+ }
+ }
+
+ if (plan == null) {
+ throw new Error("Motion planning did not finish in time");
+ }
+ const planData = plan;
+
+ await step.run("persist-plan", async () => {
+ const client = getCarbonServiceRole();
+ const planPath = `${companyId}/models/${modelUploadId}/${job.id}/plan.json`;
+
+ const upload = await client.storage
+ .from("private")
+ .upload(planPath, JSON.stringify(planData), {
+ contentType: "application/json",
+ upsert: true
+ });
+ if (upload.error) {
+ throw new Error(`Failed to upload plan: ${upload.error.message}`);
+ }
+
+ await client
+ .from("assemblyPlanJob")
+ .update({
+ status: "Success",
+ planPath,
+ stats,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", job.id);
+ });
+
+ // Re-motion: the plan preserved the step order — update each step's motion
+ // in place (Done steps kept, order/titles/typed fields untouched).
+ if (reMotionFor) {
+ await step.run("update-step-motions", async () => {
+ const client = getCarbonServiceRole();
+ await updateAssemblyStepMotionsFromPlan(client, {
+ assemblyInstructionId: reMotionFor,
+ plan: planData as unknown as AssemblyPlan,
+ graphPath: job.graphPath,
+ companyId,
+ userId
+ });
+ });
+ }
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index 4958ed8d85..d9b4512474 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -1,3 +1,5 @@
+export { assemblyConvertFunction } from "./assembly-convert";
+export { assemblyPlanFunction } from "./assembly-plan";
export { companyExportFunction } from "./company-export";
export { companyImportFunction } from "./company-import";
export {
diff --git a/packages/jobs/src/inngest/functions/tasks/match-units.test.ts b/packages/jobs/src/inngest/functions/tasks/match-units.test.ts
new file mode 100644
index 0000000000..9645dd5964
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/match-units.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { assignComponentsToBom } from "./match-units";
+
+const components = [
+ { name: "R_0402_1005Metric_49", count: 40 },
+ { name: "minimalBCU_gen2_PCB", count: 1 }
+];
+const bom = [{ itemId: "i_pcb", name: "BCU PCB" }];
+
+describe("assignComponentsToBom guards", () => {
+ const original = process.env.OPENAI_API_KEY;
+ beforeEach(() => {
+ process.env.OPENAI_API_KEY = "test-key";
+ });
+ afterEach(() => {
+ if (original === undefined) delete process.env.OPENAI_API_KEY;
+ else process.env.OPENAI_API_KEY = original;
+ });
+
+ it("returns [] with no components", async () => {
+ expect(await assignComponentsToBom([], bom)).toEqual([]);
+ });
+
+ it("returns [] with an empty BOM", async () => {
+ expect(await assignComponentsToBom(components, [])).toEqual([]);
+ });
+
+ it("returns [] when the component set is implausibly large", async () => {
+ const many = Array.from({ length: 601 }, (_, i) => ({
+ name: `P${i}`,
+ count: 1
+ }));
+ expect(await assignComponentsToBom(many, bom)).toEqual([]);
+ });
+
+ it("returns [] (no throw) when the OpenAI key is absent", async () => {
+ delete process.env.OPENAI_API_KEY;
+ expect(await assignComponentsToBom(components, bom)).toEqual([]);
+ });
+});
diff --git a/packages/jobs/src/inngest/functions/tasks/match-units.ts b/packages/jobs/src/inngest/functions/tasks/match-units.ts
new file mode 100644
index 0000000000..e23d01486b
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/match-units.ts
@@ -0,0 +1,86 @@
+import { openai } from "@ai-sdk/openai";
+import { generateObject } from "ai";
+import { z } from "zod";
+
+/**
+ * Assigns each distinct CAD component name to the BOM line it belongs to, using an
+ * LLM's domain knowledge. CAD exports are usually flat, so this is what groups a
+ * populated PCB's hundreds of component solids (R_0402, SOT-23, SOIC, the bare
+ * board…) under the single "PCB" BOM line — a purely textual matcher can't, but
+ * a model knows a resistor footprint belongs to a circuit board.
+ *
+ * Returns name → itemId assignments for `deriveAssemblyUnits`. Degrades to `[]`
+ * (leaves stay loose) when there's nothing to match, the set is implausibly
+ * large, or the OpenAI key is absent.
+ */
+
+const MODEL = "gpt-4o-mini";
+const MIN_CONFIDENCE = 0.5;
+const MAX_COMPONENTS = 600;
+
+const assignmentSchema = z.object({
+ assignments: z.array(
+ z.object({
+ name: z.string().describe("The exact CAD component name"),
+ itemId: z
+ .string()
+ .nullable()
+ .describe(
+ "The BOM item id this component belongs to, or null if none fits"
+ ),
+ confidence: z.number().min(0).max(1)
+ })
+ )
+});
+
+type ComponentName = { name: string; count: number };
+type BomLine = { itemId: string; name: string | null };
+export type PartMatch = { name: string; itemId: string };
+
+export async function assignComponentsToBom(
+ components: ComponentName[],
+ bom: BomLine[]
+): Promise<PartMatch[]> {
+ if (components.length === 0 || bom.length === 0) return [];
+ if (components.length > MAX_COMPONENTS) return [];
+ if (!process.env.OPENAI_API_KEY) return [];
+
+ const bomText = bom
+ .map((line) => `- ${line.itemId}: ${line.name ?? "(unnamed)"}`)
+ .join("\n");
+ const componentsText = components
+ .map((component) => `- "${component.name}" (${component.count}×)`)
+ .join("\n");
+
+ try {
+ const { object } = await generateObject({
+ model: openai(MODEL),
+ schema: assignmentSchema,
+ temperature: 0,
+ prompt: `You are grouping the solids of a flat CAD assembly by the bill-of-materials (BOM) line each belongs to.
+
+Assign every CAD component name below to exactly one BOM line id, or null if none fits. Use engineering knowledge, not just text overlap: electronic component footprints (resistors like R_0402, capacitors like C_0402, ICs like SOT-23 / SOIC / TSDSO, inductors, diodes, and the bare printed circuit board itself) all belong to the assembly's circuit-board / "PCB" BOM line. Fasteners map to the matching screw/clip line; housings, seals, lids and boxes to their own lines.
+
+BOM lines (id: name):
+${bomText}
+
+CAD component names (with instance counts):
+${componentsText}
+
+Return one assignment per CAD component name. Only use BOM item ids from the list above.`
+ });
+
+ const bomIds = new Set(bom.map((line) => line.itemId));
+ return object.assignments.flatMap((a) =>
+ a.itemId && a.confidence >= MIN_CONFIDENCE && bomIds.has(a.itemId)
+ ? [{ name: a.name, itemId: a.itemId }]
+ : []
+ );
+ } catch (error) {
+ console.error(
+ "assignComponentsToBom failed; leaving components unmatched:",
+ error
+ );
+ return [];
+ }
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/plan-units.ts b/packages/jobs/src/inngest/functions/tasks/plan-units.ts
new file mode 100644
index 0000000000..399a5d334f
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/plan-units.ts
@@ -0,0 +1,222 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import {
+ deriveAssemblyUnits,
+ distinctComponentNames,
+ type UnitGraph
+} from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { assignComponentsToBom } from "./match-units";
+
+/** A pre-grouped rigid body for the geometry planner's `options.units`. */
+export type PlanUnit = { id: string; name: string | null; nodeIds: string[] };
+
+/**
+ * Derives the planned units for a model — the sets of leaf components the planner
+ * should treat as one rigid body — from its CAD graph, the item's BOM, the
+ * geometry↔BOM mappings, and an LLM matcher. Best-effort: any failure (no
+ * graph, no BOM, storage/parse error) returns `[]`, and the planner falls back
+ * to planning every leaf.
+ *
+ * Only multi-leaf units are returned; a single-leaf unit is just a normal component.
+ */
+export async function loadPlanUnits(args: {
+ modelUploadId: string;
+ companyId: string;
+ graphPath: string | null;
+}): Promise<PlanUnit[]> {
+ const { modelUploadId, companyId, graphPath } = args;
+ if (!graphPath) return [];
+
+ try {
+ const client = getCarbonServiceRole();
+
+ const graphFile = await client.storage.from("private").download(graphPath);
+ if (graphFile.error || !graphFile.data) return [];
+ const graph = JSON.parse(await graphFile.data.text()) as UnitGraph;
+ if (!graph?.root) return [];
+
+ const instruction = await client
+ .from("assemblyInstruction")
+ .select("itemId")
+ .eq("modelUploadId", modelUploadId)
+ .eq("companyId", companyId)
+ .not("itemId", "is", null)
+ .limit(1)
+ .maybeSingle();
+
+ const itemId = instruction.data?.itemId ?? null;
+ const bom = itemId ? await loadItemBom(client, itemId, companyId) : [];
+
+ const mappings = await client
+ .from("assemblyComponentMapping")
+ .select("geometryHash, itemId")
+ .eq("modelUploadId", modelUploadId);
+
+ // User "plan as one component" overrides — explicit units that always collapse.
+ const authored = await client
+ .from("assemblyUnit")
+ .select("id, name, componentNodeIds")
+ .eq("modelUploadId", modelUploadId);
+
+ const componentMatches = await assignComponentsToBom(
+ distinctComponentNames(graph),
+ bom
+ );
+
+ // Geometry↔BOM mappings can point at items NESTED inside a top-level
+ // Make line's BOM (the bare board inside the "PCB assembly" line);
+ // resolve those up to the line so the whole populated subassembly
+ // derives as ONE unit.
+ const lineByItem = await loadLineByItem(client, bom, companyId);
+
+ const units = deriveAssemblyUnits({
+ graph,
+ bomMaterials: bom,
+ componentMappings: mappings.data ?? [],
+ authoredUnits: (authored.data ?? []).map((unit) => ({
+ id: unit.id,
+ name: unit.name,
+ componentNodeIds: unit.componentNodeIds ?? []
+ })),
+ componentMatches,
+ lineByItem
+ });
+
+ return units
+ .filter((unit) => unit.nodeIds.length > 1)
+ .map((unit) => ({
+ id: unit.id,
+ name: unit.name,
+ nodeIds: unit.nodeIds
+ }));
+ } catch (error) {
+ console.error("loadPlanUnits failed; planning every leaf instead:", error);
+ return [];
+ }
+}
+
+/**
+ * Descendant BOM itemId → its top-level line's itemId, walking each direct
+ * line's Make-subassembly BOM breadth-first (bounded depth). The bare board
+ * and connector inside a "PCB assembly" line resolve to that line, so a
+ * geometry mapping that points at the nested item still lands the leaf in
+ * the line's unit. First line wins when an item appears under two lines.
+ */
+async function loadLineByItem(
+ client: SupabaseClient<Database>,
+ bomLines: { itemId: string }[],
+ companyId: string
+): Promise<Record<string, string>> {
+ const lineByItem: Record<string, string> = {};
+ const topLevel = new Set(bomLines.map((line) => line.itemId));
+ let frontier = bomLines.map((line) => ({
+ itemId: line.itemId,
+ line: line.itemId
+ }));
+
+ for (let depth = 0; depth < 5 && frontier.length > 0; depth++) {
+ const methods = await client
+ .from("makeMethod")
+ .select("id, itemId, status")
+ .in(
+ "itemId",
+ frontier.map((entry) => entry.itemId)
+ )
+ .eq("companyId", companyId);
+ if (methods.error || !methods.data?.length) break;
+
+ // Active method first, else the first one, per item
+ const methodByItem = new Map<string, string>();
+ for (const method of methods.data) {
+ if (!methodByItem.has(method.itemId) || method.status === "Active") {
+ methodByItem.set(method.itemId, method.id);
+ }
+ }
+ const lineByMethod = new Map<string, string>();
+ for (const entry of frontier) {
+ const methodId = methodByItem.get(entry.itemId);
+ if (methodId) lineByMethod.set(methodId, entry.line);
+ }
+ if (lineByMethod.size === 0) break;
+
+ const materials = await client
+ .from("methodMaterial")
+ .select("makeMethodId, itemId")
+ .in("makeMethodId", [...lineByMethod.keys()])
+ .eq("companyId", companyId);
+ if (materials.error) break;
+
+ const next: { itemId: string; line: string }[] = [];
+ for (const material of materials.data ?? []) {
+ if (!material.itemId || !material.makeMethodId) continue;
+ const line = lineByMethod.get(material.makeMethodId);
+ if (!line) continue;
+ if (topLevel.has(material.itemId) || lineByItem[material.itemId]) {
+ continue;
+ }
+ lineByItem[material.itemId] = line;
+ next.push({ itemId: material.itemId, line });
+ }
+ frontier = next;
+ }
+
+ return lineByItem;
+}
+
+/**
+ * The item's direct BOM components (single level). Top-level model
+ * subassemblies match the item's direct components, so the full flattened BOM
+ * isn't needed for unit matching.
+ */
+async function loadItemBom(
+ client: SupabaseClient<Database>,
+ itemId: string,
+ companyId: string
+): Promise<{ itemId: string; name: string | null; quantity: number }[]> {
+ const makeMethods = await client
+ .from("makeMethod")
+ .select("id, status")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId);
+ if (makeMethods.error || !makeMethods.data?.length) return [];
+
+ const active =
+ makeMethods.data.find((method) => method.status === "Active") ??
+ makeMethods.data[0];
+ if (!active) return [];
+
+ const materials = await client
+ .from("methodMaterial")
+ .select("itemId, quantity")
+ .eq("makeMethodId", active.id)
+ .eq("companyId", companyId);
+
+ // One row per BOM item; sum quantities of duplicate lines. Quantity drives
+ // the collapse rule (qty ≤ 1 with many leaves → one rigid body).
+ const quantityByItem = new Map<string, number>();
+ for (const material of materials.data ?? []) {
+ if (!material.itemId) continue;
+ quantityByItem.set(
+ material.itemId,
+ (quantityByItem.get(material.itemId) ?? 0) + (material.quantity ?? 0)
+ );
+ }
+ const componentIds = [...quantityByItem.keys()];
+ if (componentIds.length === 0) return [];
+
+ const items = await client
+ .from("item")
+ .select("id, name")
+ .in("id", componentIds)
+ .eq("companyId", companyId);
+ const nameById = new Map(
+ (items.data ?? []).map((item) => [item.id, item.name])
+ );
+
+ return componentIds.map((id) => ({
+ itemId: id,
+ name: nameById.get(id) ?? null,
+ quantity: quantityByItem.get(id) ?? 1
+ }));
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/update-step-motions.ts b/packages/jobs/src/inngest/functions/tasks/update-step-motions.ts
new file mode 100644
index 0000000000..2b0e993a32
Binary files /dev/null and b/packages/jobs/src/inngest/functions/tasks/update-step-motions.ts differ
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 61ef4e49a9..985ab5ac87 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -40,6 +40,8 @@ import {
weeklyFunction
} from "./functions/scheduled";
import {
+ assemblyConvertFunction,
+ assemblyPlanFunction,
companyExportFunction,
companyImportFunction,
companyRestoreFinalizeFunction,
@@ -71,6 +73,8 @@ export const functions = [
workflowFunction,
embeddingFunction,
// Tasks
+ assemblyConvertFunction,
+ assemblyPlanFunction,
companyExportFunction,
companyImportFunction,
companyRestoreFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 22c9a3ffba..831e166078 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -56,6 +56,36 @@ export type Events = {
};
};
+ // Assembly model conversion (CAD → GLB + assembly graph)
+ "carbon/assembly-convert": {
+ data: {
+ modelUploadId: string;
+ companyId: string;
+ userId: string;
+ };
+ };
+
+ // Assembly motion planning (collision-free removal paths + sequence)
+ "carbon/assembly-plan": {
+ data: {
+ modelUploadId: string;
+ companyId: string;
+ userId: string;
+ // When set (the user clicked "Re-run Motion Planning" on an instruction
+ // that already has steps), the planner runs in order-preserving mode: it
+ // takes the existing step order as fixed (options.sequence) and recomputes
+ // each step's motion to avoid collision with parts from earlier steps, then
+ // updates the step motions in place. Mutually exclusive with reordering.
+ reMotionFor?: string;
+ // A pre-created `assemblyPlanJob` row (status Queued) the worker should
+ // adopt instead of inserting its own. User-facing triggers create the row
+ // synchronously so the UI reflects "planning" immediately — the worker's
+ // own insert only lands after event pickup, and a page revalidation in
+ // that gap would see no running job and never start polling.
+ planJobId?: string;
+ };
+ };
+
// Model thumbnail generation
"carbon/model-thumbnail": {
data: {
diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.ts
index 6e11fe207f..d1d52cf4b9 100644
--- a/packages/lib/src/trigger.ts
+++ b/packages/lib/src/trigger.ts
@@ -8,6 +8,8 @@ import { inngest } from "./inngest/client.ts";
*/
const taskToEvent = {
"accounting-backfill": "carbon/accounting-backfill",
+ "assembly-convert": "carbon/assembly-convert",
+ "assembly-plan": "carbon/assembly-plan",
"company-export": "carbon/company-export",
"company-import": "carbon/company-import",
"company-restore": "carbon/company-restore",
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 3628c9e210..8fb453944a 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Aufsteigend"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Bitten Sie einen Admin mit {0}-Berechtigung, das erste {1} hinzuzufügen."
+msgid "Assemblies"
+msgstr "Montagen"
+
+msgid "Assembly Instructions"
+msgstr "Montageanleitungen"
+
msgid "Assembly:"
msgstr "Baugruppe:"
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 6020077af1..490ec006b7 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -764,6 +764,9 @@ msgstr "Zurück"
msgid "Preventive"
msgstr "Vorbeugend"
+msgid "Previous"
+msgstr "Zurück"
+
msgid "Print"
msgstr "Drucken"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 479b6701c5..015b76914a 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Ascending"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Ask an admin with {0} permission to add the first {1}."
+msgid "Assemblies"
+msgstr "Assemblies"
+
+msgid "Assembly Instructions"
+msgstr "Assembly Instructions"
+
msgid "Assembly:"
msgstr "Assembly:"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index ca009bb83e..52bca45845 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -764,6 +764,9 @@ msgstr "Prev"
msgid "Preventive"
msgstr "Preventive"
+msgid "Previous"
+msgstr "Previous"
+
msgid "Print"
msgstr "Print"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 792c86aa0d..e2dff7f28d 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Ascendente"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Pida a un administrador con permiso {0} que agregue el primer {1}."
+msgid "Assemblies"
+msgstr "Asambleas"
+
+msgid "Assembly Instructions"
+msgstr "Instrucciones de Montaje"
+
msgid "Assembly:"
msgstr "Ensamblaje:"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index e5b79fe94b..3fb7c56efa 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -764,6 +764,9 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventivo"
+msgid "Previous"
+msgstr "Anterior"
+
msgid "Print"
msgstr "Imprimir"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 3e2aad98e0..629ff129d3 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Croissant"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Demandez à un administrador disposant de la permission {0} d'ajouter le premier {1}."
+msgid "Assemblies"
+msgstr "Assemblages"
+
+msgid "Assembly Instructions"
+msgstr "Instructions d'assemblage"
+
msgid "Assembly:"
msgstr "Assemblage :"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 8b71536158..9be3791a8c 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -764,6 +764,9 @@ msgstr "Précédent"
msgid "Preventive"
msgstr "Préventif"
+msgid "Previous"
+msgstr "Précédent"
+
msgid "Print"
msgstr "Imprimer"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 92f305c537..c042efad51 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -1371,6 +1371,12 @@ msgstr "आरोही"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "{0} अनुमति वाले व्यवस्थापक से पहली {1} जोड़ने के लिए कहें।"
+msgid "Assemblies"
+msgstr "असेंबलीज"
+
+msgid "Assembly Instructions"
+msgstr "असेंबली निर्देश"
+
msgid "Assembly:"
msgstr "असेंबली:"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index acbbe41d32..47908caa5c 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -764,6 +764,9 @@ msgstr "पिछला"
msgid "Preventive"
msgstr "निवारक"
+msgid "Previous"
+msgstr "पिछला"
+
msgid "Print"
msgstr "प्रिंट करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index a4e1a3a772..0a8d6057f2 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Ascendente"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Chiedi a un amministratore con autorizzazione {0} di aggiungere il primo {1}."
+msgid "Assemblies"
+msgstr "Assiemi"
+
+msgid "Assembly Instructions"
+msgstr "Istruzioni di Montaggio"
+
msgid "Assembly:"
msgstr "Assieme:"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 6afcdcfd33..2233684657 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -764,6 +764,9 @@ msgstr "Precedente"
msgid "Preventive"
msgstr "Preventivo"
+msgid "Previous"
+msgstr "Precedente"
+
msgid "Print"
msgstr "Stampa"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index df0b1c2deb..c9cd46a4dc 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -1371,6 +1371,12 @@ msgstr "昇順"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "{0}権限を持つ管理者に最初の{1}を追加するよう依頼してください。"
+msgid "Assemblies"
+msgstr "アセンブリ"
+
+msgid "Assembly Instructions"
+msgstr "組立指示"
+
msgid "Assembly:"
msgstr "アセンブリ:"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 0e0b88b37d..399d8246c0 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -764,6 +764,9 @@ msgstr "前へ"
msgid "Preventive"
msgstr "予防保全"
+msgid "Previous"
+msgstr "前へ"
+
msgid "Print"
msgstr "印刷"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index fb5dae28b8..10dc2e7004 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -1371,6 +1371,12 @@ msgstr "오름차순"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "{0} 권한이 있는 관리자에게 첫 {1} 추가를 요청하세요."
+msgid "Assemblies"
+msgstr ""
+
+msgid "Assembly Instructions"
+msgstr ""
+
msgid "Assembly:"
msgstr "조립:"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index 872c719679..f1a3ad515a 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -764,6 +764,9 @@ msgstr "이전"
msgid "Preventive"
msgstr "예방"
+msgid "Previous"
+msgstr ""
+
msgid "Print"
msgstr "인쇄"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index cf56061cc5..0cd2b7035f 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Rosnąco"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Poproś administratora z uprawnieniami {0} o dodanie pierwszego {1}."
+msgid "Assemblies"
+msgstr "Zespoły"
+
+msgid "Assembly Instructions"
+msgstr "Instrukcje montażu"
+
msgid "Assembly:"
msgstr "Zespół:"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index e4c5d045f0..5d8f495cb3 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -764,6 +764,9 @@ msgstr "Poprzedni"
msgid "Preventive"
msgstr "Prewencyjne"
+msgid "Previous"
+msgstr "Poprzedni"
+
msgid "Print"
msgstr "Drukuj"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index e0f3ac0344..5f54d70e74 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Ascendente"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Peça a um administrador com permissão {0} para adicionar o primeiro {1}."
+msgid "Assemblies"
+msgstr "Montagens"
+
+msgid "Assembly Instructions"
+msgstr "Instruções de Montagem"
+
msgid "Assembly:"
msgstr "Montagem:"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index b3041dcd41..5323d56771 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -764,6 +764,9 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventiva"
+msgid "Previous"
+msgstr "Anterior"
+
msgid "Print"
msgstr "Imprimir"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index aeb64a1bcd..8aeb65aa65 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -1371,6 +1371,12 @@ msgstr "По возрастанию"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "Попросите администратора с разрешением {0} добавить первый {1}."
+msgid "Assemblies"
+msgstr "Сборки"
+
+msgid "Assembly Instructions"
+msgstr "Инструкции по сборке"
+
msgid "Assembly:"
msgstr "Сборка:"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index db0d915c05..f7b4304871 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -764,6 +764,9 @@ msgstr "Назад"
msgid "Preventive"
msgstr "Профилактическое"
+msgid "Previous"
+msgstr "Предыдущий"
+
msgid "Print"
msgstr "Печать"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 82b93df756..9d053900a2 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -1371,6 +1371,12 @@ msgstr "Artan"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "{0} izni olan bir yöneticiye ilk {1}i eklemesini isteyin."
+msgid "Assemblies"
+msgstr "Montajlar"
+
+msgid "Assembly Instructions"
+msgstr "Montaj Talimatları"
+
msgid "Assembly:"
msgstr "Montaj:"
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 5c0dbbd608..5bad764180 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -764,6 +764,9 @@ msgstr "Önceki"
msgid "Preventive"
msgstr "Önleyici"
+msgid "Previous"
+msgstr "Önceki"
+
msgid "Print"
msgstr "Yazdır"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 449a26e6a9..28da180251 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -1371,6 +1371,12 @@ msgstr "升序"
msgid "Ask an admin with {0} permission to add the first {1}."
msgstr "请求具有{0}权限的管理员添加第一个{1}。"
+msgid "Assemblies"
+msgstr "装配件"
+
+msgid "Assembly Instructions"
+msgstr "装配说明"
+
msgid "Assembly:"
msgstr "装配体:"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index cedc556b37..c1f9922d92 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -764,6 +764,9 @@ msgstr "上一个"
msgid "Preventive"
msgstr "预防性"
+msgid "Previous"
+msgstr "上一步"
+
msgid "Print"
msgstr "打印"
diff --git a/packages/react/src/ModelViewer.tsx b/packages/react/src/ModelViewer.tsx
index 16b78b47f7..dc8c217c64 100644
--- a/packages/react/src/ModelViewer.tsx
+++ b/packages/react/src/ModelViewer.tsx
@@ -11,14 +11,10 @@ import { cn } from "./utils/cn";
type UnitSystem = "metric" | "imperial";
-const darkColor = "#9797a5";
-const lightColor = "#8c8a8a";
-
export function ModelViewer({
file,
url,
mode = "dark",
- color,
className,
withProperties = true,
onDataUrl,
@@ -28,7 +24,6 @@ export function ModelViewer({
file: File | null;
url: string | null;
mode?: "dark" | "light";
- color?: `#${string}`;
withProperties?: boolean;
onDataUrl?: (dataUrl: string) => void;
onDelete?: () => void;
@@ -71,7 +66,6 @@ export function ModelViewer({
onModelLoaded: () => {
if (viewerRef.current) {
const viewer3D = viewerRef.current.GetViewer();
- updateColor(color ?? (isDarkMode ? darkColor : lightColor));
viewer3D.Resize(
parentDiv.current?.clientWidth,
@@ -264,28 +258,6 @@ export function ModelViewer({
viewer.LoadModelFromUrlList([url]);
}
- function updateColor(color: string) {
- if (!viewerRef.current) return;
-
- const viewer3D = viewerRef.current.GetViewer();
- viewer3D.mainModel.EnumerateMeshes((mesh: any) => {
- if (Array.isArray(mesh.material)) {
- mesh.material.forEach((material: any) => {
- if (material) {
- (material as THREE.MeshStandardMaterial).color.set(color);
- }
- });
- }
- });
- }
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
- useEffect(() => {
- if (color) {
- updateColor(color);
- }
- }, [color]);
-
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
if (!file || !viewerRef.current) return;
@@ -310,12 +282,8 @@ export function ModelViewer({
? new OV.RGBAColor(21, 22, 25, 255)
: new OV.RGBAColor(255, 255, 255, 255)
);
-
- if (!color) {
- updateColor(isDarkMode ? darkColor : lightColor);
- }
}
- }, [isDarkMode, color]);
+ }, [isDarkMode]);
const { locale } = useLocale();
diff --git a/packages/react/src/Tabs.tsx b/packages/react/src/Tabs.tsx
index df51d23201..f45dcccce3 100644
--- a/packages/react/src/Tabs.tsx
+++ b/packages/react/src/Tabs.tsx
@@ -15,7 +15,10 @@ const TabsList = forwardRef<
<TabsPrimitive.List
ref={ref}
className={cn(
- "inline-flex h-9 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground shadow-[inset_0_1px_2px_rgba(0,0,0,0.15)] border-b border-border",
+ // No fixed height and no border — p-1 sizes the box, so the space
+ // around the triggers is uniform on every side (a fixed h-* squeezed
+ // them, and a border-b read as an extra pixel of bottom padding)
+ "inline-flex items-center justify-center rounded-md bg-muted p-1 text-muted-foreground shadow-[inset_0_1px_2px_rgba(0,0,0,0.15)]",
className
)}
{...props}
diff --git a/packages/utils/src/assembly-units.test.ts b/packages/utils/src/assembly-units.test.ts
new file mode 100644
index 0000000000..d90dda8d18
--- /dev/null
+++ b/packages/utils/src/assembly-units.test.ts
@@ -0,0 +1,209 @@
+import { describe, expect, it } from "vitest";
+import {
+ deriveAssemblyUnits,
+ distinctComponentNames,
+ type UnitGraph,
+ type UnitGraphNode
+} from "./assembly-units";
+
+function leaf(
+ nodeId: string,
+ name: string,
+ geometryHash: string
+): UnitGraphNode {
+ return { nodeId, name, isAssembly: false, geometryHash, children: [] };
+}
+
+function flat(children: UnitGraphNode[]): UnitGraph {
+ return {
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ children
+ }
+ };
+}
+
+describe("deriveAssemblyUnits", () => {
+ it("gives an unmatched flat model one loose unit per leaf", () => {
+ const graph = flat([
+ leaf("a", "Bracket", "h1"),
+ leaf("b", "Screw", "h2"),
+ leaf("c", "Cover", "h3")
+ ]);
+ const units = deriveAssemblyUnits({
+ graph,
+ bomMaterials: [],
+ componentMappings: [],
+ authoredUnits: []
+ });
+ expect(units).toHaveLength(3);
+ expect(units.every((u) => u.source === "loose")).toBe(true);
+ expect(units.map((u) => u.id).sort()).toEqual(["a", "b", "c"]);
+ });
+
+ // A flat SA-BCU-like model: a populated PCB (qty 1) shown as many component
+ // solids, plus 8 screws (qty 8) and a single seal (qty 1).
+ const bcuGraph = () =>
+ flat([
+ leaf("seal", "Seal Electronics Box", "hseal"),
+ ...Array.from({ length: 8 }, (_, i) =>
+ leaf(`screw-${i}`, "Flanged Screw", `hscrew`)
+ ),
+ ...Array.from({ length: 300 }, (_, i) =>
+ leaf(`pcb-${i}`, `R_0402_${i}`, `hr${i}`)
+ )
+ ]);
+ const bcuBom = [
+ { itemId: "i_seal", name: "Seal Electronics Box", quantity: 1 },
+ { itemId: "i_screw", name: "Flanged Screws", quantity: 8 },
+ { itemId: "i_pcb", name: "BCU PCB", quantity: 1 }
+ ];
+ // The LLM assigns each distinct component name to a BOM line.
+ const bcuMatches = [
+ { name: "Seal Electronics Box", itemId: "i_seal" },
+ { name: "Flanged Screw", itemId: "i_screw" },
+ ...Array.from({ length: 300 }, (_, i) => ({
+ name: `R_0402_${i}`,
+ itemId: "i_pcb"
+ }))
+ ];
+
+ it("collapses the qty-1 PCB into one rigid unit but keeps 8 screws separate", () => {
+ const units = deriveAssemblyUnits({
+ graph: bcuGraph(),
+ bomMaterials: bcuBom,
+ componentMappings: [],
+ authoredUnits: [],
+ componentMatches: bcuMatches
+ });
+
+ const pcb = units.find((u) => u.id === "unit:i_pcb");
+ expect(pcb?.nodeIds).toHaveLength(300);
+ expect(pcb?.name).toBe("BCU PCB");
+ expect(pcb?.source).toBe("bom");
+
+ // 8 screws stay as 8 separate components (qty 8, not merged).
+ const screws = units.filter((u) => u.itemId === "i_screw");
+ expect(screws).toHaveLength(8);
+ expect(screws.every((u) => u.nodeIds.length === 1)).toBe(true);
+
+ // Seal is a lone matched component.
+ const seal = units.find((u) => u.id === "seal");
+ expect(seal?.itemId).toBe("i_seal");
+
+ // 1 PCB unit + 8 screws + 1 seal.
+ expect(units).toHaveLength(10);
+ });
+
+ it("does not collapse a qty>1 line even with many leaves", () => {
+ const graph = flat(
+ Array.from({ length: 12 }, (_, i) => leaf(`s-${i}`, "Screw", "hs"))
+ );
+ const units = deriveAssemblyUnits({
+ graph,
+ bomMaterials: [{ itemId: "i", name: "Screw", quantity: 12 }],
+ componentMappings: [],
+ authoredUnits: [],
+ componentMatches: [{ name: "Screw", itemId: "i" }]
+ });
+ expect(units).toHaveLength(12);
+ expect(units.every((u) => u.nodeIds.length === 1)).toBe(true);
+ });
+
+ it("prefers an exact geometry↔BOM mapping over the LLM name assignment", () => {
+ const graph = flat([leaf("a", "Widget", "hA"), leaf("b", "Widget", "hB")]);
+ const units = deriveAssemblyUnits({
+ graph,
+ bomMaterials: [
+ { itemId: "i_map", name: "Mapped", quantity: 1 },
+ { itemId: "i_llm", name: "Guessed", quantity: 1 }
+ ],
+ // Exact mapping says hA → i_map; the LLM guesses the name → i_llm.
+ componentMappings: [{ geometryHash: "hA", itemId: "i_map" }],
+ authoredUnits: [],
+ componentMatches: [{ name: "Widget", itemId: "i_llm" }]
+ });
+ expect(units.find((u) => u.id === "a")?.itemId).toBe("i_map");
+ expect(units.find((u) => u.id === "b")?.itemId).toBe("i_llm");
+ });
+
+ it("honors an authored unit and removes its leaves from the automatic pass", () => {
+ const graph = flat([
+ leaf("a", "Bracket", "h1"),
+ leaf("b", "Screw", "h2"),
+ leaf("c", "Washer", "h3")
+ ]);
+ const units = deriveAssemblyUnits({
+ graph,
+ bomMaterials: [],
+ componentMappings: [],
+ authoredUnits: [
+ { id: "unit-1", name: "Fastener Kit", componentNodeIds: ["b", "c"] }
+ ]
+ });
+ const authored = units.find((u) => u.id === "unit-1");
+ expect(authored?.source).toBe("authored");
+ expect(authored?.nodeIds.sort()).toEqual(["b", "c"]);
+ expect(units.filter((u) => u.nodeIds.includes("b"))).toHaveLength(1);
+ expect(units.find((u) => u.id === "a")?.source).toBe("loose");
+ });
+
+ it("summarizes distinct component names with counts for the matcher", () => {
+ const names = distinctComponentNames(bcuGraph());
+ const byName = new Map(names.map((n) => [n.name, n.count]));
+ expect(byName.get("Flanged Screw")).toBe(8);
+ expect(byName.get("Seal Electronics Box")).toBe(1);
+ // 300 distinct R_0402_* names + screw + seal.
+ expect(names).toHaveLength(302);
+ });
+
+ it("folds leaves mapped to nested-subassembly items into the top-level line's unit", () => {
+ // The bare board and its connector are geometry-mapped to items that live
+ // INSIDE the "BCU PCB" line's Make BOM — without lineByItem they escape
+ // the populated-PCB unit and the component swarm installs with nothing
+ // to mate to.
+ const graph = flat([
+ leaf("board", "minimalBCU_gen2_PCB", "hboard"),
+ leaf("conn", "C-1-776163-1", "hconn"),
+ ...Array.from({ length: 10 }, (_, i) =>
+ leaf(`pcb-${i}`, `R_0402_${i}`, `hr${i}`)
+ )
+ ]);
+ const bom = [{ itemId: "i_pcb", name: "BCU PCB", quantity: 1 }];
+ const matches = Array.from({ length: 10 }, (_, i) => ({
+ name: `R_0402_${i}`,
+ itemId: "i_pcb"
+ }));
+ const mappings = [
+ { geometryHash: "hboard", itemId: "i_bareboard" },
+ { geometryHash: "hconn", itemId: "i_connector" }
+ ];
+
+ const without = deriveAssemblyUnits({
+ graph,
+ bomMaterials: bom,
+ componentMappings: mappings,
+ authoredUnits: [],
+ componentMatches: matches
+ });
+ expect(without.find((u) => u.id === "unit:i_pcb")?.nodeIds).toHaveLength(
+ 10
+ );
+
+ const withAliases = deriveAssemblyUnits({
+ graph,
+ bomMaterials: bom,
+ componentMappings: mappings,
+ authoredUnits: [],
+ componentMatches: matches,
+ lineByItem: { i_bareboard: "i_pcb", i_connector: "i_pcb" }
+ });
+ const unit = withAliases.find((u) => u.id === "unit:i_pcb");
+ expect(unit?.nodeIds).toHaveLength(12);
+ expect(unit?.nodeIds).toContain("board");
+ expect(unit?.nodeIds).toContain("conn");
+ });
+});
diff --git a/packages/utils/src/assembly-units.ts b/packages/utils/src/assembly-units.ts
new file mode 100644
index 0000000000..52859325ef
--- /dev/null
+++ b/packages/utils/src/assembly-units.ts
@@ -0,0 +1,274 @@
+/**
+ * Deriving the "units" a motion planner should treat as one rigid body from a
+ * CAD assembly graph, its item BOM, geometry↔BOM mappings, an LLM component→BOM
+ * assignment, and user overrides. Pure (no IO), so the planner worker, the
+ * editor UI, and tests all share one implementation.
+ *
+ * The graph shape is declared structurally (only the fields used) so this file
+ * has no dependency on the viewer/three rendering package — `@carbon/viewer`'s
+ * `AssemblyGraph` is assignable to `UnitGraph`.
+ *
+ * CAD exports are frequently FLAT — every leaf sits at the root with no
+ * subassembly nesting (a populated PCB's hundreds of R/C/IC solids are
+ * top-level siblings of the enclosure and screws). So units are grouped by
+ * which BOM line each leaf belongs to, not by tree position: the LLM assigns
+ * each distinct component name to a BOM line (electronic components → the "PCB"
+ * line), leaves group by assignment, and a line collapses into ONE rigid body
+ * only when it's a single instance shown in detail (quantity ≤ 1 with ≥ 2
+ * leaves) — the PCB, never the 8 screws.
+ *
+ * Assignments resolve to the TOP-LEVEL line: a leaf mapped (by geometry hash
+ * or name) to an item that lives INSIDE a top-level Make subassembly's BOM —
+ * the bare board and its connector inside the "PCB assembly" line — belongs
+ * to that line's unit, via `lineByItem` (descendant itemId → top-level line
+ * itemId). Without it the bare board escapes its own populated-PCB unit and
+ * the planner installs the component swarm with nothing to mate to.
+ */
+
+/** Minimal structural view of a graph.json node. */
+export type UnitGraphNode = {
+ nodeId: string;
+ name: string;
+ isAssembly: boolean;
+ geometryHash: string | null;
+ children: UnitGraphNode[];
+};
+
+export type UnitGraph = { root: UnitGraphNode };
+
+// --- Name similarity (shared with BOM auto-matching) ---------------------
+
+/** Lowercase alphanumeric+dot tokens (drops punctuation/whitespace). */
+export function tokenizeName(value: string): Set<string> {
+ return new Set(
+ value
+ .toLowerCase()
+ .split(/[^a-z0-9.]+/)
+ .filter((token) => token.length > 0)
+ );
+}
+
+/** Jaccard overlap of two names' token sets, 0..1. */
+export function nameSimilarity(a: string, b: string): number {
+ const tokensA = tokenizeName(a);
+ const tokensB = tokenizeName(b);
+ if (tokensA.size === 0 || tokensB.size === 0) return 0;
+ let shared = 0;
+ for (const token of tokensA) if (tokensB.has(token)) shared++;
+ return shared / (tokensA.size + tokensB.size - shared);
+}
+
+/** Threshold above which two names are treated as the same component. */
+export const NAME_MATCH_THRESHOLD = 0.45;
+
+// --- Leaf collection -----------------------------------------------------
+
+/** A node the graph treats as a leaf instance (see indexAssemblyGraph). */
+function isLeaf(node: UnitGraphNode): boolean {
+ return !node.isAssembly && node.children.length === 0;
+}
+
+function collectLeaves(node: UnitGraphNode, out: UnitGraphNode[]): void {
+ if (isLeaf(node)) {
+ out.push(node);
+ return;
+ }
+ for (const child of node.children) collectLeaves(child, out);
+}
+
+/** Every leaf in the graph, depth-first. */
+export function collectLeafNodes(graph: UnitGraph): UnitGraphNode[] {
+ const leaves: UnitGraphNode[] = [];
+ collectLeaves(graph.root, leaves);
+ return leaves;
+}
+
+/**
+ * Distinct leaf component names with their instance counts — the input to the
+ * LLM BOM-assignment prompt (semantic matching happens on the name).
+ */
+export function distinctComponentNames(
+ graph: UnitGraph
+): { name: string; count: number }[] {
+ const counts = new Map<string, number>();
+ for (const leaf of collectLeafNodes(graph)) {
+ counts.set(leaf.name, (counts.get(leaf.name) ?? 0) + 1);
+ }
+ return [...counts.entries()].map(([name, count]) => ({ name, count }));
+}
+
+// --- Unit derivation -----------------------------------------------------
+
+/**
+ * A planned unit: the set of leaf components the planner should treat as one rigid
+ * body (and that becomes one assembly step). A purchased PCB whose CAD model
+ * carries hundreds of tiny child solids collapses to a single unit.
+ */
+export type AssemblyUnit = {
+ /** Stable id: a collapsed unit uses `unit:<itemId>`; a lone leaf its nodeId. */
+ id: string;
+ name: string;
+ /** Member LEAF nodeIds — what the planner merges and the step installs. */
+ nodeIds: string[];
+ /** BOM item this unit maps to, when resolvable. */
+ itemId?: string;
+ source: "authored" | "bom" | "loose";
+};
+
+type BomMaterial = { itemId: string; name: string | null; quantity?: number };
+type ComponentMapping = { geometryHash: string; itemId: string };
+type AuthoredUnit = { id: string; componentNodeIds: string[]; name?: string };
+/** Component name → BOM itemId, as decided by the LLM assigner. */
+type ComponentMatch = { name: string; itemId: string };
+
+/**
+ * Derives the planned units for a model.
+ *
+ * Precedence:
+ * 1. Authored units are explicit overrides.
+ * 2. Each remaining leaf is assigned a BOM item — geometry↔BOM mapping first
+ * (exact), then the LLM component-name assignment.
+ * 3. Leaves group by assigned item. A group collapses into one rigid unit only
+ * when the BOM quantity is ≤ 1 and it has ≥ 2 leaves (a single subassembly
+ * shown in full detail — the PCB). Otherwise each leaf stays its own component
+ * (8 screws remain 8 bodies; the viewer still groups identical ones into a
+ * step). Unassigned leaves are loose units.
+ */
+export function deriveAssemblyUnits(args: {
+ graph: UnitGraph;
+ bomMaterials: BomMaterial[];
+ componentMappings: ComponentMapping[];
+ authoredUnits: AuthoredUnit[];
+ /** Component name → itemId assignments from the LLM (optional). */
+ componentMatches?: ComponentMatch[];
+ /**
+ * Descendant BOM itemId → the top-level BOM line it belongs to (items
+ * nested inside a line's Make-subassembly BOM). Lets a leaf mapped to the
+ * bare board join the populated-PCB line's unit.
+ */
+ lineByItem?: Record<string, string>;
+}): AssemblyUnit[] {
+ const {
+ graph,
+ bomMaterials,
+ componentMappings,
+ authoredUnits,
+ componentMatches = [],
+ lineByItem = {}
+ } = args;
+
+ const bomByItem = new Map(bomMaterials.map((m) => [m.itemId, m]));
+ const itemByHash = new Map(
+ componentMappings.map((m) => [m.geometryHash, m.itemId])
+ );
+ const itemByName = new Map(componentMatches.map((m) => [m.name, m.itemId]));
+
+ const units: AssemblyUnit[] = [];
+ const claimed = new Set<string>();
+
+ // 1. Authored overrides win; their leaves leave the automatic pass.
+ for (const authored of authoredUnits) {
+ const nodeIds = authored.componentNodeIds.filter((id) => !claimed.has(id));
+ if (nodeIds.length === 0) continue;
+ for (const id of nodeIds) claimed.add(id);
+ const itemId = soleItem(nodeIds, graph, itemByHash, itemByName);
+ units.push({
+ id: authored.id,
+ name: authored.name ?? bomName(itemId, bomByItem) ?? "Subassembly",
+ nodeIds,
+ itemId,
+ source: "authored"
+ });
+ }
+
+ // 2. Assign each remaining leaf a BOM item (mapping first, then LLM),
+ // then resolve nested-subassembly items up to their top-level line.
+ const byItem = new Map<string, UnitGraphNode[]>();
+ const loose: UnitGraphNode[] = [];
+ for (const leaf of collectLeafNodes(graph)) {
+ if (claimed.has(leaf.nodeId)) continue;
+ const assigned =
+ (leaf.geometryHash ? itemByHash.get(leaf.geometryHash) : undefined) ??
+ itemByName.get(leaf.name);
+ const itemId = assigned ? (lineByItem[assigned] ?? assigned) : undefined;
+ if (itemId) {
+ const group = byItem.get(itemId) ?? [];
+ group.push(leaf);
+ byItem.set(itemId, group);
+ } else {
+ loose.push(leaf);
+ }
+ }
+
+ // 3. Emit units per BOM group.
+ for (const [itemId, leaves] of byItem) {
+ const quantity = bomByItem.get(itemId)?.quantity ?? 1;
+ const name = bomName(itemId, bomByItem);
+ if (leaves.length >= 2 && quantity <= 1) {
+ // A single physical subassembly shown in full detail → one rigid body.
+ units.push({
+ id: `unit:${itemId}`,
+ name: name ?? leaves[0]!.name,
+ nodeIds: leaves.map((l) => l.nodeId),
+ itemId,
+ source: "bom"
+ });
+ } else {
+ // Multiple instances (or a lone component) → keep each leaf separate.
+ for (const leaf of leaves) {
+ units.push({
+ id: leaf.nodeId,
+ name: name ?? leaf.name,
+ nodeIds: [leaf.nodeId],
+ itemId,
+ source: "bom"
+ });
+ }
+ }
+ }
+
+ // Unassigned leaves are loose units.
+ for (const leaf of loose) {
+ units.push({
+ id: leaf.nodeId,
+ name: leaf.name,
+ nodeIds: [leaf.nodeId],
+ source: "loose"
+ });
+ }
+
+ return units;
+}
+
+/** The single BOM item a set of leaf nodeIds resolves to, if unambiguous. */
+function soleItem(
+ nodeIds: string[],
+ graph: UnitGraph,
+ itemByHash: Map<string, string>,
+ itemByName: Map<string, string>
+): string | undefined {
+ const byNode = new Map<string, UnitGraphNode>();
+ const index = (node: UnitGraphNode): void => {
+ byNode.set(node.nodeId, node);
+ for (const child of node.children) index(child);
+ };
+ index(graph.root);
+ const items = new Set<string>();
+ for (const nodeId of nodeIds) {
+ const node = byNode.get(nodeId);
+ if (!node) continue;
+ const itemId =
+ (node.geometryHash ? itemByHash.get(node.geometryHash) : undefined) ??
+ itemByName.get(node.name);
+ if (itemId) items.add(itemId);
+ }
+ return items.size === 1 ? [...items][0] : undefined;
+}
+
+function bomName(
+ itemId: string | undefined,
+ bomByItem: Map<string, BomMaterial>
+): string | undefined {
+ if (!itemId) return undefined;
+ return bomByItem.get(itemId)?.name ?? undefined;
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 79dbb96db4..32cc8f1b61 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -2,6 +2,7 @@ export * from "./accounting";
export * from "./address";
export * from "./all";
export * from "./arrays";
+export * from "./assembly-units";
export * from "./bom";
export * from "./color";
export * from "./const";
diff --git a/packages/utils/src/tiptap.ts b/packages/utils/src/tiptap.ts
index a281da6b07..b3dd8bab6a 100644
--- a/packages/utils/src/tiptap.ts
+++ b/packages/utils/src/tiptap.ts
@@ -41,6 +41,43 @@ export const textToTiptap = (text: string) => {
return { type: "doc", content };
};
+/**
+ * Convert a Tiptap JSON document to plain text (inverse of textToTiptap).
+ * Block nodes become newline-separated lines; marks and non-text inline
+ * content are dropped.
+ */
+export function tiptapToText(doc: JSONContent | null | undefined): string {
+ if (!doc || !doc.content) return "";
+
+ function inlineText(node: JSONContent): string {
+ if (node.type === "text") return node.text ?? "";
+ if (node.type === "hardBreak") return "\n";
+ if (node.content) return node.content.map(inlineText).join("");
+ return "";
+ }
+
+ function blockText(node: JSONContent): string[] {
+ switch (node.type) {
+ case "bulletList":
+ case "orderedList":
+ case "blockquote":
+ return (node.content ?? []).flatMap(blockText);
+ case "listItem":
+ return (node.content ?? []).flatMap(blockText);
+ case "horizontalRule":
+ return [];
+ default:
+ return [node.content ? node.content.map(inlineText).join("") : ""];
+ }
+ }
+
+ return doc.content
+ .flatMap(blockText)
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
/**
* Convert a Tiptap JSON document to an HTML string.
* Works server-side without DOM dependencies.
diff --git a/packages/viewer/README.md b/packages/viewer/README.md
new file mode 100644
index 0000000000..6790ce5775
--- /dev/null
+++ b/packages/viewer/README.md
@@ -0,0 +1,71 @@
+# @carbon/viewer
+
+Animated assembly work-instruction playback built on react-three-fiber.
+Implements the shared contracts in
+`docs/specs/animated-work-instructions-contracts.md` (graph.json, step motion
+JSON, `AssemblyStep`, and the step playback semantics).
+
+## Usage
+
+```tsx
+import { AssemblyPlayer, type AssemblyStep } from "@carbon/viewer";
+
+const steps: AssemblyStep[] = [
+ {
+ id: "step-1",
+ title: "Install base plate",
+ instructionText: "Lower the base plate onto the fixture.",
+ componentNodeIds: ["a1b2c3d4e5f60718"],
+ motion: { type: "linear", direction: [0, 0, -1], distance: 80 },
+ camera: null,
+ fastener: null
+ }
+];
+
+<AssemblyPlayer
+ glbUrl={signedGlbUrl} // meshopt-compressed GLB with nodeId extras
+ graphUrl={signedGraphUrl} // graph.json from the geometry service
+ steps={steps}
+ activeStepIndex={activeStepIndex}
+ onStepChange={setActiveStepIndex}
+ onSelectParts={(nodeIds) => ...} // editor: click-to-select (shift = additive)
+ readOnly // MES: disables part selection
+ mode="dark"
+ className="h-[480px]"
+/>;
+```
+
+## Step playback semantics
+
+For active step `k` (0-based):
+
+- parts of steps `< k` are shown **solid** at their final pose
+- parts of step `k` **animate** their insertion motion (looping, with a short
+ hold at the seated pose) and are highlighted
+- parts of steps `> k` are **hidden**, or **ghosted** wireframe when the
+ x-ray toggle is on
+- parts in no step (base/fixture parts) are always shown solid
+
+Motion JSON describes the **insertion** of the step's parts; the viewer
+derives the displaced start pose from it. `path` motions are absolute world
+poses (`t` normalized 0..1, strictly increasing, last keyframe must equal the
+part's final pose). `camera: null` auto-frames the active parts.
+
+## Building blocks
+
+- `useAssembly(glbUrl, graphUrl)` — loads the GLB (meshopt decoding wired)
+ and graph.json; returns `{ scene, nodesById, graph, isLoading, error }`.
+ `nodesById` maps stable nodeIds (glTF `extras.nodeId`) to `Object3D`s.
+- `motionToKeyframes(motion, basePose, opts)` / `buildStepClip(step,
+ nodesById, opts)` — pure keyframe/clip construction, unit-testable without
+ WebGL.
+- `AssemblyViewer` — bare Canvas wrapper (lights + orbit controls) for
+ custom scenes.
+
+## Integration notes
+
+- The footer controls use Carbon design-token Tailwind classes
+ (`bg-background`, `text-muted-foreground`, `accent-primary`, ...); the
+ consuming app's Tailwind build must scan `packages/viewer/src` as a source.
+- Peer deps: `react` / `react-dom` 18. Three is pinned to `0.163.0` to match
+ `@carbon/react`.
diff --git a/packages/viewer/package.json b/packages/viewer/package.json
new file mode 100644
index 0000000000..98a10a2900
--- /dev/null
+++ b/packages/viewer/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@carbon/viewer",
+ "dependencies": {
+ "@react-three/drei": "9.122.0",
+ "@react-three/fiber": "8.18.0",
+ "three": "0.163.0",
+ "three-stdlib": "2.36.1"
+ },
+ "devDependencies": {
+ "@carbon/config": "workspace:*",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@types/three": "0.163.0",
+ "react": "catalog:",
+ "react-dom": "catalog:",
+ "typescript": "catalog:",
+ "vitest": "catalog:"
+ },
+ "exports": {
+ ".": "./src/index.ts",
+ "./steps": "./src/steps.ts"
+ },
+ "peerDependencies": {
+ "react": "catalog:",
+ "react-dom": "catalog:"
+ },
+ "private": true,
+ "scripts": {
+ "clean": "rimraf .turbo node_modules",
+ "lint": "biome lint --write ",
+ "test": "vitest run",
+ "typecheck": "tsgo --noEmit"
+ },
+ "sideEffects": false,
+ "version": "0.0.0"
+}
diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsx
new file mode 100644
index 0000000000..32c82e61b1
--- /dev/null
+++ b/packages/viewer/src/AssemblyPlayer.tsx
@@ -0,0 +1,1953 @@
+import { type ThreeEvent, useFrame, useThree } from "@react-three/fiber";
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState
+} from "react";
+import {
+ AnimationMixer,
+ Box3,
+ Color,
+ LoopOnce,
+ type Material,
+ type Mesh,
+ type MeshBasicMaterial,
+ MeshStandardMaterial,
+ type Object3D,
+ PerspectiveCamera,
+ Vector3
+} from "three";
+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
+import { AssemblyViewer } from "./AssemblyViewer";
+import { describeStep, type NamedUnit } from "./describe";
+import { indexAssemblyGraph } from "./graph";
+import { MotionPathEditor } from "./MotionPathEditor";
+import {
+ buildStepClip,
+ displayMotionForStep,
+ exaggerateMotion,
+ stepTimelineSeconds
+} from "./motion";
+import type {
+ AssemblyGraph,
+ AssemblyStep,
+ CameraPose,
+ Motion,
+ Vec3
+} from "./types";
+import { useAssembly } from "./useAssembly";
+import { cn } from "./utils";
+import {
+ type ComponentVisual,
+ type FutureComponentsMode,
+ visualForComponent
+} from "./visibility";
+
+export type { FutureComponentsMode } from "./visibility";
+
+/** Marquee rectangle in canvas-local CSS pixels while box-selecting. */
+type BoxRect = { left: number; top: number; width: number; height: number };
+
+export type AssemblyPlayerProps = {
+ glbUrl: string;
+ graphUrl: string;
+ steps: AssemblyStep[];
+ activeStepIndex: number;
+ onStepChange?: (index: number) => void;
+ /** Click-to-select component nodeIds for the editor (additive with shift held) */
+ onSelectComponents?: (nodeIds: string[]) => void;
+ /** Surfaces the parsed graph.json once loaded (for BOM/title derivation) */
+ onGraphLoaded?: (graph: AssemblyGraph) => void;
+ /**
+ * External (e.g. BOM-driven) highlight. Highlighted components render with an
+ * emissive tint and stay visible even when their step would hide them.
+ * Independent of click-selection.
+ */
+ highlightedNodeIds?: string[];
+ /** Components hidden from the viewer entirely (fixtures, reference geometry) */
+ hiddenNodeIds?: string[];
+ /** Disables component selection (MES playback) */
+ readOnly?: boolean;
+ /**
+ * Puts the active step's insertion motion into the draggable red-path editor.
+ * Must reference the active step; the draft `motion` is what renders (so the
+ * route can hold it as controlled state). Playback is paused while set.
+ */
+ editMotion?: { stepId: string; motion: Motion } | null;
+ /** Drag/insert/delete of a waypoint emits the new relative motion. */
+ onMotionChange?: (stepId: string, motion: Motion) => void;
+ /** Initial render mode for future-step components */
+ defaultFutureMode?: FutureComponentsMode;
+ /**
+ * When true (default), the whole sequence auto-plays on load and runs through
+ * every step. When false, the player starts paused: selecting a step plays
+ * just that step, and it only continues through the rest once Play is pressed.
+ */
+ autoPlay?: boolean;
+ /**
+ * Named subassembly units (authored "plan as one component" groups). A step whose
+ * components are exactly one of these is titled by the unit's name rather than by
+ * listing every component inside it.
+ */
+ units?: NamedUnit[];
+ /**
+ * Skips AABB fallback synthesis for steps stored with motion "none" so they
+ * fade in at the seated pose instead. Set while motion planning is running —
+ * the fresh plan is about to replace those motions, so animating a fabricated
+ * path would be misleading.
+ */
+ suppressFallbackMotions?: boolean;
+ mode?: "dark" | "light";
+ className?: string;
+};
+
+/** Imperative handle for reading the live camera (per-step "Set view"). */
+export type AssemblyPlayerHandle = {
+ /** The current camera pose, or null before the scene is ready. */
+ captureCameraPose: () => CameraPose | null;
+};
+
+/**
+ * Animated assembly playback per the assembly contracts (section 5):
+ * - components of steps before the active step are shown solid at their final pose
+ * - components of the active step play their insertion motion once, holding the
+ * seated pose; flagged steps (no collision-free path) fade in instead
+ * - components of later steps render per the future-components mode: ghosted at low
+ * opacity in their original color (default), hidden, or solid
+ * - components no step installs are never present: they render like future-step
+ * components (hidden during playback, the future-components mode while paused)
+ *
+ * All steps form one continuous timeline: playing advances through steps
+ * automatically, the scrubber maps to global seconds (step boundaries are
+ * tick marks), and the footer shows elapsed / total time.
+ */
+export const AssemblyPlayer = forwardRef<
+ AssemblyPlayerHandle,
+ AssemblyPlayerProps
+>(function AssemblyPlayer(
+ {
+ glbUrl,
+ graphUrl,
+ steps,
+ activeStepIndex,
+ onStepChange,
+ onSelectComponents,
+ onGraphLoaded,
+ highlightedNodeIds,
+ hiddenNodeIds,
+ readOnly = false,
+ editMotion,
+ onMotionChange,
+ defaultFutureMode = "ghost",
+ autoPlay = true,
+ units,
+ suppressFallbackMotions = false,
+ mode = "dark",
+ className
+ },
+ ref
+) {
+ const { scene, nodesById, graph, isLoading, error } = useAssembly(
+ glbUrl,
+ graphUrl
+ );
+ // With autoPlay, the sequence runs through every step on load. Otherwise the
+ // player starts paused: selecting a step plays just that step, and it only
+ // continues through the rest once Play is pressed (`continuous`).
+ const [isPlaying, setIsPlaying] = useState(autoPlay);
+ const [continuous, setContinuous] = useState(autoPlay);
+ const [futureMode, setFutureMode] =
+ useState<FutureComponentsMode>(defaultFutureMode);
+ // Live marquee rectangle while box-selecting (drawn as a DOM overlay).
+ const [boxRect, setBoxRect] = useState<BoxRect | null>(null);
+
+ // The scene writes the live camera reader here; the imperative handle reads it.
+ const capturePoseRef = useRef<(() => CameraPose | null) | null>(null);
+ useImperativeHandle(
+ ref,
+ () => ({ captureCameraPose: () => capturePoseRef.current?.() ?? null }),
+ []
+ );
+
+ // Editing the motion path pauses playback so drags aren't fought by the clip.
+ const isEditingMotion = Boolean(editMotion);
+ useEffect(() => {
+ if (isEditingMotion) setIsPlaying(false);
+ }, [isEditingMotion]);
+
+ // Selecting a step plays that one step's animation (single-step). Skip the
+ // initial mount so the player is paused by default, and don't auto-play while
+ // the motion-path editor is open (components must sit seated for the drag handles).
+ const isEditingMotionRef = useRef(isEditingMotion);
+ isEditingMotionRef.current = isEditingMotion;
+ const prevStepIndexRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (graph) onGraphLoaded?.(graph);
+ }, [graph, onGraphLoaded]);
+
+ const graphIndex = useMemo(
+ () => (graph ? indexAssemblyGraph(graph) : null),
+ [graph]
+ );
+
+ const assemblyDiagonal = useMemo(() => {
+ const bbox = graphIndex?.graph.root.bbox;
+ if (!bbox) return 0;
+ return Math.hypot(
+ bbox.max[0] - bbox.min[0],
+ bbox.max[1] - bbox.min[1],
+ bbox.max[2] - bbox.min[2]
+ );
+ }, [graphIndex]);
+
+ const stepCount = steps.length;
+ const clampedIndex = Math.min(Math.max(activeStepIndex, 0), stepCount - 1);
+ const activeStep = steps[clampedIndex] ?? null;
+ const activeStepTitle = activeStep
+ ? describeStep(activeStep, graphIndex, units)
+ : null;
+
+ useEffect(() => {
+ const prev = prevStepIndexRef.current;
+ prevStepIndexRef.current = clampedIndex;
+ // Auto-playing a step on selection is the paused (editor) mode's behavior.
+ // In autoPlay mode the sequence already runs itself, so leave stepping alone.
+ if (autoPlay) return;
+ // Only on a real step change (not the initial mount), and never while the
+ // motion-path editor is open.
+ if (prev === null || prev === clampedIndex) return;
+ if (isEditingMotionRef.current) return;
+ setIsPlaying(true);
+ }, [autoPlay, clampedIndex]);
+
+ // Cmd/Ctrl+A selects every currently visible component (skipping hidden ones and,
+ // per the future-components mode, any that aren't rendered). Ignored while typing
+ // in a field and in read-only playback, so the browser's own select-all still
+ // works there.
+ useEffect(() => {
+ if (readOnly || !onSelectComponents) return;
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (
+ !(event.metaKey || event.ctrlKey) ||
+ event.key.toLowerCase() !== "a" ||
+ isEditableTarget(event.target)
+ ) {
+ return;
+ }
+ if (!graphIndex) return;
+ const visible = graphIndex.leaves
+ .map((leaf) => leaf.nodeId)
+ .filter((nodeId) => nodesById.get(nodeId)?.visible);
+ event.preventDefault();
+ onSelectComponents(visible);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [readOnly, onSelectComponents, graphIndex, nodesById]);
+
+ // Display-only motion adjustments — the stored data is untouched:
+ // 1. Non-flagged steps saved with motion "none" (legacy plans, manual
+ // steps) get an AABB-synthesized insertion so components never pop into
+ // place. Flagged steps (no collision-free path exists) keep "none" and
+ // fade in instead. The first step is the base — placed, not inserted.
+ // 2. Small components (bolts, washers) get exaggerated travel so their
+ // insertion reads clearly at assembly scale.
+ const displaySteps = useMemo(() => {
+ if (!graphIndex) return steps;
+ const root = graphIndex.graph.root.bbox;
+ const assemblyDiagonal = Math.hypot(
+ root.max[0] - root.min[0],
+ root.max[1] - root.min[1],
+ root.max[2] - root.min[2]
+ );
+ // Fallback synthesis sees only the components already installed by earlier
+ // steps — the parts actually on the canvas when this step plays
+ const present = new Set<string>();
+ return steps.map((step, index) => {
+ const baseMotion = suppressFallbackMotions
+ ? step.motion
+ : displayMotionForStep(step, index, graphIndex, present);
+ for (const nodeId of step.componentNodeIds) present.add(nodeId);
+
+ let minBox: [number, number, number] | null = null;
+ let maxBox: [number, number, number] | null = null;
+ for (const nodeId of step.componentNodeIds) {
+ const node = graphIndex.nodesById.get(nodeId);
+ if (!node) continue;
+ if (!minBox || !maxBox) {
+ minBox = [...node.bbox.min];
+ maxBox = [...node.bbox.max];
+ } else {
+ for (let axis = 0; axis < 3; axis++) {
+ minBox[axis] = Math.min(
+ minBox[axis] ?? 0,
+ node.bbox.min[axis] ?? 0
+ );
+ maxBox[axis] = Math.max(
+ maxBox[axis] ?? 0,
+ node.bbox.max[axis] ?? 0
+ );
+ }
+ }
+ }
+ if (!minBox || !maxBox) {
+ return baseMotion === step.motion
+ ? step
+ : { ...step, motion: baseMotion };
+ }
+ const componentDiagonal = Math.hypot(
+ maxBox[0] - minBox[0],
+ maxBox[1] - minBox[1],
+ maxBox[2] - minBox[2]
+ );
+ const motion = exaggerateMotion(
+ baseMotion,
+ componentDiagonal,
+ assemblyDiagonal
+ );
+ return motion === step.motion ? step : { ...step, motion };
+ });
+ }, [steps, graphIndex, suppressFallbackMotions]);
+
+ // --- Continuous timeline ---------------------------------------------
+ const segments = useMemo(
+ () => displaySteps.map(stepTimelineSeconds),
+ [displaySteps]
+ );
+ const startTimes = useMemo(() => {
+ let elapsed = 0;
+ return segments.map((segment) => {
+ const start = elapsed;
+ elapsed += segment;
+ return start;
+ });
+ }, [segments]);
+ const totalSeconds = useMemo(
+ () => segments.reduce((sum, segment) => sum + segment, 0),
+ [segments]
+ );
+
+ /** Global playhead in seconds, written by the scene each frame */
+ const playheadRef = useRef(0);
+ /** Pending seek (seconds within the active step), consumed by the scene */
+ const seekRef = useRef<number | null>(null);
+ const [seekVersion, setSeekVersion] = useState(0);
+ const [displayTime, setDisplayTime] = useState(0);
+
+ // The playhead advances inside the render loop; poll it for the footer
+ // instead of re-rendering React at frame rate.
+ useEffect(() => {
+ const id = setInterval(() => {
+ setDisplayTime((previous) => {
+ const next = playheadRef.current;
+ return Math.abs(next - previous) > 0.05 ? next : previous;
+ });
+ }, 200);
+ return () => clearInterval(id);
+ }, []);
+
+ const goToStep = useCallback(
+ (index: number) => {
+ if (index < 0 || index >= stepCount) return;
+ seekRef.current = 0;
+ playheadRef.current = startTimes[index] ?? 0;
+ setDisplayTime(startTimes[index] ?? 0);
+ if (index === activeStepIndex) {
+ setSeekVersion((version) => version + 1);
+ } else {
+ onStepChange?.(index);
+ }
+ },
+ [onStepChange, stepCount, startTimes, activeStepIndex]
+ );
+
+ const handleStepFinished = useCallback(() => {
+ // Auto-advance to the next step only during a continuous play-through. A
+ // single-step play (from selecting a step) stops here, paused at the seated
+ // pose.
+ if (continuous && clampedIndex < stepCount - 1) {
+ goToStep(clampedIndex + 1);
+ } else {
+ setIsPlaying(false);
+ setContinuous(false);
+ }
+ }, [continuous, clampedIndex, stepCount, goToStep]);
+
+ const onScrub = useCallback(
+ (seconds: number) => {
+ const clamped = Math.max(0, Math.min(seconds, totalSeconds));
+ let index = 0;
+ while (
+ index < stepCount - 1 &&
+ clamped >= (startTimes[index + 1] ?? Number.POSITIVE_INFINITY)
+ ) {
+ index++;
+ }
+ seekRef.current = clamped - (startTimes[index] ?? 0);
+ playheadRef.current = clamped;
+ setDisplayTime(clamped);
+ if (index !== clampedIndex) {
+ onStepChange?.(index);
+ } else {
+ setSeekVersion((version) => version + 1);
+ }
+ },
+ [totalSeconds, stepCount, startTimes, clampedIndex, onStepChange]
+ );
+
+ return (
+ <div className={cn("flex h-full w-full flex-col", className)}>
+ <div className="relative min-h-0 flex-1">
+ <AssemblyViewer mode={mode} className="absolute inset-0">
+ {scene && (
+ <AssemblyScene
+ key={scene.uuid}
+ scene={scene}
+ nodesById={nodesById}
+ steps={displaySteps}
+ activeStepIndex={clampedIndex}
+ isPlaying={isPlaying}
+ futureMode={futureMode}
+ highlightedNodeIds={highlightedNodeIds}
+ hiddenNodeIds={hiddenNodeIds}
+ readOnly={readOnly}
+ onSelectComponents={onSelectComponents}
+ editMotion={editMotion ?? null}
+ onMotionChange={onMotionChange}
+ assemblyDiagonal={assemblyDiagonal}
+ capturePoseRef={capturePoseRef}
+ assemblyBounds={graphIndex?.graph.root.bbox ?? null}
+ leafBounds={graphIndex?.leaves ?? null}
+ segments={segments}
+ startTimes={startTimes}
+ playheadRef={playheadRef}
+ seekRef={seekRef}
+ seekVersion={seekVersion}
+ onStepFinished={handleStepFinished}
+ onBoxRect={setBoxRect}
+ />
+ )}
+ </AssemblyViewer>
+ {boxRect && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute z-10 rounded-[2px] border border-primary bg-primary/10"
+ style={{
+ left: boxRect.left,
+ top: boxRect.top,
+ width: boxRect.width,
+ height: boxRect.height
+ }}
+ />
+ )}
+ {isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center">
+ <svg
+ className="h-6 w-6 animate-spin text-muted-foreground"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-label="Loading model"
+ >
+ <circle
+ className="opacity-25"
+ cx="12"
+ cy="12"
+ r="10"
+ stroke="currentColor"
+ strokeWidth="4"
+ />
+ <path
+ className="opacity-75"
+ fill="currentColor"
+ d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
+ />
+ </svg>
+ </div>
+ )}
+ {error && (
+ <div className="absolute inset-0 flex items-center justify-center p-4">
+ <p className="text-sm text-destructive">{error.message}</p>
+ </div>
+ )}
+ {stepCount > 1 && (
+ <>
+ <OverlayNavButton
+ side="left"
+ aria-label="Previous step"
+ disabled={clampedIndex <= 0}
+ onClick={() => goToStep(clampedIndex - 1)}
+ />
+ <OverlayNavButton
+ side="right"
+ aria-label="Next step"
+ disabled={clampedIndex >= stepCount - 1}
+ onClick={() => goToStep(clampedIndex + 1)}
+ />
+ </>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 border-t border-border bg-background px-3 py-2">
+ <ControlButton
+ aria-label="Previous step"
+ disabled={clampedIndex <= 0}
+ onClick={() => goToStep(clampedIndex - 1)}
+ >
+ <ChevronLeftIcon />
+ </ControlButton>
+ <ControlButton
+ aria-label={isPlaying ? "Pause" : "Play"}
+ disabled={isEditingMotion}
+ onClick={() => {
+ if (isPlaying) {
+ setIsPlaying(false);
+ setContinuous(false);
+ return;
+ }
+ // Play = run on through the rest of the steps.
+ const nextStart =
+ startTimes[clampedIndex + 1] ?? Number.POSITIVE_INFINITY;
+ const currentStepFinished =
+ clampedIndex < stepCount - 1 &&
+ playheadRef.current >= nextStart - 0.05;
+ if (stepCount > 0 && playheadRef.current >= totalSeconds - 0.05) {
+ // Parked at the very end → restart the whole sequence.
+ onScrub(0);
+ } else if (currentStepFinished) {
+ // Current step already finished (e.g. after a single-step play) →
+ // continue with the next one rather than replaying this one.
+ goToStep(clampedIndex + 1);
+ } else {
+ // Mid-step or a fresh step → (re)play it from the current position.
+ setSeekVersion((version) => version + 1);
+ }
+ setContinuous(true);
+ setIsPlaying(true);
+ }}
+ >
+ {isPlaying ? <PauseIcon /> : <PlayIcon />}
+ </ControlButton>
+ <ControlButton
+ aria-label="Next step"
+ disabled={clampedIndex >= stepCount - 1}
+ onClick={() => goToStep(clampedIndex + 1)}
+ >
+ <ChevronRightIcon />
+ </ControlButton>
+ <div className="relative min-w-0 flex-1">
+ <input
+ type="range"
+ aria-label="Timeline"
+ className="w-full accent-primary"
+ min={0}
+ max={Math.max(totalSeconds, 0.01)}
+ step={0.05}
+ value={Math.min(displayTime, totalSeconds)}
+ disabled={stepCount === 0}
+ onChange={(changeEvent) =>
+ onScrub(Number(changeEvent.target.value))
+ }
+ />
+ {totalSeconds > 0 &&
+ startTimes
+ .slice(1)
+ .map((startTime) => (
+ <span
+ key={startTime}
+ aria-hidden="true"
+ className="pointer-events-none absolute top-1/2 h-2 w-px -translate-y-1/2 bg-muted-foreground/40"
+ style={{ left: `${(startTime / totalSeconds) * 100}%` }}
+ />
+ ))}
+ </div>
+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">
+ {stepCount > 0
+ ? `${formatTime(Math.min(displayTime, totalSeconds))} / ${formatTime(totalSeconds)}`
+ : "–"}
+ </span>
+ <span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">
+ {stepCount > 0 ? `${clampedIndex + 1} / ${stepCount}` : ""}
+ </span>
+ <div className="flex items-center rounded-md border border-border">
+ <ControlButton
+ aria-label="Show future components ghosted"
+ aria-pressed={futureMode === "ghost"}
+ isActive={futureMode === "ghost"}
+ onClick={() => setFutureMode("ghost")}
+ >
+ <GhostIcon />
+ </ControlButton>
+ <ControlButton
+ aria-label="Hide future components"
+ aria-pressed={futureMode === "hidden"}
+ isActive={futureMode === "hidden"}
+ onClick={() => setFutureMode("hidden")}
+ >
+ <HiddenIcon />
+ </ControlButton>
+ <ControlButton
+ aria-label="Show all components solid"
+ aria-pressed={futureMode === "solid"}
+ isActive={futureMode === "solid"}
+ onClick={() => setFutureMode("solid")}
+ >
+ <SolidIcon />
+ </ControlButton>
+ </div>
+ </div>
+
+ {activeStep && (activeStepTitle || activeStep.instructionText) && (
+ <div className="border-t border-border bg-background px-3 py-2">
+ {activeStepTitle && (
+ <p className="text-sm font-medium text-foreground">
+ {activeStepTitle}
+ </p>
+ )}
+ {activeStep.instructionText && (
+ <p className="text-sm text-muted-foreground">
+ {activeStep.instructionText}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+});
+
+type OverrideKind = "ghost" | "highlight" | "selected" | "external" | "fade";
+
+type MaterialOverrides = {
+ original: Material | Material[];
+ /** Clones are created lazily on first use, not per mesh up front */
+ ghost?: Material | Material[];
+ highlight?: Material | Material[];
+ selected?: Material | Material[];
+ external?: Material | Material[];
+ fade?: Material | Material[];
+};
+
+const HIGHLIGHT_COLOR = 0x3b82f6;
+// Selection is always red — both an in-scene click selection ("selected") and a
+// components-panel selection ("external", forced visible) tint the component red so the
+// current selection reads the same everywhere, Onshape-style.
+const SELECTED_COLOR = 0xef4444;
+const EXTERNAL_COLOR = 0xef4444;
+const GHOST_OPACITY = 0.3;
+/** Seconds a flagged step's components take to fade in at the seated pose */
+const FADE_SECONDS = 1.2;
+
+function AssemblyScene({
+ scene,
+ nodesById,
+ steps,
+ activeStepIndex,
+ isPlaying,
+ futureMode,
+ highlightedNodeIds,
+ hiddenNodeIds,
+ readOnly,
+ onSelectComponents,
+ editMotion,
+ onMotionChange,
+ assemblyDiagonal,
+ capturePoseRef,
+ assemblyBounds,
+ leafBounds,
+ segments,
+ startTimes,
+ playheadRef,
+ seekRef,
+ seekVersion,
+ onStepFinished,
+ onBoxRect
+}: {
+ scene: Object3D;
+ nodesById: Map<string, Object3D>;
+ steps: AssemblyStep[];
+ activeStepIndex: number;
+ isPlaying: boolean;
+ futureMode: FutureComponentsMode;
+ highlightedNodeIds?: string[];
+ hiddenNodeIds?: string[];
+ readOnly: boolean;
+ onSelectComponents?: (nodeIds: string[]) => void;
+ /** Active-step motion draft to edit (null = play normally) */
+ editMotion: { stepId: string; motion: Motion } | null;
+ onMotionChange?: (stepId: string, motion: Motion) => void;
+ /** Assembly diagonal (world units) for sizing the waypoint handles */
+ assemblyDiagonal: number;
+ /** The scene writes the live-camera reader here for the imperative handle */
+ capturePoseRef: React.MutableRefObject<(() => CameraPose | null) | null>;
+ /** Seated world bounds from graph.json (stable under animation) */
+ assemblyBounds: { min: number[]; max: number[] } | null;
+ /** Seated per-leaf bounds for camera occlusion scoring */
+ leafBounds:
+ | { nodeId: string; bbox: { min: number[]; max: number[] } }[]
+ | null;
+ /** Timeline seconds per step */
+ segments: number[];
+ /** Timeline start (seconds) of each step */
+ startTimes: number[];
+ /** Written each frame with the global playhead (seconds) */
+ playheadRef: React.MutableRefObject<number>;
+ /** Pending seek (seconds within the active step); consumed on apply */
+ seekRef: React.MutableRefObject<number | null>;
+ /** Bumped to re-apply a seek within the same step */
+ seekVersion: number;
+ /** The active step's timeline segment has fully elapsed */
+ onStepFinished?: () => void;
+ /** Live marquee rectangle (canvas-local px) while box-selecting; null clears */
+ onBoxRect?: (rect: BoxRect | null) => void;
+}) {
+ const camera = useThree((state) => state.camera);
+ const controls = useThree(
+ (state) => state.controls
+ ) as unknown as OrbitControlsImpl | null;
+ const gl = useThree((state) => state.gl);
+
+ const activeStep = steps[activeStepIndex] ?? null;
+ const isEditingActive = Boolean(
+ editMotion && activeStep && editMotion.stepId === activeStep.id
+ );
+
+ // Anchor for the editable path: center of the step's components' seated world
+ // bounds — the visual center of the object at its final location. Node
+ // origins won't do: CAD exports often pivot far from the geometry, which
+ // would draw the locked endpoint away from the component. Components sit seated while
+ // editing (the clip is skipped below), so world space IS the final pose.
+ const seatedCentroid = useMemo<Vec3 | null>(() => {
+ if (!isEditingActive || !activeStep) return null;
+ const box = new Box3();
+ for (const nodeId of activeStep.componentNodeIds) {
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+ node.updateWorldMatrix(true, false);
+ box.expandByObject(node);
+ }
+ if (box.isEmpty()) return null;
+ return box.getCenter(new Vector3()).toArray() as Vec3;
+ }, [isEditingActive, activeStep, nodesById]);
+
+ const highlightedSet = useMemo(
+ () => new Set(highlightedNodeIds ?? []),
+ [highlightedNodeIds]
+ );
+
+ const hiddenSet = useMemo(
+ () => new Set(hiddenNodeIds ?? []),
+ [hiddenNodeIds]
+ );
+
+ /** nodeId → index of the first step that installs it */
+ const stepIndexByNode = useMemo(() => {
+ const map = new Map<string, number>();
+ steps.forEach((step, index) => {
+ for (const nodeId of step.componentNodeIds) {
+ if (!map.has(nodeId)) map.set(nodeId, index);
+ }
+ });
+ return map;
+ }, [steps]);
+
+ // --- Component visual states (visibility + material overrides) ---------------
+
+ const overridesRef = useRef(new Map<Mesh, MaterialOverrides>());
+
+ // AssemblyScene is keyed by scene uuid, so unmount means the scene is done:
+ // dispose the cloned override materials.
+ useEffect(() => {
+ const overrides = overridesRef.current;
+ return () => {
+ for (const entry of overrides.values()) {
+ if (entry.ghost) disposeMaterials(entry.ghost);
+ if (entry.highlight) disposeMaterials(entry.highlight);
+ if (entry.selected) disposeMaterials(entry.selected);
+ if (entry.external) disposeMaterials(entry.external);
+ if (entry.fade) disposeMaterials(entry.fade);
+ }
+ overrides.clear();
+ };
+ }, []);
+
+ useEffect(() => {
+ const overrides = overridesRef.current;
+
+ // Reset: everything visible with its original material
+ for (const node of nodesById.values()) {
+ node.visible = true;
+ }
+ for (const [mesh, entry] of overrides) {
+ mesh.material = entry.original;
+ mesh.renderOrder = 0;
+ }
+
+ const applyVisual = (node: Object3D, visual: ComponentVisual) => {
+ if (visual === "hidden") {
+ node.visible = false;
+ return;
+ }
+ if (visual === "solid") return;
+ node.traverse((object) => {
+ if (!(object as Mesh).isMesh) return;
+ const mesh = object as Mesh;
+ if (visual === "ghost") {
+ mesh.material = getOverride(mesh, overrides, "ghost");
+ // Draw transparent ghosts after opaque components to limit sorting artifacts
+ mesh.renderOrder = 1;
+ } else {
+ mesh.material = getOverride(mesh, overrides, "highlight");
+ }
+ });
+ };
+
+ // While the animation plays, later-step components stay hidden until their own
+ // step installs them, so playback reads as a real build-up rather than a
+ // ghosted preview. The future-components toggle still applies while paused.
+ const effectiveFutureMode: FutureComponentsMode = isPlaying
+ ? "hidden"
+ : futureMode;
+
+ for (const [nodeId, stepIndex] of stepIndexByNode) {
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+ applyVisual(
+ node,
+ visualForComponent(stepIndex, activeStepIndex, effectiveFutureMode)
+ );
+ }
+
+ // Components no step installs are never "already there": they get the same
+ // treatment as future-step components (hidden during playback, the
+ // future-components toggle while paused). Skipped when there are no steps
+ // at all — a plain model preview should show everything.
+ if (steps.length > 0 && leafBounds) {
+ const unassignedVisual = visualForComponent(
+ undefined,
+ activeStepIndex,
+ effectiveFutureMode
+ );
+ for (const leaf of leafBounds) {
+ if (stepIndexByNode.has(leaf.nodeId)) continue;
+ const node = nodesById.get(leaf.nodeId);
+ if (!node) continue;
+ applyVisual(node, unassignedVisual);
+ }
+ }
+
+ // External (BOM) highlight: emissive tint, forced visible even when the
+ // component's step would hide it ("show me all the M8 bolts")
+ for (const nodeId of highlightedSet) {
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+ node.visible = true;
+ node.traverse((object) => {
+ if (!(object as Mesh).isMesh) return;
+ const mesh = object as Mesh;
+ mesh.material = getOverride(mesh, overrides, "external");
+ mesh.renderOrder = 0;
+ });
+ }
+
+ // Explicitly hidden components (fixtures/reference geometry) always hide,
+ // even when highlighted
+ for (const nodeId of hiddenSet) {
+ const node = nodesById.get(nodeId);
+ if (node) node.visible = false;
+ }
+
+ // The selection renders on top of everything else. It's the same set as the
+ // external highlight above (both come from `highlightedNodeIds`), so a
+ // selected component is forced visible there, then gets the strong "selected"
+ // material here — regardless of whether it was picked in the viewer or the
+ // Components panel.
+ for (const nodeId of highlightedSet) {
+ const node = nodesById.get(nodeId);
+ if (!node || !node.visible) continue;
+ node.traverse((object) => {
+ if (!(object as Mesh).isMesh) return;
+ const mesh = object as Mesh;
+ mesh.material = getOverride(mesh, overrides, "selected");
+ });
+ }
+ }, [
+ nodesById,
+ stepIndexByNode,
+ steps.length,
+ leafBounds,
+ activeStepIndex,
+ futureMode,
+ isPlaying,
+ highlightedSet,
+ hiddenSet
+ ]);
+
+ // --- Animation -----------------------------------------------------------
+
+ const mixer = useMemo(() => new AnimationMixer(scene), [scene]);
+ const actionRef = useRef<ReturnType<AnimationMixer["clipAction"]> | null>(
+ null
+ );
+ /** Seconds elapsed within the active step's timeline segment */
+ const localElapsedRef = useRef(0);
+ const finishedRef = useRef(false);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: seekVersion intentionally re-applies a pending seek within the same step
+ useEffect(() => {
+ const step = steps[activeStepIndex];
+
+ // Consume any pending seek; otherwise the step starts at 0
+ const seek = seekRef.current;
+ seekRef.current = null;
+ localElapsedRef.current = seek ?? 0;
+ finishedRef.current = false;
+ playheadRef.current =
+ (startTimes[activeStepIndex] ?? 0) + localElapsedRef.current;
+
+ if (!step) return;
+
+ // Editing this step's path: keep components at their seated pose, skip the clip
+ // so the animation doesn't fight the drag handles.
+ if (editMotion && step.id === editMotion.stepId) return;
+
+ const clip = buildStepClip(step, nodesById);
+ if (!clip) return;
+
+ // Save seated transforms so we can restore them when the step changes
+ const restore = step.componentNodeIds
+ .map((nodeId) => nodesById.get(nodeId))
+ .filter((node): node is Object3D => Boolean(node))
+ .map((node) => ({
+ node,
+ position: node.position.clone(),
+ quaternion: node.quaternion.clone()
+ }));
+
+ const action = mixer.clipAction(clip);
+ action.setLoop(LoopOnce, 1);
+ action.clampWhenFinished = true;
+ action.play();
+ if (seek !== null) {
+ action.time = Math.min(seek, clip.duration);
+ mixer.update(0);
+ }
+ actionRef.current = action;
+
+ return () => {
+ action.stop();
+ mixer.uncacheClip(clip);
+ actionRef.current = null;
+ for (const { node, position, quaternion } of restore) {
+ node.position.copy(position);
+ node.quaternion.copy(quaternion);
+ }
+ };
+ // seekVersion re-applies a seek within the same step
+ }, [
+ mixer,
+ nodesById,
+ steps,
+ activeStepIndex,
+ seekVersion,
+ seekRef,
+ playheadRef,
+ startTimes,
+ editMotion
+ ]);
+
+ useEffect(() => {
+ if (actionRef.current) actionRef.current.paused = !isPlaying;
+ }, [isPlaying]);
+
+ // --- Seated fade-in ---------------------------------------------------
+ // Steps that install components without an animation fade them in at the
+ // seated pose instead of popping: planner-flagged steps (no collision-free
+ // path exists) and any non-first step whose display motion resolved to
+ // "none" (no stored motion and no collision-free fallback). Runs after the
+ // visual-state pass, which assigns the base materials this overrides.
+ const fadeRef = useRef<{
+ meshes: Mesh[];
+ materials: Material[];
+ seconds: number;
+ } | null>(null);
+
+ useEffect(() => {
+ const step = steps[activeStepIndex];
+ // Editing this step: keep its components solid at the seated pose, no fade.
+ if (editMotion && step && editMotion.stepId === step.id) {
+ fadeRef.current = null;
+ return;
+ }
+ const fadesIn =
+ step &&
+ step.motion.type === "none" &&
+ step.componentNodeIds.length > 0 &&
+ (step.flagged || activeStepIndex > 0);
+ if (!fadesIn) {
+ fadeRef.current = null;
+ return;
+ }
+
+ const overrides = overridesRef.current;
+ const meshes: Mesh[] = [];
+ const materials: Material[] = [];
+ for (const nodeId of step.componentNodeIds) {
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+ node.traverse((object) => {
+ if (!(object as Mesh).isMesh) return;
+ const mesh = object as Mesh;
+ const override = getOverride(mesh, overrides, "fade");
+ for (const material of Array.isArray(override)
+ ? override
+ : [override]) {
+ material.transparent = true;
+ material.opacity = 0;
+ material.depthWrite = false;
+ materials.push(material);
+ }
+ mesh.material = override;
+ // Draw after opaque components while transparent
+ mesh.renderOrder = 1;
+ meshes.push(mesh);
+ });
+ }
+ if (meshes.length === 0) {
+ fadeRef.current = null;
+ return;
+ }
+
+ const segment = segments[activeStepIndex] ?? 0;
+ fadeRef.current = {
+ meshes,
+ materials,
+ seconds: segment > 0 ? Math.min(FADE_SECONDS, segment) : FADE_SECONDS
+ };
+
+ return () => {
+ fadeRef.current = null;
+ // Materials are reassigned by the visual-state pass on step change
+ for (const mesh of meshes) mesh.renderOrder = 0;
+ };
+ }, [steps, activeStepIndex, nodesById, segments, editMotion]);
+
+ useFrame(() => {
+ const fade = fadeRef.current;
+ if (!fade) return;
+ const progress =
+ fade.seconds > 0
+ ? Math.min(localElapsedRef.current / fade.seconds, 1)
+ : 1;
+ for (const material of fade.materials) {
+ material.opacity = progress;
+ material.transparent = progress < 1;
+ material.depthWrite = progress >= 1;
+ }
+ });
+
+ useFrame((_, delta) => {
+ if (isPlaying) {
+ mixer.update(delta);
+ localElapsedRef.current += delta;
+ }
+ const segment = segments[activeStepIndex] ?? 0;
+ const clamped = Math.min(localElapsedRef.current, segment);
+ playheadRef.current = (startTimes[activeStepIndex] ?? 0) + clamped;
+ if (
+ isPlaying &&
+ !finishedRef.current &&
+ segment > 0 &&
+ localElapsedRef.current >= segment
+ ) {
+ finishedRef.current = true;
+ onStepFinished?.();
+ }
+ });
+
+ // --- Camera ----------------------------------------------------------------
+
+ // Expose a live-camera reader for the "Set view" button (per-step camera).
+ useEffect(() => {
+ capturePoseRef.current = () => {
+ if (!controls) return null;
+ const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
+ return {
+ position: camera.position.toArray() as Vec3,
+ target: controls.target.toArray() as Vec3,
+ fov
+ };
+ };
+ return () => {
+ capturePoseRef.current = null;
+ };
+ }, [camera, controls, capturePoseRef]);
+
+ const frameBox = useCallback(
+ (box: Box3) => {
+ if (box.isEmpty() || !controls) return;
+ const center = box.getCenter(new Vector3());
+ const radius = box.getSize(new Vector3()).length() / 2;
+ const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
+ const distance = Math.max(
+ (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.4,
+ radius * 2
+ );
+ const direction = camera.position
+ .clone()
+ .sub(controls.target)
+ .normalize();
+ // Front-top-right isometric (models are Z-up, -Y front)
+ if (direction.lengthSq() === 0) direction.set(1, -1, 1).normalize();
+ camera.position.copy(center).addScaledVector(direction, distance);
+ controls.target.copy(center);
+ controls.update();
+ },
+ [camera, controls]
+ );
+
+ // The whole-assembly bounds set the standing camera distance: per-step
+ // transitions keep this distance and only rotate, so the zoom never jumps
+ // between steps. Prefer the graph's seated bounds — measuring the scene
+ // mid-animation would inflate the box with displaced components.
+ const getAssemblyBox = useCallback((): Box3 => {
+ if (assemblyBounds) {
+ return new Box3(
+ new Vector3(...(assemblyBounds.min as [number, number, number])),
+ new Vector3(...(assemblyBounds.max as [number, number, number]))
+ );
+ }
+ return new Box3().setFromObject(scene);
+ }, [assemblyBounds, scene]);
+
+ // Initial framing of the whole assembly
+ const framedSceneRef = useRef<Object3D | null>(null);
+ useEffect(() => {
+ if (!controls || framedSceneRef.current === scene) return;
+ framedSceneRef.current = scene;
+ frameBox(getAssemblyBox());
+ }, [scene, controls, frameBox, getAssemblyBox]);
+
+ // Smoothly approached camera pose (per-step rotation); cleared when the
+ // user grabs the controls so they can take over mid-transition
+ const desiredPoseRef = useRef<{ position: Vector3; target: Vector3 } | null>(
+ null
+ );
+
+ // Signature of the last pose the per-step effect framed. Guards against
+ // re-framing when nothing framing-relevant changed — the effect otherwise
+ // re-runs on every new `steps` array reference (any revalidation, or a component
+ // selection that restages the draft), silently yanking the camera back and
+ // discarding the orbit the user did to inspect the selected component.
+ const lastFramedKeyRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (!controls) return;
+ const cancel = () => {
+ desiredPoseRef.current = null;
+ };
+ controls.addEventListener("start", cancel);
+ return () => controls.removeEventListener("start", cancel);
+ }, [controls]);
+
+ // Transition by orbiting around the target — the view direction rotates
+ // and the distance eases, so the model never leaves the frame the way a
+ // straight-line position lerp can.
+ useFrame((_, delta) => {
+ const desired = desiredPoseRef.current;
+ if (!desired || !controls) return;
+ const alpha = 1 - Math.exp(-delta * 4);
+
+ controls.target.lerp(desired.target, alpha);
+
+ const currentOffset = camera.position.clone().sub(controls.target);
+ const desiredOffset = desired.position.clone().sub(desired.target);
+ const currentDistance = Math.max(currentOffset.length(), 1e-3);
+ const desiredDistance = Math.max(desiredOffset.length(), 1e-3);
+
+ const direction = currentOffset
+ .divideScalar(currentDistance)
+ .lerp(desiredOffset.divideScalar(desiredDistance), alpha);
+ if (direction.lengthSq() < 1e-6) {
+ // Opposite directions: nudge through the desired side
+ direction.copy(desired.position).sub(desired.target).normalize();
+ }
+ direction.normalize();
+
+ const distance =
+ currentDistance + (desiredDistance - currentDistance) * alpha;
+ camera.position.copy(controls.target).addScaledVector(direction, distance);
+ controls.update();
+
+ if (
+ camera.position.distanceToSquared(desired.position) < 0.01 &&
+ controls.target.distanceToSquared(desired.target) < 0.01
+ ) {
+ desiredPoseRef.current = null;
+ }
+ });
+
+ // Selecting/highlighting components intentionally does NOT move the camera —
+ // the red tint (+ forced visibility) is the feedback. Auto-framing here
+ // yanked the view away every time a component was picked in the components panel.
+
+ // Per-step camera: explicit pose wins; otherwise keep the standing
+ // whole-assembly distance and rotate so the active component and its travel
+ // face the camera — the zoom stays steady, only the view angle changes.
+ useEffect(() => {
+ const step = steps[activeStepIndex];
+ if (!step || !controls) return;
+
+ // Only re-frame when the active step (or a framing-relevant input) actually
+ // changes. A bare re-render — or a revalidation / component selection that hands
+ // us a new-but-equivalent `steps` array — must not recompute a pose and pull
+ // the camera off wherever the user orbited it to.
+ const framingKey = [
+ activeStepIndex,
+ step.id,
+ JSON.stringify(step.camera ?? null),
+ JSON.stringify(step.componentNodeIds),
+ JSON.stringify(step.motion),
+ futureMode,
+ [...hiddenSet].sort().join(",")
+ ].join("|");
+ if (framingKey === lastFramedKeyRef.current) return;
+ lastFramedKeyRef.current = framingKey;
+
+ if (step.camera) {
+ desiredPoseRef.current = {
+ position: new Vector3(...step.camera.position),
+ target: new Vector3(...step.camera.target)
+ };
+ if (camera instanceof PerspectiveCamera) {
+ camera.fov = step.camera.fov;
+ camera.updateProjectionMatrix();
+ }
+ return;
+ }
+
+ if (step.componentNodeIds.length === 0) return;
+
+ const assemblyBox = getAssemblyBox();
+ if (assemblyBox.isEmpty()) return;
+ const center = assemblyBox.getCenter(new Vector3());
+ const radius = assemblyBox.getSize(new Vector3()).length() / 2;
+ const fov = camera instanceof PerspectiveCamera ? camera.fov : 45;
+ const distance = Math.max(
+ (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.25,
+ radius * 2
+ );
+
+ const componentBox = new Box3();
+ for (const nodeId of step.componentNodeIds) {
+ const node = nodesById.get(nodeId);
+ if (node) componentBox.expandByObject(node);
+ }
+ if (componentBox.isEmpty()) return;
+ const componentCenter = componentBox.getCenter(new Vector3());
+
+ // Aim mostly at the assembly (context) with a nudge toward the component
+ const target = center.clone().lerp(componentCenter, 0.3);
+
+ // Where the action happens: the seated pose and the travel midpoint
+ const motionDirection = insertionDirection(step.motion);
+ const lookPoints = [componentCenter];
+ const startOffset = insertionStartOffset(step.motion);
+ if (startOffset) {
+ lookPoints.push(
+ componentCenter.clone().addScaledVector(startOffset, 0.5)
+ );
+ }
+
+ // Occluders: everything that renders during this step, weighted by how
+ // strongly it hides the action (ghosted future components barely count)
+ const stepComponents = new Set(step.componentNodeIds);
+ const occluders: { min: Vector3; max: Vector3; weight: number }[] = [];
+ for (const leaf of leafBounds ?? []) {
+ if (stepComponents.has(leaf.nodeId)) continue;
+ if (hiddenSet.has(leaf.nodeId)) continue;
+ const leafStep = stepIndexByNode.get(leaf.nodeId);
+ const isFuture = leafStep !== undefined && leafStep > activeStepIndex;
+ if (isFuture && futureMode === "hidden") continue;
+ occluders.push({
+ min: new Vector3(...(leaf.bbox.min as [number, number, number])),
+ max: new Vector3(...(leaf.bbox.max as [number, number, number])),
+ weight: isFuture && futureMode === "ghost" ? 0.3 : 1
+ });
+ }
+
+ // Candidate view directions: two elevation rings around the up axis,
+ // plus the current view. Pick the one that sees the action with the
+ // fewest components in the way, preferring lateral travel and small turns.
+ const up = camera.up.clone().normalize();
+ let basisU = new Vector3().crossVectors(up, new Vector3(0, 0, 1));
+ if (basisU.lengthSq() < 1e-6) {
+ basisU = new Vector3().crossVectors(up, new Vector3(1, 0, 0));
+ }
+ basisU.normalize();
+ const basisV = new Vector3().crossVectors(up, basisU).normalize();
+
+ const currentDirection = camera.position
+ .clone()
+ .sub(controls.target)
+ .normalize();
+ const candidates: Vector3[] = [];
+ if (currentDirection.lengthSq() > 1e-6) candidates.push(currentDirection);
+ for (const elevation of [0.3, 0.55]) {
+ const horizontal = Math.sqrt(1 - elevation * elevation);
+ for (let i = 0; i < 8; i++) {
+ const azimuth = (i / 8) * Math.PI * 2;
+ candidates.push(
+ new Vector3()
+ .addScaledVector(basisU, Math.cos(azimuth) * horizontal)
+ .addScaledVector(basisV, Math.sin(azimuth) * horizontal)
+ .addScaledVector(up, elevation)
+ .normalize()
+ );
+ }
+ }
+
+ let bestDirection = candidates[0] ?? new Vector3(1, 1, 1).normalize();
+ let bestScore = Number.POSITIVE_INFINITY;
+ for (const candidate of candidates) {
+ const eye = target.clone().addScaledVector(candidate, distance);
+ let score = 0;
+ // How much is in the way of seeing the action?
+ for (const point of lookPoints) {
+ for (const occluder of occluders) {
+ if (segmentIntersectsBox(eye, point, occluder.min, occluder.max)) {
+ score += occluder.weight;
+ }
+ }
+ }
+ // Prefer travel running across the screen, not into it
+ if (motionDirection) {
+ score +=
+ 4 * Math.max(0, Math.abs(candidate.dot(motionDirection)) - 0.6);
+ }
+ // Prefer small turns from the current view
+ score += 1.75 * (1 - candidate.dot(currentDirection));
+ if (score < bestScore) {
+ bestScore = score;
+ bestDirection = candidate;
+ }
+ }
+
+ desiredPoseRef.current = {
+ position: target.clone().addScaledVector(bestDirection, distance),
+ target
+ };
+ }, [
+ steps,
+ activeStepIndex,
+ nodesById,
+ camera,
+ controls,
+ getAssemblyBox,
+ leafBounds,
+ hiddenSet,
+ stepIndexByNode,
+ futureMode
+ ]);
+
+ // --- Selection -------------------------------------------------------------
+
+ const handleClick = useCallback(
+ (clickEvent: ThreeEvent<MouseEvent>) => {
+ if (readOnly || !onSelectComponents) return;
+ clickEvent.stopPropagation();
+ // three.js raycasting ignores Object3D.visible, so a hidden enclosing
+ // component still reports as the closest hit. Walk the front-to-back
+ // intersections and pick the nearest component that is actually rendered,
+ // letting clicks pass through hidden geometry to the components inside it.
+ const nodeId = findVisibleNodeId(clickEvent.intersections);
+ if (!nodeId) return;
+ // Selection is controlled by `highlightedNodeIds`: shift-click extends the
+ // current selection, a plain click replaces it. Emit the new set and let
+ // the parent own the state so it stays in lockstep with the Components panel
+ // and clears instantly when the parent resets it (e.g. starting Add components).
+ const next = clickEvent.nativeEvent.shiftKey
+ ? new Set(highlightedSet)
+ : new Set<string>();
+ if (clickEvent.nativeEvent.shiftKey && next.has(nodeId)) {
+ next.delete(nodeId);
+ } else {
+ next.add(nodeId);
+ }
+ onSelectComponents([...next]);
+ },
+ [readOnly, onSelectComponents, highlightedSet]
+ );
+
+ // A box drag just completed the selection — swallow the click that fires at
+ // the end of the drag so it doesn't immediately clear what we just selected.
+ const boxJustSelectedRef = useRef(false);
+
+ const handlePointerMissed = useCallback(
+ (pointerEvent: MouseEvent) => {
+ if (readOnly || !onSelectComponents || pointerEvent.shiftKey) return;
+ if (boxJustSelectedRef.current) {
+ boxJustSelectedRef.current = false;
+ return;
+ }
+ if (highlightedSet.size === 0) return;
+ onSelectComponents([]);
+ },
+ [readOnly, onSelectComponents, highlightedSet]
+ );
+
+ // --- Box (marquee) selection ---------------------------------------------
+ // Plain drag orbits as usual. Holding Shift turns the drag into a rubber-band
+ // rectangle that adds every visible component whose center falls inside it to the
+ // selection (the CAD Shift+box = add convention). Env is read through a ref so
+ // the window listeners attach once yet always see the latest camera,
+ // selection, and callbacks.
+ const boxEnvRef = useRef({
+ readOnly,
+ onSelectComponents,
+ editMotion,
+ leafBounds,
+ nodesById,
+ highlightedSet,
+ onBoxRect,
+ camera,
+ controls,
+ gl
+ });
+ boxEnvRef.current = {
+ readOnly,
+ onSelectComponents,
+ editMotion,
+ leafBounds,
+ nodesById,
+ highlightedSet,
+ onBoxRect,
+ camera,
+ controls,
+ gl
+ };
+
+ useEffect(() => {
+ const drag = {
+ active: false,
+ startX: 0,
+ startY: 0,
+ moved: false
+ };
+ const localX = (event: PointerEvent, rect: DOMRect) =>
+ event.clientX - rect.left;
+ const localY = (event: PointerEvent, rect: DOMRect) =>
+ event.clientY - rect.top;
+
+ const onDown = (event: PointerEvent) => {
+ const env = boxEnvRef.current;
+ boxJustSelectedRef.current = false;
+ // Box-select only while Shift is held; otherwise the drag orbits.
+ if (
+ event.button !== 0 ||
+ !event.shiftKey ||
+ env.readOnly ||
+ !env.onSelectComponents ||
+ env.editMotion ||
+ event.target !== env.gl.domElement
+ ) {
+ return;
+ }
+ const rect = env.gl.domElement.getBoundingClientRect();
+ if (env.controls) env.controls.enabled = false; // suppress orbit for the box
+ drag.active = true;
+ drag.startX = localX(event, rect);
+ drag.startY = localY(event, rect);
+ drag.moved = false;
+ env.onBoxRect?.({
+ left: drag.startX,
+ top: drag.startY,
+ width: 0,
+ height: 0
+ });
+ };
+
+ const onMove = (event: PointerEvent) => {
+ if (!drag.active) return;
+ const env = boxEnvRef.current;
+ const rect = env.gl.domElement.getBoundingClientRect();
+ const x = localX(event, rect);
+ const y = localY(event, rect);
+ const width = Math.abs(x - drag.startX);
+ const height = Math.abs(y - drag.startY);
+ if (width > 3 || height > 3) drag.moved = true;
+ env.onBoxRect?.({
+ left: Math.min(drag.startX, x),
+ top: Math.min(drag.startY, y),
+ width,
+ height
+ });
+ };
+
+ const onUp = (event: PointerEvent) => {
+ if (!drag.active) return;
+ drag.active = false;
+ const env = boxEnvRef.current;
+ if (env.controls) env.controls.enabled = true;
+ env.onBoxRect?.(null);
+ // A click, not a drag — let the miss handler clear the selection instead.
+ if (!drag.moved || !env.onSelectComponents) return;
+ const rect = env.gl.domElement.getBoundingClientRect();
+ const endX = localX(event, rect);
+ const endY = localY(event, rect);
+ const minX = Math.min(drag.startX, endX);
+ const maxX = Math.max(drag.startX, endX);
+ const minY = Math.min(drag.startY, endY);
+ const maxY = Math.max(drag.startY, endY);
+ const center = new Vector3();
+ const inside: string[] = [];
+ for (const leaf of env.leafBounds ?? []) {
+ if (!env.nodesById.get(leaf.nodeId)?.visible) continue;
+ const min = leaf.bbox.min as [number, number, number];
+ const max = leaf.bbox.max as [number, number, number];
+ center
+ .set(
+ (min[0] + max[0]) / 2,
+ (min[1] + max[1]) / 2,
+ (min[2] + max[2]) / 2
+ )
+ .project(env.camera);
+ if (center.z > 1) continue; // behind the camera / beyond the far plane
+ const sx = (center.x * 0.5 + 0.5) * rect.width;
+ const sy = (-center.y * 0.5 + 0.5) * rect.height;
+ if (sx >= minX && sx <= maxX && sy >= minY && sy <= maxY) {
+ inside.push(leaf.nodeId);
+ }
+ }
+ boxJustSelectedRef.current = true;
+ // Shift+box adds to the current selection.
+ const set = new Set(env.highlightedSet);
+ for (const nodeId of inside) set.add(nodeId);
+ env.onSelectComponents([...set]);
+ };
+
+ window.addEventListener("pointerdown", onDown, { capture: true });
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onUp);
+ return () => {
+ window.removeEventListener("pointerdown", onDown, { capture: true });
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ };
+ }, []);
+
+ return (
+ <>
+ <primitive
+ object={scene}
+ onClick={handleClick}
+ onPointerMissed={handlePointerMissed}
+ />
+ {isEditingActive && editMotion && onMotionChange && seatedCentroid && (
+ <MotionPathEditor
+ key={editMotion.stepId}
+ motion={editMotion.motion}
+ seatedPosition={seatedCentroid}
+ scale={assemblyDiagonal}
+ onMotionChange={(motion) => onMotionChange(editMotion.stepId, motion)}
+ />
+ )}
+ </>
+ );
+}
+
+/**
+ * Does the open segment from `origin` to `end` pass through the AABB?
+ * Slab clipping; ignores grazing contact right at the endpoint so a box
+ * around the look-at point does not count as occluding itself.
+ */
+function segmentIntersectsBox(
+ origin: Vector3,
+ end: Vector3,
+ min: Vector3,
+ max: Vector3
+): boolean {
+ let tMin = 0;
+ let tMax = 0.98; // stop just short of the look-at point
+ const axes = ["x", "y", "z"] as const;
+ for (const axis of axes) {
+ const delta = end[axis] - origin[axis];
+ if (Math.abs(delta) < 1e-9) {
+ if (origin[axis] < min[axis] || origin[axis] > max[axis]) return false;
+ continue;
+ }
+ let tNear = (min[axis] - origin[axis]) / delta;
+ let tFar = (max[axis] - origin[axis]) / delta;
+ if (tNear > tFar) [tNear, tFar] = [tFar, tNear];
+ tMin = Math.max(tMin, tNear);
+ tMax = Math.min(tMax, tFar);
+ if (tMin > tMax) return false;
+ }
+ return true;
+}
+
+/**
+ * Where a component starts relative to its seated pose for the given insertion
+ * motion. Null when the motion does not translate the component.
+ */
+function insertionStartOffset(motion: AssemblyStep["motion"]): Vector3 | null {
+ switch (motion.type) {
+ case "linear": {
+ const direction = new Vector3(...motion.direction).normalize();
+ return direction.multiplyScalar(-motion.distance);
+ }
+ case "L": {
+ const offset = new Vector3();
+ for (const segment of motion.segments) {
+ const direction = new Vector3(...segment.direction).normalize();
+ offset.addScaledVector(direction, -segment.distance);
+ }
+ return offset;
+ }
+ case "helix": {
+ const axis = new Vector3(...motion.axis).normalize();
+ const travel = motion.approach + motion.pitch * motion.turns;
+ return axis.multiplyScalar(-travel);
+ }
+ default:
+ return null;
+ }
+}
+
+/**
+ * The dominant travel direction of an insertion motion (used to pick a
+ * camera angle where the motion reads laterally). Null for motions that
+ * do not translate the component.
+ */
+function insertionDirection(motion: AssemblyStep["motion"]): Vector3 | null {
+ switch (motion.type) {
+ case "linear":
+ return new Vector3(...motion.direction).normalize();
+ case "L": {
+ let longest: Vector3 | null = null;
+ let longestDistance = 0;
+ for (const segment of motion.segments) {
+ if (Math.abs(segment.distance) > longestDistance) {
+ longestDistance = Math.abs(segment.distance);
+ longest = new Vector3(...segment.direction);
+ }
+ }
+ return longest ? longest.normalize() : null;
+ }
+ case "helix":
+ return new Vector3(...motion.axis).normalize();
+ default:
+ return null;
+ }
+}
+
+function formatTime(seconds: number): string {
+ const safe = Math.max(0, seconds);
+ const minutes = Math.floor(safe / 60);
+ const remainder = Math.floor(safe % 60);
+ return `${minutes}:${String(remainder).padStart(2, "0")}`;
+}
+
+/** True when the keyboard event is aimed at a text field, so shortcuts like
+ * Cmd/Ctrl+A should fall through to the browser's own select-all. */
+function isEditableTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ const tag = target.tagName;
+ return (
+ tag === "INPUT" ||
+ tag === "TEXTAREA" ||
+ tag === "SELECT" ||
+ target.isContentEditable
+ );
+}
+
+function findNodeId(object: Object3D): string | null {
+ let current: Object3D | null = object;
+ while (current) {
+ const nodeId = current.userData?.nodeId;
+ if (typeof nodeId === "string" && nodeId.length > 0) return nodeId;
+ current = current.parent;
+ }
+ return null;
+}
+
+/** True only if the object and every ancestor are visible (i.e. rendered). */
+function isRendered(object: Object3D): boolean {
+ let current: Object3D | null = object;
+ while (current) {
+ if (!current.visible) return false;
+ current = current.parent;
+ }
+ return true;
+}
+
+/**
+ * The component id of the nearest intersection that is actually rendered. Skips
+ * hidden geometry (raycasting ignores `visible`) so clicks fall through to the
+ * frontmost visible component behind or inside it.
+ */
+function findVisibleNodeId(
+ intersections: readonly { object: Object3D }[]
+): string | null {
+ for (const intersection of intersections) {
+ if (!isRendered(intersection.object)) continue;
+ const nodeId = findNodeId(intersection.object);
+ if (nodeId) return nodeId;
+ }
+ return null;
+}
+
+function getOverride(
+ mesh: Mesh,
+ cache: Map<Mesh, MaterialOverrides>,
+ kind: OverrideKind
+): Material | Material[] {
+ let entry = cache.get(mesh);
+ if (!entry) {
+ entry = { original: mesh.material };
+ cache.set(mesh, entry);
+ }
+ let override = entry[kind];
+ if (!override) {
+ const emissiveColor =
+ kind === "highlight"
+ ? HIGHLIGHT_COLOR
+ : kind === "selected"
+ ? SELECTED_COLOR
+ : EXTERNAL_COLOR;
+ override =
+ kind === "ghost"
+ ? cloneAsGhost(entry.original)
+ : kind === "fade"
+ ? cloneAsFade(entry.original)
+ : cloneWithEmissive(entry.original, emissiveColor);
+ entry[kind] = override;
+ }
+ return override;
+}
+
+/**
+ * Fading-in flagged component: the original material starting fully transparent.
+ * The scene animates opacity 0 → 1 across the step; at 1 the material is
+ * switched back to opaque so it renders like any seated component.
+ */
+function cloneAsFade(material: Material | Material[]): Material | Material[] {
+ const clone = (source: Material): Material => {
+ const cloned = source.clone();
+ cloned.transparent = true;
+ cloned.opacity = 0;
+ cloned.depthWrite = false;
+ return cloned;
+ };
+ return Array.isArray(material) ? material.map(clone) : clone(material);
+}
+
+/**
+ * Ghosted future component: the original material at low opacity so components keep
+ * their color while reading as "not installed yet".
+ */
+function cloneAsGhost(material: Material | Material[]): Material | Material[] {
+ const clone = (source: Material): Material => {
+ const cloned = source.clone();
+ cloned.transparent = true;
+ cloned.opacity = GHOST_OPACITY;
+ cloned.depthWrite = false;
+ return cloned;
+ };
+ return Array.isArray(material) ? material.map(clone) : clone(material);
+}
+
+function cloneWithEmissive(
+ material: Material | Material[],
+ emissiveColor: number
+): Material | Material[] {
+ const clone = (source: Material): Material => {
+ const cloned = source.clone();
+ if (cloned instanceof MeshStandardMaterial) {
+ cloned.emissive = new Color(emissiveColor);
+ cloned.emissiveIntensity = 0.4;
+ } else if ("color" in cloned) {
+ (cloned as MeshBasicMaterial).color.lerp(new Color(emissiveColor), 0.5);
+ }
+ return cloned;
+ };
+ return Array.isArray(material) ? material.map(clone) : clone(material);
+}
+
+function disposeMaterials(material: Material | Material[]) {
+ if (Array.isArray(material)) {
+ for (const entry of material) entry.dispose();
+ } else {
+ material.dispose();
+ }
+}
+
+function OverlayNavButton({
+ side,
+ className,
+ ...props
+}: React.ButtonHTMLAttributes<HTMLButtonElement> & {
+ side: "left" | "right";
+}) {
+ return (
+ <button
+ type="button"
+ className={cn(
+ "absolute top-1/2 z-10 flex h-20 w-12 -translate-y-1/2 items-center justify-center rounded-lg",
+ "text-foreground/30 transition-colors hover:bg-background/40 hover:text-foreground/90",
+ "disabled:pointer-events-none disabled:opacity-0",
+ side === "left" ? "left-2" : "right-2",
+ className
+ )}
+ {...props}
+ >
+ <svg
+ className="h-8 w-8"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d={side === "left" ? "M15 18l-6-6 6-6" : "M9 6l6 6-6 6"}
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ </button>
+ );
+}
+
+function ControlButton({
+ isActive = false,
+ className,
+ ...props
+}: React.ButtonHTMLAttributes<HTMLButtonElement> & { isActive?: boolean }) {
+ return (
+ <button
+ type="button"
+ className={cn(
+ "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50",
+ isActive && "bg-accent text-accent-foreground",
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function ChevronLeftIcon() {
+ return (
+ <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path
+ d="M15 18l-6-6 6-6"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+}
+
+function ChevronRightIcon() {
+ return (
+ <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path
+ d="M9 6l6 6-6 6"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+}
+
+function PlayIcon() {
+ return (
+ <svg
+ className="h-4 w-4"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d="M8 5.14v13.72a1 1 0 001.5.87l11-6.86a1 1 0 000-1.74l-11-6.86a1 1 0 00-1.5.87z" />
+ </svg>
+ );
+}
+
+function PauseIcon() {
+ return (
+ <svg
+ className="h-4 w-4"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <rect x="6" y="5" width="4" height="14" rx="1" />
+ <rect x="14" y="5" width="4" height="14" rx="1" />
+ </svg>
+ );
+}
+
+function GhostIcon() {
+ return (
+ <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <rect
+ x="4"
+ y="4"
+ width="16"
+ height="16"
+ rx="2"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeDasharray="3 2"
+ />
+ <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" />
+ </svg>
+ );
+}
+
+function HiddenIcon() {
+ return (
+ <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path
+ d="M3 3l18 18M10.6 5.1A9.8 9.8 0 0112 5c7 0 10 7 10 7a16.7 16.7 0 01-3.2 4.2M6.6 6.6A16.4 16.4 0 002 12s3 7 10 7a9.9 9.9 0 004.3-1"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M9.9 9.9a3 3 0 004.2 4.2"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ />
+ </svg>
+ );
+}
+
+function SolidIcon() {
+ return (
+ <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <path
+ d="M12 3l8 4.5v9L12 21l-8-4.5v-9L12 3z"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinejoin="round"
+ />
+ <path
+ d="M12 12l8-4.5M12 12L4 7.5M12 12v9"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinejoin="round"
+ />
+ </svg>
+ );
+}
diff --git a/packages/viewer/src/AssemblyViewer.tsx b/packages/viewer/src/AssemblyViewer.tsx
new file mode 100644
index 0000000000..e2853337d7
--- /dev/null
+++ b/packages/viewer/src/AssemblyViewer.tsx
@@ -0,0 +1,79 @@
+import { GizmoHelper, GizmoViewcube, OrbitControls } from "@react-three/drei";
+import { Canvas } from "@react-three/fiber";
+import type { ReactNode } from "react";
+import { cn } from "./utils";
+
+export type AssemblyViewerProps = {
+ children?: ReactNode;
+ mode?: "dark" | "light";
+ /** Orientation cube in the top-right with click-to-snap views */
+ viewCube?: boolean;
+ className?: string;
+};
+
+/**
+ * Canvas wrapper for assembly playback: neutral studio lighting, orbit
+ * controls, and a transparent, resize-safe canvas. Colors follow the same
+ * dark/light convention as ModelViewer in @carbon/react.
+ */
+export function AssemblyViewer({
+ children,
+ mode = "dark",
+ viewCube = true,
+ className
+}: AssemblyViewerProps) {
+ const isDarkMode = mode === "dark";
+
+ return (
+ <div
+ className={cn(
+ "relative h-full w-full",
+ isDarkMode ? "bg-[#141619]" : "bg-white",
+ className
+ )}
+ >
+ <Canvas
+ gl={{ antialias: true, alpha: true }}
+ // CAD-style home view: models are Z-up with -Y as front, so +Z is
+ // screen-up (bottom faces down) and the (+X, -Y, +Z) octant shows the
+ // front, right, and top faces
+ camera={{
+ position: [100, -100, 100],
+ up: [0, 0, 1],
+ fov: 45,
+ near: 0.1,
+ far: 100000
+ }}
+ resize={{ debounce: 0 }}
+ style={{ position: "absolute", inset: 0 }}
+ >
+ <ambientLight intensity={isDarkMode ? 0.6 : 0.8} />
+ <hemisphereLight
+ color={0xffffff}
+ groundColor={isDarkMode ? 0x202329 : 0xd4d4d8}
+ intensity={0.5}
+ />
+ <directionalLight position={[1, 1, 1]} intensity={1.6} />
+ <directionalLight position={[-1, 0.5, -1]} intensity={0.8} />
+ <OrbitControls makeDefault enableDamping dampingFactor={0.1} />
+ {viewCube && (
+ // GizmoHelper animates the default OrbitControls on face clicks
+ <GizmoHelper alignment="top-right" margin={[56, 56]}>
+ <GizmoViewcube
+ // Converted models keep raw CAD coordinates (Z-up, like
+ // Onshape/STEP), so label the axes with CAD semantics instead of
+ // drei's Y-up default. Order is [+X, -X, +Y, -Y, +Z, -Z].
+ faces={["Right", "Left", "Back", "Front", "Top", "Bottom"]}
+ color={isDarkMode ? "#2a2d33" : "#e4e4e7"}
+ hoverColor={isDarkMode ? "#3f4450" : "#cbd5e1"}
+ textColor={isDarkMode ? "#e4e4e7" : "#27272a"}
+ strokeColor={isDarkMode ? "#71757d" : "#71717a"}
+ opacity={1}
+ />
+ </GizmoHelper>
+ )}
+ {children}
+ </Canvas>
+ </div>
+ );
+}
diff --git a/packages/viewer/src/MotionPathEditor.tsx b/packages/viewer/src/MotionPathEditor.tsx
new file mode 100644
index 0000000000..7a8e10e47f
--- /dev/null
+++ b/packages/viewer/src/MotionPathEditor.tsx
@@ -0,0 +1,228 @@
+import { Line } from "@react-three/drei";
+import { type ThreeEvent, useThree } from "@react-three/fiber";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Plane, Vector3 } from "three";
+import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
+import { motionToWaypoints, waypointsToMotion } from "./motion";
+import type { Motion, Vec3 } from "./types";
+
+/**
+ * In-scene editor for a step's insertion motion, rendered as a red path with
+ * drag-and-drop waypoints. Grab a sphere and drag it (it moves in the plane
+ * facing the camera); the LAST waypoint is the seated (final) pose and is
+ * locked. Double-click the path to insert a waypoint; select one and press
+ * Delete to remove it.
+ *
+ * Edits serialize back to a RELATIVE motion (`linear`/`L`) via
+ * `waypointsToMotion`, so they apply to every component of a rigid-group step. Pure
+ * translation — components keep their seated orientation (see the plan / decision #2).
+ *
+ * Lives outside the AnimationMixer clip lifecycle: while editing, the player
+ * skips building the step clip so components stay seated and the handles are not
+ * fought by playback.
+ */
+export function MotionPathEditor({
+ motion,
+ seatedPosition,
+ scale,
+ onMotionChange
+}: {
+ motion: Motion;
+ /** Centroid of the step's components' seated world positions (path anchor). */
+ seatedPosition: Vec3;
+ /** Assembly diagonal (world units) — sizes the waypoint handles. */
+ scale: number;
+ onMotionChange: (motion: Motion) => void;
+}) {
+ const camera = useThree((state) => state.camera);
+ const controls = useThree(
+ (state) => state.controls
+ ) as unknown as OrbitControlsImpl | null;
+
+ const [points, setPoints] = useState<Vector3[]>(() =>
+ motionToWaypoints(motion, seatedPosition, {
+ defaultDistance: scale > 0 ? scale * 0.25 : undefined
+ }).map((point) => new Vector3(...point))
+ );
+ const [selected, setSelected] = useState<number | null>(null);
+ const [hovered, setHovered] = useState<number | null>(null);
+ // Mirror of `points` for the drag-end commit (state is async).
+ const pointsRef = useRef(points);
+ useEffect(() => {
+ pointsRef.current = points;
+ }, [points]);
+ // Active drag: which waypoint, and the camera-facing plane it slides in.
+ const dragRef = useRef<{ index: number; plane: Plane } | null>(null);
+
+ const lastIndex = points.length - 1;
+ const handleRadius = Math.max(scale * 0.014, 0.5);
+
+ const commit = useCallback(
+ (pts: Vector3[]) =>
+ onMotionChange(
+ waypointsToMotion(
+ pts.map((point) => point.toArray() as Vec3),
+ seatedPosition
+ )
+ ),
+ [onMotionChange, seatedPosition]
+ );
+
+ const onPointerDown = useCallback(
+ (index: number, event: ThreeEvent<PointerEvent>) => {
+ if (index === lastIndex) return; // seated pose is locked
+ event.stopPropagation();
+ (event.target as Element).setPointerCapture?.(event.pointerId);
+ setSelected(index);
+ const anchor = pointsRef.current[index];
+ if (!anchor) return;
+ // Slide in the plane facing the camera, through the grabbed waypoint.
+ const normal = camera.getWorldDirection(new Vector3());
+ dragRef.current = {
+ index,
+ plane: new Plane().setFromNormalAndCoplanarPoint(normal, anchor.clone())
+ };
+ if (controls) controls.enabled = false;
+ },
+ [camera, controls, lastIndex]
+ );
+
+ const onPointerMove = useCallback((event: ThreeEvent<PointerEvent>) => {
+ const drag = dragRef.current;
+ if (!drag) return;
+ event.stopPropagation();
+ const hit = new Vector3();
+ if (!event.ray.intersectPlane(drag.plane, hit)) return;
+ setPoints((previous) => {
+ const next = previous.map((point, index) =>
+ index === drag.index ? hit.clone() : point
+ );
+ pointsRef.current = next;
+ return next;
+ });
+ }, []);
+
+ const endDrag = useCallback(
+ (event: ThreeEvent<PointerEvent>) => {
+ const drag = dragRef.current;
+ if (!drag) return;
+ event.stopPropagation();
+ (event.target as Element).releasePointerCapture?.(event.pointerId);
+ dragRef.current = null;
+ if (controls) controls.enabled = true;
+ commit(pointsRef.current);
+ },
+ [commit, controls]
+ );
+
+ const insertWaypoint = useCallback(
+ (event: ThreeEvent<MouseEvent>) => {
+ event.stopPropagation();
+ const point = event.point.clone();
+ let bestSegment = 0;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ const current = pointsRef.current;
+ for (let i = 0; i < current.length - 1; i++) {
+ const from = current[i];
+ const to = current[i + 1];
+ if (!from || !to) continue;
+ const distance = distanceToSegment(point, from, to);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestSegment = i;
+ }
+ }
+ const insertIndex = bestSegment + 1;
+ const next = [...current];
+ next.splice(insertIndex, 0, point);
+ pointsRef.current = next;
+ setPoints(next);
+ setSelected(insertIndex);
+ commit(next);
+ },
+ [commit]
+ );
+
+ // Delete the selected (non-seated) waypoint, keeping at least a start + seated.
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Delete" && event.key !== "Backspace") return;
+ if (selected == null || selected === lastIndex) return;
+ if (pointsRef.current.length <= 2) return;
+ const next = pointsRef.current.filter((_, index) => index !== selected);
+ pointsRef.current = next;
+ setPoints(next);
+ setSelected(null);
+ commit(next);
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [selected, lastIndex, commit]);
+
+ // Restore orbit controls if we unmount mid-drag.
+ useEffect(() => {
+ return () => {
+ if (dragRef.current && controls) controls.enabled = true;
+ };
+ }, [controls]);
+
+ const linePoints = useMemo(
+ () => points.map((point) => point.toArray() as Vec3),
+ [points]
+ );
+
+ return (
+ <group renderOrder={10}>
+ <Line
+ points={linePoints}
+ color="#ef4444"
+ lineWidth={3}
+ depthTest={false}
+ transparent
+ onDoubleClick={insertWaypoint}
+ />
+ {points.map((point, index) => {
+ const isSeated = index === lastIndex;
+ const isActive = index === selected || index === hovered;
+ return (
+ <mesh
+ key={index}
+ position={point}
+ renderOrder={11}
+ onPointerDown={(event) => onPointerDown(index, event)}
+ onPointerMove={onPointerMove}
+ onPointerUp={endDrag}
+ onPointerOver={(event) => {
+ if (isSeated) return;
+ event.stopPropagation();
+ setHovered(index);
+ }}
+ onPointerOut={() => setHovered((h) => (h === index ? null : h))}
+ >
+ <sphereGeometry
+ args={[
+ isActive && !isSeated ? handleRadius * 1.3 : handleRadius,
+ 20,
+ 20
+ ]}
+ />
+ <meshBasicMaterial
+ color={isSeated ? "#9ca3af" : isActive ? "#f59e0b" : "#ef4444"}
+ depthTest={false}
+ transparent
+ />
+ </mesh>
+ );
+ })}
+ </group>
+ );
+}
+
+/** Shortest distance from a point to the segment [a, b]. */
+function distanceToSegment(point: Vector3, a: Vector3, b: Vector3): number {
+ const ab = b.clone().sub(a);
+ const lengthSq = ab.lengthSq();
+ if (lengthSq === 0) return point.distanceTo(a);
+ const t = Math.max(0, Math.min(1, point.clone().sub(a).dot(ab) / lengthSq));
+ return point.distanceTo(a.clone().addScaledVector(ab, t));
+}
diff --git a/packages/viewer/src/camera.test.ts b/packages/viewer/src/camera.test.ts
new file mode 100644
index 0000000000..040633ef50
--- /dev/null
+++ b/packages/viewer/src/camera.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from "vitest";
+import { computeStepCameraPose, computeStepCameras } from "./camera";
+import { indexAssemblyGraph } from "./graph";
+import type { AssemblyGraph, AssemblyGraphNode, Motion, Vec3 } from "./types";
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+const NONE: Motion = { type: "none" };
+
+function leaf(nodeId: string, min: Vec3, max: Vec3): AssemblyGraphNode {
+ return {
+ nodeId,
+ name: nodeId,
+ isAssembly: false,
+ geometryHash: nodeId,
+ transform: IDENTITY,
+ bbox: { min, max },
+ volume: 1000,
+ color: [0.5, 0.5, 0.5, 1],
+ children: []
+ };
+}
+
+// partA sits small at the origin. partB is a wide wall standing between the
+// origin and the +Y viewpoints (the Z-up candidate rings lead with +Y), so it
+// genuinely blocks partA's default sight line — which lets us prove that
+// excluding it (as a future part) matters.
+const graph: AssemblyGraph = {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: 2,
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [-50, -5, -50], max: [50, 60, 50] },
+ volume: null,
+ color: null,
+ children: [
+ leaf("partA", [-5, -5, -5], [5, 5, 5]),
+ leaf("partB", [-50, 40, -50], [50, 60, 50])
+ ]
+ }
+};
+
+const index = indexAssemblyGraph(graph);
+
+/** Local slab test mirroring the module's, for asserting the sight line. */
+function blocked(
+ eye: Vec3,
+ look: Vec3,
+ box: { min: Vec3; max: Vec3 }
+): boolean {
+ const axes: [number, number, number, number][] = [
+ [eye[0], look[0], box.min[0], box.max[0]],
+ [eye[1], look[1], box.min[1], box.max[1]],
+ [eye[2], look[2], box.min[2], box.max[2]]
+ ];
+ let tMin = 0;
+ let tMax = 0.98;
+ for (const [o, e, boxMin, boxMax] of axes) {
+ const delta = e - o;
+ if (Math.abs(delta) < 1e-9) {
+ if (o < boxMin || o > boxMax) return false;
+ continue;
+ }
+ let tNear = (boxMin - o) / delta;
+ let tFar = (boxMax - o) / delta;
+ if (tNear > tFar) [tNear, tFar] = [tFar, tNear];
+ tMin = Math.max(tMin, tNear);
+ tMax = Math.min(tMax, tFar);
+ if (tMin > tMax) return false;
+ }
+ return true;
+}
+
+describe("computeStepCameraPose", () => {
+ it("returns a standing pose that frames the subject", () => {
+ const pose = computeStepCameraPose(index, ["partA"], NONE, []);
+ expect(pose).not.toBeNull();
+ expect(pose?.fov).toBe(45);
+ // target is the assembly center nudged toward the part
+ expect(pose?.target[1]).toBeGreaterThan(0);
+ expect(pose?.target[1]).toBeLessThan(28);
+ });
+
+ it("returns null for degenerate geometry", () => {
+ expect(computeStepCameraPose(index, ["missing"], NONE, [])).toBeNull();
+ });
+});
+
+describe("computeStepCameras", () => {
+ const groups = [
+ { componentNodeIds: ["partA"], motion: NONE },
+ { componentNodeIds: ["partB"], motion: NONE }
+ ];
+ const cameras = computeStepCameras(groups, index);
+
+ it("produces one pose per group", () => {
+ expect(cameras).toHaveLength(2);
+ expect(cameras[0]).not.toBeNull();
+ expect(cameras[1]).not.toBeNull();
+ });
+
+ it("ignores not-yet-animated (future) parts when framing an earlier step", () => {
+ // Step 0's occluders must be empty — partB installs later, so it must not
+ // push the camera. The baked pose therefore equals the no-occluder pose.
+ expect(cameras[0]).toEqual(
+ computeStepCameraPose(index, ["partA"], NONE, [])
+ );
+ // And this is not vacuous: partB genuinely blocks partA's default view, so
+ // if it were wrongly treated as an occluder the pose would change.
+ expect(
+ computeStepCameraPose(index, ["partA"], NONE, ["partB"])
+ ).not.toEqual(cameras[0]);
+ });
+
+ it("gives a step an unobstructed view over already-animated parts", () => {
+ // Step 1 installs partB; partA is already seated and could occlude. The
+ // chosen eye must keep a clear sight line to partB.
+ const pose = cameras[1];
+ expect(pose).not.toBeNull();
+ if (!pose) return;
+ const partBCenter: Vec3 = [0, 50, 0];
+ const partA = index.nodesById.get("partA");
+ expect(partA).toBeDefined();
+ if (!partA) return;
+ expect(blocked(pose.position, partBCenter, partA.bbox)).toBe(false);
+ });
+
+ it("ignores components no step installs — they are never on the canvas", () => {
+ // Same layout plus a stray wall assigned to NO group. Never-installed
+ // components render like future ones (not present), so the stray wall
+ // must not push the camera either.
+ const strayGraph: AssemblyGraph = {
+ ...graph,
+ componentCount: 3,
+ root: {
+ ...graph.root,
+ children: [
+ ...graph.root.children,
+ leaf("stray", [-50, 40, -50], [50, 60, 50])
+ ]
+ }
+ };
+ const strayIndex = indexAssemblyGraph(strayGraph);
+ const strayCameras = computeStepCameras(
+ [{ componentNodeIds: ["partA"], motion: NONE }],
+ strayIndex
+ );
+ expect(strayCameras[0]).toEqual(
+ computeStepCameraPose(strayIndex, ["partA"], NONE, [])
+ );
+ // Not vacuous: treated as an occluder, the stray wall would change the pose
+ expect(
+ computeStepCameraPose(strayIndex, ["partA"], NONE, ["stray"])
+ ).not.toEqual(strayCameras[0]);
+ });
+});
diff --git a/packages/viewer/src/camera.ts b/packages/viewer/src/camera.ts
new file mode 100644
index 0000000000..4b256db58c
--- /dev/null
+++ b/packages/viewer/src/camera.ts
@@ -0,0 +1,283 @@
+import type { AssemblyGraphIndex } from "./graph";
+import type { CameraPose, Motion, Vec3 } from "./types";
+
+// Plain-array vector math so this runs server-side (step generation) without
+// pulling three.js into the bundle. Mirrors the viewer's live occlusion-aware
+// framing (AssemblyPlayer), but baked per step at planning time.
+
+const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
+const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
+const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s];
+const dot = (a: Vec3, b: Vec3): number =>
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+const cross = (a: Vec3, b: Vec3): Vec3 => [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0]
+];
+const len = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]);
+const normalize = (a: Vec3): Vec3 => {
+ const l = len(a);
+ return l > 1e-9 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0];
+};
+const lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [
+ a[0] + (b[0] - a[0]) * t,
+ a[1] + (b[1] - a[1]) * t,
+ a[2] + (b[2] - a[2]) * t
+];
+
+type Aabb = { min: Vec3; max: Vec3 };
+
+const boxCenter = (box: Aabb): Vec3 => [
+ (box.min[0] + box.max[0]) / 2,
+ (box.min[1] + box.max[1]) / 2,
+ (box.min[2] + box.max[2]) / 2
+];
+
+function unionBounds(
+ nodeIds: Iterable<string>,
+ graphIndex: AssemblyGraphIndex
+): Aabb | null {
+ let min: Vec3 | null = null;
+ let max: Vec3 | null = null;
+ for (const nodeId of nodeIds) {
+ const node = graphIndex.nodesById.get(nodeId);
+ if (!node) continue;
+ if (!min || !max) {
+ min = [...node.bbox.min];
+ max = [...node.bbox.max];
+ } else {
+ min = [
+ Math.min(min[0], node.bbox.min[0]),
+ Math.min(min[1], node.bbox.min[1]),
+ Math.min(min[2], node.bbox.min[2])
+ ];
+ max = [
+ Math.max(max[0], node.bbox.max[0]),
+ Math.max(max[1], node.bbox.max[1]),
+ Math.max(max[2], node.bbox.max[2])
+ ];
+ }
+ }
+ return min && max ? { min, max } : null;
+}
+
+/** Where a component starts relative to its seated pose; null if it doesn't translate. */
+function insertionStartOffset(motion: Motion): Vec3 | null {
+ switch (motion.type) {
+ case "linear":
+ return scale(normalize(motion.direction), -motion.distance);
+ case "L": {
+ let offset: Vec3 = [0, 0, 0];
+ for (const segment of motion.segments) {
+ offset = add(
+ offset,
+ scale(normalize(segment.direction), -segment.distance)
+ );
+ }
+ return offset;
+ }
+ case "helix":
+ return scale(
+ normalize(motion.axis),
+ -(motion.approach + motion.pitch * motion.turns)
+ );
+ default:
+ return null;
+ }
+}
+
+/** Dominant travel direction of an insertion; null if it doesn't translate. */
+function insertionDirection(motion: Motion): Vec3 | null {
+ switch (motion.type) {
+ case "linear":
+ return normalize(motion.direction);
+ case "L": {
+ let longest: Vec3 | null = null;
+ let longestDistance = 0;
+ for (const segment of motion.segments) {
+ if (Math.abs(segment.distance) > longestDistance) {
+ longestDistance = Math.abs(segment.distance);
+ longest = segment.direction;
+ }
+ }
+ return longest ? normalize(longest) : null;
+ }
+ case "helix":
+ return normalize(motion.axis);
+ default:
+ return null;
+ }
+}
+
+/** Slab test: does the segment origin→end pass through the box? Stops just short
+ * of the look-at point so a box AT the target doesn't count as blocking it. */
+function segmentIntersectsBox(origin: Vec3, end: Vec3, box: Aabb): boolean {
+ // Per-axis slabs, unrolled so tuple access stays literal-indexed.
+ const axes: [number, number, number, number][] = [
+ [origin[0], end[0], box.min[0], box.max[0]],
+ [origin[1], end[1], box.min[1], box.max[1]],
+ [origin[2], end[2], box.min[2], box.max[2]]
+ ];
+ let tMin = 0;
+ let tMax = 0.98;
+ for (const [o, e, boxMin, boxMax] of axes) {
+ const delta = e - o;
+ if (Math.abs(delta) < 1e-9) {
+ if (o < boxMin || o > boxMax) return false;
+ continue;
+ }
+ let tNear = (boxMin - o) / delta;
+ let tFar = (boxMax - o) / delta;
+ if (tNear > tFar) [tNear, tFar] = [tFar, tNear];
+ tMin = Math.max(tMin, tNear);
+ tMax = Math.min(tMax, tFar);
+ if (tMin > tMax) return false;
+ }
+ return true;
+}
+
+/**
+ * A baked camera pose that frames a step's components on their motion path with
+ * an unobstructed sight line, given only the components present when the step
+ * plays (`occluderNodeIds` — the already-animated parts). Keeps the standing
+ * whole-assembly distance and only rotates the view angle. Returns null when the
+ * geometry is degenerate (no subject bounds / zero-size assembly).
+ */
+export function computeStepCameraPose(
+ graphIndex: AssemblyGraphIndex,
+ subjectNodeIds: readonly string[],
+ motion: Motion,
+ occluderNodeIds: Iterable<string>,
+ fov = 45
+): CameraPose | null {
+ const assembly = graphIndex.graph.root.bbox;
+ const assemblyRadius = len(sub(assembly.max, assembly.min)) / 2;
+ if (assemblyRadius <= 1e-6) return null;
+
+ const subjectBounds = unionBounds(subjectNodeIds, graphIndex);
+ if (!subjectBounds) return null;
+ const subjectCenter = boxCenter(subjectBounds);
+ const assemblyCenter = boxCenter(assembly);
+
+ // Constant standing distance — never re-zoom per step
+ const distance = Math.max(
+ (assemblyRadius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.25,
+ assemblyRadius * 2
+ );
+
+ // Aim mostly at the whole assembly (context) with a nudge toward the part
+ const target = lerp(assemblyCenter, subjectCenter, 0.3);
+
+ // Where the action happens: the seated pose and the travel midpoint
+ const lookPoints: Vec3[] = [subjectCenter];
+ const startOffset = insertionStartOffset(motion);
+ if (startOffset) {
+ lookPoints.push(add(subjectCenter, scale(startOffset, 0.5)));
+ }
+
+ const subjectSet = new Set(subjectNodeIds);
+ const occluders: Aabb[] = [];
+ for (const nodeId of occluderNodeIds) {
+ if (subjectSet.has(nodeId)) continue;
+ const node = graphIndex.nodesById.get(nodeId);
+ if (node) occluders.push(node.bbox);
+ }
+
+ const motionDirection = insertionDirection(motion);
+
+ // Candidate directions: two elevation rings around the up axis (models
+ // keep CAD coordinates, so up is +Z and "elevated" means above the model)
+ const up: Vec3 = [0, 0, 1];
+ let basisU = cross(up, [0, 0, 1]);
+ if (len(basisU) < 1e-6) basisU = cross(up, [1, 0, 0]);
+ basisU = normalize(basisU);
+ const basisV = normalize(cross(up, basisU));
+
+ const candidates: Vec3[] = [];
+ for (const elevation of [0.3, 0.55]) {
+ const horizontal = Math.sqrt(1 - elevation * elevation);
+ for (let i = 0; i < 8; i++) {
+ const azimuth = (i / 8) * Math.PI * 2;
+ candidates.push(
+ normalize(
+ add(
+ add(
+ scale(basisU, Math.cos(azimuth) * horizontal),
+ scale(basisV, Math.sin(azimuth) * horizontal)
+ ),
+ scale(up, elevation)
+ )
+ )
+ );
+ }
+ }
+
+ let bestDirection = candidates[0] ?? normalize([1, 1, 1]);
+ let bestScore = Number.POSITIVE_INFINITY;
+ for (const candidate of candidates) {
+ const eye = add(target, scale(candidate, distance));
+ let score = 0;
+ // How much is in the way of seeing the action?
+ for (const point of lookPoints) {
+ for (const occluder of occluders) {
+ if (segmentIntersectsBox(eye, point, occluder)) score += 1;
+ }
+ }
+ // Prefer travel running across the screen, not into it
+ if (motionDirection) {
+ score += 4 * Math.max(0, Math.abs(dot(candidate, motionDirection)) - 0.6);
+ }
+ if (score < bestScore) {
+ bestScore = score;
+ bestDirection = candidate;
+ }
+ }
+
+ return {
+ position: add(target, scale(bestDirection, distance)),
+ target,
+ fov
+ };
+}
+
+/**
+ * Bakes a camera pose for each step group in sequence order. A step's occluders
+ * are exactly the components already animated by the time it plays — parts from
+ * earlier groups. Components from LATER groups and components in no group are
+ * not on the canvas (never-installed parts render like future ones), so they
+ * never push the camera around. Returns one entry per group (null where
+ * geometry is degenerate).
+ */
+export function computeStepCameras(
+ groups: readonly { componentNodeIds: string[]; motion: Motion }[],
+ graphIndex: AssemblyGraphIndex,
+ fov = 45
+): (CameraPose | null)[] {
+ const groupIndexByNode = new Map<string, number>();
+ groups.forEach((group, index) => {
+ for (const nodeId of group.componentNodeIds) {
+ groupIndexByNode.set(nodeId, index);
+ }
+ });
+
+ return groups.map((group, index) => {
+ const subject = new Set(group.componentNodeIds);
+ const occluders: string[] = [];
+ for (const leaf of graphIndex.leaves) {
+ if (subject.has(leaf.nodeId)) continue;
+ const leafGroup = groupIndexByNode.get(leaf.nodeId);
+ // Present only if it belongs to an earlier step.
+ if (leafGroup !== undefined && leafGroup < index) {
+ occluders.push(leaf.nodeId);
+ }
+ }
+ return computeStepCameraPose(
+ graphIndex,
+ group.componentNodeIds,
+ group.motion,
+ occluders,
+ fov
+ );
+ });
+}
diff --git a/packages/viewer/src/describe.ts b/packages/viewer/src/describe.ts
new file mode 100644
index 0000000000..b555cc68ff
--- /dev/null
+++ b/packages/viewer/src/describe.ts
@@ -0,0 +1,82 @@
+import { type AssemblyGraphIndex, groupComponentNodeIds } from "./graph";
+import type { AssemblyStep, Fastener } from "./types";
+
+/**
+ * A named subassembly unit for title derivation: a set of leaf components that
+ * assemble as one body and share a single step titled by `name` (e.g. an
+ * authored "Board" or a purchased PCB), rather than enumerating every component.
+ */
+export type NamedUnit = { name: string; componentNodeIds: string[] };
+
+/**
+ * Display title for a step. An explicit title always wins. When the step's
+ * components are exactly a named subassembly unit, the unit's name is used
+ * ("Add Board") instead of listing every component inside it. Otherwise the title
+ * is derived from the step's components and fastener, e.g.
+ * "Add Seat Rail Clamp, M5 SHCS (×4)". Returns null when there is nothing to
+ * derive from (no title, no known components, no fastener).
+ */
+export function describeStep(
+ step: Pick<AssemblyStep, "title" | "componentNodeIds" | "fastener">,
+ index: AssemblyGraphIndex | null,
+ units?: NamedUnit[]
+): string | null {
+ if (step.title && step.title.trim().length > 0) return step.title;
+
+ const fastenerSegment = describeFastener(step.fastener);
+
+ // A step whose components are exactly a named subassembly is titled by that
+ // subassembly's name, never by listing each of its (often hundreds of) components.
+ const unit = units ? matchNamedUnit(step.componentNodeIds, units) : null;
+ if (unit) {
+ const segments = [unit.name];
+ if (fastenerSegment) segments.push(fastenerSegment);
+ return `Add ${segments.join(", ")}`;
+ }
+
+ const groups = index
+ ? groupComponentNodeIds(step.componentNodeIds, index)
+ : [];
+
+ if (groups.length === 0 && !fastenerSegment) return null;
+
+ const verb =
+ groups.length === 0 ? "Install" : groups.length === 1 ? "Add" : "Assemble";
+
+ const segments = groups.map((group) =>
+ group.count > 1 ? `${group.name} (×${group.count})` : group.name
+ );
+ if (fastenerSegment) segments.push(fastenerSegment);
+
+ return `${verb} ${segments.join(", ")}`;
+}
+
+/** "M5 SHCS (×4)" / "M5 SHCS", or null when the step has no fastener spec. */
+function describeFastener(fastener: Fastener | null): string | null {
+ const spec = fastener?.spec?.trim();
+ if (!spec) return null;
+ const count = fastener?.count;
+ return count && count > 1 ? `${spec} (×${count})` : spec;
+}
+
+/** The named unit whose components set-equal the step's components, if any. */
+function matchNamedUnit(
+ componentNodeIds: string[],
+ units: NamedUnit[]
+): NamedUnit | null {
+ if (componentNodeIds.length === 0) return null;
+ const stepSet = new Set(componentNodeIds);
+ for (const unit of units) {
+ const unitSet = new Set(unit.componentNodeIds);
+ if (unitSet.size === 0 || unitSet.size !== stepSet.size) continue;
+ let equal = true;
+ for (const nodeId of unitSet) {
+ if (!stepSet.has(nodeId)) {
+ equal = false;
+ break;
+ }
+ }
+ if (equal) return unit;
+ }
+ return null;
+}
diff --git a/packages/viewer/src/fallback.test.ts b/packages/viewer/src/fallback.test.ts
new file mode 100644
index 0000000000..6a6a85d81a
--- /dev/null
+++ b/packages/viewer/src/fallback.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, it } from "vitest";
+import { synthesizeFallbackMotion } from "./fallback";
+import { indexAssemblyGraph } from "./graph";
+import type { AssemblyGraph, AssemblyGraphNode, Vec3 } from "./types";
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+function leaf(
+ nodeId: string,
+ bbox: { min: Vec3; max: Vec3 }
+): AssemblyGraphNode {
+ return {
+ nodeId,
+ name: nodeId,
+ isAssembly: false,
+ geometryHash: `hash-${nodeId}`,
+ transform: IDENTITY,
+ bbox,
+ volume: 1000,
+ color: null,
+ children: []
+ };
+}
+
+function graphOf(leaves: AssemblyGraphNode[]): AssemblyGraph {
+ return {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: leaves.length,
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [0, 0, 0], max: [0, 0, 0] },
+ volume: null,
+ color: null,
+ children: leaves
+ }
+ };
+}
+
+/** Every leaf except the moving component(s) — the "all installed" world. */
+function allExcept(
+ leaves: AssemblyGraphNode[],
+ componentNodeIds: string[]
+): Set<string> {
+ const components = new Set(componentNodeIds);
+ return new Set(
+ leaves.map((node) => node.nodeId).filter((id) => !components.has(id))
+ );
+}
+
+describe("synthesizeFallbackMotion", () => {
+ it("returns null when no component resolves to leaf geometry", () => {
+ const leaves = [leaf("base", { min: [0, 0, 0], max: [100, 100, 10] })];
+ const index = indexAssemblyGraph(graphOf(leaves));
+ expect(
+ synthesizeFallbackMotion(index, ["missing"], allExcept(leaves, []))
+ ).toBeNull();
+ expect(
+ synthesizeFallbackMotion(index, [], allExcept(leaves, []))
+ ).toBeNull();
+ });
+
+ it("lifts an unobstructed top component straight up", () => {
+ // Small box sitting on a plate: nothing above it, exits +Z
+ const leaves = [
+ leaf("base", { min: [-50, -50, 0], max: [50, 50, 10] }),
+ leaf("top", { min: [-10, -10, 10], max: [10, 10, 20] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const motion = synthesizeFallbackMotion(
+ index,
+ ["top"],
+ allExcept(leaves, ["top"])
+ );
+ expect(motion?.type).toBe("linear");
+ if (motion?.type !== "linear") throw new Error("expected linear");
+ // Removal +Z -> insertion approaches from above (direction -Z)
+ expect(motion.direction).toEqual([-0, -0, -1]);
+ expect(motion.distance).toBeGreaterThan(0);
+ });
+
+ it("escapes sideways-then-up from under an overhang", () => {
+ // Component under a canopy that blocks +Z and walls blocking +X/-X/±Y at its
+ // level, open toward -X above the walls... simpler: canopy over the component
+ // only; the component must hop +X past the canopy edge, then exit +Z
+ const leaves = [
+ leaf("base", { min: [-50, -50, 0], max: [50, 50, 10] }),
+ // canopy directly above the component, wider than it on -X/±Y so the only
+ // short hop past its footprint is +X
+ leaf("canopy", { min: [-50, -50, 30], max: [20, 50, 40] }),
+ leaf("component", { min: [-10, -10, 10], max: [10, 10, 20] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const motion = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ allExcept(leaves, ["component"])
+ );
+ expect(motion).not.toBeNull();
+ // The component exits +X (only unobstructed straight direction: -X/±Y sweep
+ // under the canopy... all lateral sweeps at z10-20 are actually free of
+ // the canopy at z30 — so this stays linear along a lateral axis
+ expect(motion?.type).toBe("linear");
+ });
+
+ it("hops past blockers when every straight exit is obstructed", () => {
+ // The component is ringed by boxes at its own level on all four sides and
+ // covered above and below by slabs that leave a gap over the +X blocker:
+ // straight exits all collide; the escape is +X after hopping... instead
+ // craft the canonical case: blockers above AND laterally except one hop
+ const leaves = [
+ leaf("component", { min: [-10, -10, 10], max: [10, 10, 20] }),
+ // slabs above and below, spanning the whole footprint
+ leaf("above", { min: [-40, -40, 25], max: [40, 40, 35] }),
+ leaf("below", { min: [-40, -40, -5], max: [40, 40, 5] }),
+ // lateral blockers on -X and ±Y at the component's level
+ leaf("wallNX", { min: [-40, -40, 5], max: [-20, 40, 25] }),
+ leaf("wallPY", { min: [-40, 20, 5], max: [40, 40, 25] }),
+ leaf("wallNY", { min: [-40, -40, 5], max: [40, -20, 25] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const motion = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ allExcept(leaves, ["component"])
+ );
+ // +X at the component's level is the only clear straight exit
+ expect(motion?.type).toBe("linear");
+ if (motion?.type !== "linear") throw new Error("expected linear");
+ expect(motion.direction).toEqual([-1, -0, -0]);
+ });
+
+ it("emits a two-segment escape when no straight exit exists", () => {
+ // Fully ringed at its level, capped above over the component footprint only:
+ // the component must hop +X (free lane at its level), then exit +Z past the
+ // cap's edge
+ const leaves = [
+ leaf("component", { min: [-10, -10, 10], max: [10, 10, 20] }),
+ // cap above the component only (footprint ends at x=15)
+ leaf("cap", { min: [-40, -40, 25], max: [15, 40, 35] }),
+ // floor below everything
+ leaf("floor", { min: [-40, -40, 0], max: [60, 40, 5] }),
+ // walls on -X and ±Y at the component's level; +X lane is open but a
+ // distant wall blocks the straight +X exit
+ leaf("wallNX", { min: [-40, -40, 5], max: [-20, 40, 25] }),
+ leaf("wallPY", { min: [-40, 20, 5], max: [60, 40, 25] }),
+ leaf("wallNY", { min: [-40, -40, 5], max: [60, -20, 25] }),
+ leaf("wallPX", { min: [50, -40, 5], max: [60, 40, 45] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const motion = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ allExcept(leaves, ["component"])
+ );
+ expect(motion?.type).toBe("L");
+ if (motion?.type !== "L") throw new Error("expected L");
+ expect(motion.segments.length).toBe(2);
+ // Insertion: first leg approaches (reverse of the exit), second settles
+ // (reverse of the hop). Every segment travels a positive distance.
+ for (const segment of motion.segments) {
+ expect(segment.distance).toBeGreaterThan(0);
+ }
+ // The settle leg reverses the +X hop -> -X insertion component
+ const settle = motion.segments[motion.segments.length - 1];
+ expect(settle?.direction[0]).toBe(-1);
+ });
+
+ it("returns null instead of fabricating a path when fully enclosed", () => {
+ const leaves = [
+ leaf("component", { min: [-10, -10, -10], max: [10, 10, 10] }),
+ // six enclosing slabs
+ leaf("top", { min: [-30, -30, 20], max: [30, 30, 30] }),
+ leaf("bottom", { min: [-30, -30, -30], max: [30, 30, -20] }),
+ leaf("px", { min: [20, -30, -30], max: [30, 30, 30] }),
+ leaf("nx", { min: [-30, -30, -30], max: [-20, 30, 30] }),
+ leaf("py", { min: [-30, 20, -30], max: [30, 30, 30] }),
+ leaf("ny", { min: [-30, -30, -30], max: [30, -20, 30] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const motion = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ allExcept(leaves, ["component"])
+ );
+ // A path through the enclosure would animate straight through geometry —
+ // the step keeps motion "none" and fades in
+ expect(motion).toBeNull();
+ });
+
+ it("refuses to synthesize for a component mated to a present part", () => {
+ // A slider-on-rail shape: the component sits INSIDE the host's bounding
+ // box (interpenetration, not face contact). Every lateral "exit" an AABB
+ // sweep would find cuts through the host on screen, so the fallback must
+ // return null (fade in) rather than fabricate one.
+ const leaves = [
+ leaf("rail", { min: [-100, -20, 0], max: [100, 20, 30] }),
+ leaf("slider", { min: [-15, -25, 5], max: [15, 25, 25] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ expect(
+ synthesizeFallbackMotion(index, ["slider"], new Set(["rail"]))
+ ).toBeNull();
+
+ // The same slider with the rail absent from the present set (not yet
+ // installed) synthesizes freely — nothing is mated on the canvas.
+ expect(
+ synthesizeFallbackMotion(index, ["slider"], new Set())
+ ).not.toBeNull();
+ });
+
+ it("ignores components that are not in the present set", () => {
+ // The canopy fully covers the component, but it belongs to a LATER step
+ // (or no step): with it absent from the present set the component exits
+ // straight up as if the canopy weren't there
+ const leaves = [
+ leaf("base", { min: [-50, -50, 0], max: [50, 50, 10] }),
+ leaf("canopy", { min: [-50, -50, 30], max: [50, 50, 40] }),
+ leaf("component", { min: [-10, -10, 10], max: [10, 10, 20] })
+ ];
+ const index = indexAssemblyGraph(graphOf(leaves));
+
+ const blocked = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ new Set(["base", "canopy"])
+ );
+ // With the canopy present the +Z exit is blocked — the fallback picks a
+ // lateral escape instead of approaching from above
+ if (blocked?.type !== "linear") throw new Error("expected linear");
+ expect(blocked.direction[2]).not.toBe(-1);
+
+ const clear = synthesizeFallbackMotion(
+ index,
+ ["component"],
+ new Set(["base"])
+ );
+ expect(clear?.type).toBe("linear");
+ if (clear?.type !== "linear") throw new Error("expected linear");
+ // Removal +Z -> insertion approaches from above
+ expect(clear.direction).toEqual([-0, -0, -1]);
+ });
+});
diff --git a/packages/viewer/src/fallback.ts b/packages/viewer/src/fallback.ts
new file mode 100644
index 0000000000..062632fcf4
--- /dev/null
+++ b/packages/viewer/src/fallback.ts
@@ -0,0 +1,237 @@
+import type { AssemblyGraphIndex } from "./graph";
+import type { Motion, Vec3 } from "./types";
+
+/**
+ * AABB-based fallback motion synthesis for steps the geometry planner left
+ * with motion "none" (old plan.json files, manually authored steps). Pure —
+ * no WebGL, unit-testable in node, same conventions as the Python planner:
+ * distances in mm, stored motion is the INSERTION (removal reversed).
+ *
+ * This is display guidance, not physics: obstacles are leaf bounding boxes.
+ * The obstacle world is the caller-provided PRESENT set — the components
+ * already installed by earlier steps. Components of later steps and components
+ * no step installs are not on the canvas, so they neither block nor redirect a
+ * fallback path.
+ *
+ * MATED components get no fallback at all: when a present component's box
+ * interpenetrates the seated box, the part engages geometry an AABB cannot
+ * reason about (a slider wrapping its rail, a screw in its bore). The one
+ * obstacle that matters would have to be ignored to synthesize anything, and
+ * whatever direction survives cuts straight through the mate on screen — a
+ * slider "inserted" sideways through its rail. Those steps return null and
+ * fade in at the seated pose until the planner or the author supplies a real
+ * motion.
+ */
+
+type Box = { min: Vec3; max: Vec3 };
+
+const EXIT_MARGIN_MM = 5;
+const HOP_MARGIN_MM = 2;
+/** Surface contact between neighbors is not an obstruction */
+const CONTACT_EPSILON_MM = 0.01;
+
+type AxisDirection = { dir: Vec3; axis: 0 | 1 | 2; sign: 1 | -1 };
+
+/** Same preference order as the Python planner's world axes: up first. */
+const DIRECTIONS: AxisDirection[] = [
+ { dir: [0, 0, 1], axis: 2, sign: 1 },
+ { dir: [0, 0, -1], axis: 2, sign: -1 },
+ { dir: [1, 0, 0], axis: 0, sign: 1 },
+ { dir: [-1, 0, 0], axis: 0, sign: -1 },
+ { dir: [0, 1, 0], axis: 1, sign: 1 },
+ { dir: [0, -1, 0], axis: 1, sign: -1 }
+];
+
+function unionBox(boxes: Box[]): Box | null {
+ const first = boxes[0];
+ if (!first) return null;
+ const min: Vec3 = [...first.min];
+ const max: Vec3 = [...first.max];
+ for (const box of boxes) {
+ for (let axis = 0; axis < 3; axis++) {
+ min[axis] = Math.min(min[axis] ?? 0, box.min[axis] ?? 0);
+ max[axis] = Math.max(max[axis] ?? 0, box.max[axis] ?? 0);
+ }
+ }
+ return { min, max };
+}
+
+function boxesOverlap(a: Box, b: Box, epsilon: number): boolean {
+ for (let axis = 0; axis < 3; axis++) {
+ if ((a.max[axis] ?? 0) - epsilon <= (b.min[axis] ?? 0)) return false;
+ if ((b.max[axis] ?? 0) - epsilon <= (a.min[axis] ?? 0)) return false;
+ }
+ return true;
+}
+
+function translateBox(
+ box: Box,
+ direction: AxisDirection,
+ distance: number
+): Box {
+ const min: Vec3 = [...box.min];
+ const max: Vec3 = [...box.max];
+ min[direction.axis] = (min[direction.axis] ?? 0) + direction.sign * distance;
+ max[direction.axis] = (max[direction.axis] ?? 0) + direction.sign * distance;
+ return { min, max };
+}
+
+/** The box swept by translating `box` along `direction` for `distance`. */
+function sweptBox(box: Box, direction: AxisDirection, distance: number): Box {
+ const min: Vec3 = [...box.min];
+ const max: Vec3 = [...box.max];
+ if (direction.sign > 0) {
+ max[direction.axis] = (max[direction.axis] ?? 0) + distance;
+ } else {
+ min[direction.axis] = (min[direction.axis] ?? 0) - distance;
+ }
+ return { min, max };
+}
+
+/** Distance until `component` separates from `assembly` along `direction`. */
+function exitTravel(
+ component: Box,
+ assembly: Box,
+ direction: AxisDirection
+): number {
+ const { axis, sign } = direction;
+ const needed =
+ sign > 0
+ ? (assembly.max[axis] ?? 0) - (component.min[axis] ?? 0)
+ : (component.max[axis] ?? 0) - (assembly.min[axis] ?? 0);
+ const extent = (component.max[axis] ?? 0) - (component.min[axis] ?? 0);
+ return Math.max(needed, extent, 0) + EXIT_MARGIN_MM;
+}
+
+/** Distance until `component` clears `obstacle` along `direction`. */
+function clearTravel(
+ component: Box,
+ obstacle: Box,
+ direction: AxisDirection
+): number {
+ const { axis, sign } = direction;
+ const needed =
+ sign > 0
+ ? (obstacle.max[axis] ?? 0) - (component.min[axis] ?? 0)
+ : (component.max[axis] ?? 0) - (obstacle.min[axis] ?? 0);
+ return Math.max(needed, 0) + HOP_MARGIN_MM;
+}
+
+function negate(direction: AxisDirection): Vec3 {
+ return direction.dir.map((c) => -c) as Vec3;
+}
+
+/**
+ * Synthesizes an insertion motion for a step's components from graph bounding
+ * boxes: a straight exit along the least-obstructed axis when one exists,
+ * else a two-segment escape (hop past the blockers, then exit). Obstacles are
+ * ONLY the leaves in `presentNodeIds` — the components already installed by
+ * earlier steps. Returns null when the components resolve to no leaf geometry,
+ * when a present component interpenetrates the seated box (a mating
+ * engagement the AABB sweep cannot respect — see module doc), or when every
+ * candidate path collides with a present component: a fabricated path that
+ * animates through geometry is worse than fading in at the seated pose, so
+ * the caller keeps motion "none" in those cases.
+ */
+export function synthesizeFallbackMotion(
+ index: AssemblyGraphIndex,
+ componentNodeIds: string[],
+ presentNodeIds: ReadonlySet<string>
+): Motion | null {
+ const componentSet = new Set(componentNodeIds);
+ const componentBoxes: Box[] = [];
+ const otherBoxes: Box[] = [];
+ for (const node of index.leaves) {
+ if (!node.bbox) continue;
+ if (componentSet.has(node.nodeId)) {
+ componentBoxes.push(node.bbox);
+ } else if (presentNodeIds.has(node.nodeId)) {
+ otherBoxes.push(node.bbox);
+ }
+ }
+
+ const component = unionBox(componentBoxes);
+ if (!component) return null;
+ const assembly = unionBox([component, ...otherBoxes]);
+ if (!assembly) return null;
+
+ // A present component interpenetrating the seated box (beyond surface
+ // contact) is a mate — refuse to fabricate a path through it. Face-on-face
+ // stacking stays within CONTACT_EPSILON_MM and still synthesizes.
+ if (
+ otherBoxes.some((box) => boxesOverlap(component, box, CONTACT_EPSILON_MM))
+ ) {
+ return null;
+ }
+ const obstacles = otherBoxes;
+
+ const candidates = DIRECTIONS.map((direction) => {
+ const travel = exitTravel(component, assembly, direction);
+ const swept = sweptBox(component, direction, travel);
+ const blockers = obstacles.filter((box) =>
+ boxesOverlap(swept, box, CONTACT_EPSILON_MM)
+ );
+ return { direction, travel, blockers };
+ }).sort(
+ (a, b) => a.blockers.length - b.blockers.length || a.travel - b.travel
+ );
+
+ const best = candidates[0];
+ if (!best) return null;
+
+ if (best.blockers.length === 0) {
+ // Straight removal along `direction` -> insertion approaches from there
+ return {
+ type: "linear",
+ direction: negate(best.direction),
+ distance: round(best.travel)
+ };
+ }
+
+ // Two-segment escape: hop perpendicular until clear of the exit blockers,
+ // then exit. Both legs must be unobstructed.
+ for (const exit of candidates) {
+ if (exit.blockers.length === 0) continue;
+ for (const hopDirection of DIRECTIONS) {
+ if (hopDirection.axis === exit.direction.axis) continue;
+
+ const hop = Math.max(
+ ...exit.blockers.map((box) => clearTravel(component, box, hopDirection))
+ );
+ const hopSwept = sweptBox(component, hopDirection, hop);
+ if (
+ obstacles.some((box) => boxesOverlap(hopSwept, box, CONTACT_EPSILON_MM))
+ ) {
+ continue;
+ }
+
+ const hopped = translateBox(component, hopDirection, hop);
+ const travel = exitTravel(hopped, assembly, exit.direction);
+ const exitSwept = sweptBox(hopped, exit.direction, travel);
+ if (
+ obstacles.some((box) =>
+ boxesOverlap(exitSwept, box, CONTACT_EPSILON_MM)
+ )
+ ) {
+ continue;
+ }
+
+ // Removal: hop then exit. Insertion reverses: enter, then settle.
+ return {
+ type: "L",
+ segments: [
+ { direction: negate(exit.direction), distance: round(travel) },
+ { direction: negate(hopDirection), distance: round(hop) }
+ ]
+ };
+ }
+ }
+
+ // Every candidate path collides with a present component — fade in at the
+ // seated pose instead of fabricating a fly-through
+ return null;
+}
+
+function round(value: number): number {
+ return Math.round(value * 1000) / 1000;
+}
diff --git a/packages/viewer/src/graph.test.ts b/packages/viewer/src/graph.test.ts
new file mode 100644
index 0000000000..40533416d2
--- /dev/null
+++ b/packages/viewer/src/graph.test.ts
@@ -0,0 +1,277 @@
+import { describe, expect, it } from "vitest";
+import { describeStep } from "./describe";
+import { groupComponentNodeIds, indexAssemblyGraph } from "./graph";
+import type { AssemblyGraph, AssemblyGraphNode } from "./types";
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+function leaf(
+ nodeId: string,
+ name: string,
+ geometryHash: string | null
+): AssemblyGraphNode {
+ return {
+ nodeId,
+ name,
+ isAssembly: false,
+ geometryHash,
+ transform: IDENTITY,
+ bbox: { min: [0, 0, 0], max: [10, 20, 30] },
+ volume: 1000,
+ color: [0.5, 0.5, 0.5, 1],
+ children: []
+ };
+}
+
+function assembly(
+ nodeId: string,
+ name: string,
+ children: AssemblyGraphNode[]
+): AssemblyGraphNode {
+ return {
+ nodeId,
+ name,
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [0, 0, 0], max: [10, 20, 30] },
+ volume: null,
+ color: null,
+ children
+ };
+}
+
+const graph: AssemblyGraph = {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: 5,
+ root: assembly("root", "Assembly", [
+ leaf("bolt-1", "M8 Bolt", "hash-bolt"),
+ leaf("bolt-2", "M8 Bolt", "hash-bolt"),
+ assembly("sub", "Bracket Sub", [
+ leaf("bolt-3", "M8 Bolt", "hash-bolt"),
+ leaf("plate-1", "Base Plate", "hash-plate")
+ ]),
+ leaf("gasket-1", "Gasket", null)
+ ])
+};
+
+describe("indexAssemblyGraph", () => {
+ const index = indexAssemblyGraph(graph);
+
+ it("indexes every node by nodeId", () => {
+ expect(index.nodesById.size).toBe(7);
+ expect(index.nodesById.get("sub")?.isAssembly).toBe(true);
+ });
+
+ it("collects leaves depth-first", () => {
+ expect(index.leaves.map((node) => node.nodeId)).toEqual([
+ "bolt-1",
+ "bolt-2",
+ "bolt-3",
+ "plate-1",
+ "gasket-1"
+ ]);
+ });
+
+ it("groups identical geometry across subassemblies", () => {
+ const bolts = index.groups.find((group) => group.key === "hash-bolt");
+ expect(bolts?.count).toBe(3);
+ expect(bolts?.nodeIds).toEqual(["bolt-1", "bolt-2", "bolt-3"]);
+ });
+
+ it("falls back to a name key for leaves without a geometry hash", () => {
+ const gasket = index.groupByNodeId.get("gasket-1");
+ expect(gasket?.key).toBe("name:Gasket");
+ expect(gasket?.count).toBe(1);
+ });
+});
+
+describe("groupComponentNodeIds", () => {
+ const index = indexAssemblyGraph(graph);
+
+ it("groups only the given ids", () => {
+ const groups = groupComponentNodeIds(
+ ["bolt-1", "bolt-3", "plate-1"],
+ index
+ );
+ expect(groups.map((group) => [group.name, group.count])).toEqual([
+ ["M8 Bolt", 2],
+ ["Base Plate", 1]
+ ]);
+ });
+
+ it("skips unknown/stale nodeIds", () => {
+ const groups = groupComponentNodeIds(["bolt-1", "gone-1"], index);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.count).toBe(1);
+ });
+
+ it("does not mutate the index groups", () => {
+ groupComponentNodeIds(["bolt-1"], index);
+ const bolts = index.groups.find((group) => group.key === "hash-bolt");
+ expect(bolts?.count).toBe(3);
+ });
+});
+
+describe("describeStep", () => {
+ const index = indexAssemblyGraph(graph);
+
+ it("uses an explicit title verbatim", () => {
+ expect(
+ describeStep(
+ {
+ title: "Torque the head",
+ componentNodeIds: ["bolt-1"],
+ fastener: null
+ },
+ index
+ )
+ ).toBe("Torque the head");
+ });
+
+ it("describes a single component", () => {
+ expect(
+ describeStep(
+ { title: null, componentNodeIds: ["plate-1"], fastener: null },
+ index
+ )
+ ).toBe("Add Base Plate");
+ });
+
+ it("counts duplicate components and appends the fastener spec", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["bolt-1", "bolt-2", "bolt-3"],
+ fastener: { spec: "M8 SHCS", count: 3 }
+ },
+ index
+ )
+ ).toBe("Add M8 Bolt (×3), M8 SHCS (×3)");
+ });
+
+ it("uses Assemble for multiple distinct components", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["plate-1", "gasket-1"],
+ fastener: null
+ },
+ index
+ )
+ ).toBe("Assemble Base Plate, Gasket");
+ });
+
+ it("uses Install for fastener-only steps", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: [],
+ fastener: { spec: "M5 SHCS", count: 4 }
+ },
+ index
+ )
+ ).toBe("Install M5 SHCS (×4)");
+ });
+
+ it("returns null when there is nothing to describe", () => {
+ expect(
+ describeStep({ title: null, componentNodeIds: [], fastener: null }, index)
+ ).toBeNull();
+ expect(
+ describeStep(
+ { title: null, componentNodeIds: ["gone"], fastener: null },
+ index
+ )
+ ).toBeNull();
+ expect(
+ describeStep(
+ { title: null, componentNodeIds: ["bolt-1"], fastener: null },
+ null
+ )
+ ).toBeNull();
+ });
+});
+
+describe("describeStep with named subassembly units", () => {
+ const index = indexAssemblyGraph(graph);
+ const units = [
+ { name: "Bracket Sub", componentNodeIds: ["plate-1", "bolt-3"] }
+ ];
+
+ it("titles a step by the unit name when its components match the unit", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["bolt-3", "plate-1"],
+ fastener: null
+ },
+ index,
+ units
+ )
+ ).toBe("Add Bracket Sub");
+ });
+
+ it("matches on the set, ignoring order and duplicates", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["plate-1", "bolt-3", "plate-1"],
+ fastener: null
+ },
+ index,
+ units
+ )
+ ).toBe("Add Bracket Sub");
+ });
+
+ it("appends the fastener spec to the unit name", () => {
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["plate-1", "bolt-3"],
+ fastener: { spec: "M5 SHCS", count: 4 }
+ },
+ index,
+ units
+ )
+ ).toBe("Add Bracket Sub, M5 SHCS (×4)");
+ });
+
+ it("still lets an explicit title win over a unit match", () => {
+ expect(
+ describeStep(
+ {
+ title: "Seat the bracket",
+ componentNodeIds: ["plate-1", "bolt-3"],
+ fastener: null
+ },
+ index,
+ units
+ )
+ ).toBe("Seat the bracket");
+ });
+
+ it("falls back to enumerating components when the set does not match a unit", () => {
+ // A superset of the unit (extra bolt) is not the unit → enumerate.
+ expect(
+ describeStep(
+ {
+ title: null,
+ componentNodeIds: ["plate-1", "bolt-3", "bolt-1"],
+ fastener: null
+ },
+ index,
+ units
+ )
+ ).toBe("Assemble Base Plate, M8 Bolt (×2)");
+ });
+});
diff --git a/packages/viewer/src/graph.ts b/packages/viewer/src/graph.ts
new file mode 100644
index 0000000000..7ea505cb47
--- /dev/null
+++ b/packages/viewer/src/graph.ts
@@ -0,0 +1,100 @@
+import type { AssemblyGraph, AssemblyGraphNode, Vec3 } from "./types";
+
+/** Distinct component (identical geometry) across the assembly, with its instances. */
+export type ComponentGroup = {
+ /** geometryHash, or `name:${name}` for leaves without one */
+ key: string;
+ name: string;
+ count: number;
+ color: [number, number, number, number] | null;
+ /** nodeIds of every instance of this component */
+ nodeIds: string[];
+ /** Per-instance volume (mm³) from the representative leaf */
+ volume: number | null;
+ /** Representative instance world bounds, mm */
+ bbox: { min: Vec3; max: Vec3 };
+};
+
+export type AssemblyGraphIndex = {
+ graph: AssemblyGraph;
+ /** Every node (assemblies and leaves) by nodeId */
+ nodesById: Map<string, AssemblyGraphNode>;
+ /** Leaf instances in depth-first order */
+ leaves: AssemblyGraphNode[];
+ /** All leaves grouped by identical geometry */
+ groups: ComponentGroup[];
+ /** Leaf nodeId → its group */
+ groupByNodeId: Map<string, ComponentGroup>;
+};
+
+function groupKey(node: AssemblyGraphNode): string {
+ return node.geometryHash ?? `name:${node.name}`;
+}
+
+/** One O(n) walk of graph.json building the lookups the editor panes need. */
+export function indexAssemblyGraph(graph: AssemblyGraph): AssemblyGraphIndex {
+ const nodesById = new Map<string, AssemblyGraphNode>();
+ const leaves: AssemblyGraphNode[] = [];
+ const groups: ComponentGroup[] = [];
+ const groupsByKey = new Map<string, ComponentGroup>();
+ const groupByNodeId = new Map<string, ComponentGroup>();
+
+ const visit = (node: AssemblyGraphNode) => {
+ nodesById.set(node.nodeId, node);
+ if (node.isAssembly || node.children.length > 0) {
+ for (const child of node.children) visit(child);
+ return;
+ }
+
+ leaves.push(node);
+ const key = groupKey(node);
+ let group = groupsByKey.get(key);
+ if (!group) {
+ group = {
+ key,
+ name: node.name,
+ count: 0,
+ color: node.color,
+ nodeIds: [],
+ volume: node.volume,
+ bbox: node.bbox
+ };
+ groupsByKey.set(key, group);
+ groups.push(group);
+ }
+ group.count += 1;
+ group.nodeIds.push(node.nodeId);
+ groupByNodeId.set(node.nodeId, group);
+ };
+
+ visit(graph.root);
+
+ return { graph, nodesById, leaves, groups, groupByNodeId };
+}
+
+/**
+ * Groups the given component nodeIds by identical geometry. Unknown/stale nodeIds
+ * (e.g. after a model re-upload) are skipped.
+ */
+export function groupComponentNodeIds(
+ componentNodeIds: string[],
+ index: AssemblyGraphIndex
+): ComponentGroup[] {
+ const result: ComponentGroup[] = [];
+ const byKey = new Map<string, ComponentGroup>();
+
+ for (const nodeId of componentNodeIds) {
+ const source = index.groupByNodeId.get(nodeId);
+ if (!source) continue;
+ let group = byKey.get(source.key);
+ if (!group) {
+ group = { ...source, count: 0, nodeIds: [] };
+ byKey.set(source.key, group);
+ result.push(group);
+ }
+ group.count += 1;
+ group.nodeIds.push(nodeId);
+ }
+
+ return result;
+}
diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts
new file mode 100644
index 0000000000..d2e3c870b5
--- /dev/null
+++ b/packages/viewer/src/index.ts
@@ -0,0 +1,55 @@
+export {
+ AssemblyPlayer,
+ type AssemblyPlayerHandle,
+ type AssemblyPlayerProps,
+ type FutureComponentsMode
+} from "./AssemblyPlayer";
+export { AssemblyViewer, type AssemblyViewerProps } from "./AssemblyViewer";
+export { computeStepCameraPose, computeStepCameras } from "./camera";
+export { describeStep, type NamedUnit } from "./describe";
+export { synthesizeFallbackMotion } from "./fallback";
+export {
+ type AssemblyGraphIndex,
+ type ComponentGroup,
+ groupComponentNodeIds,
+ indexAssemblyGraph
+} from "./graph";
+export {
+ buildStepClip,
+ displayMotionForStep,
+ exaggerateMotion,
+ type MotionKeyframeOptions,
+ type MotionKeyframes,
+ motionDuration,
+ motionToKeyframes,
+ motionTravelDistance,
+ type Pose,
+ type StepClipOptions,
+ stepTimelineSeconds
+} from "./motion";
+export {
+ type AssemblyPlan,
+ type AssemblyPlanComponent,
+ type AssemblyStepGroup,
+ buildAssemblyStepGroups,
+ CURRENT_PLAN_VERSION,
+ type PlannedMotion,
+ planMotionForComponents
+} from "./plan";
+export type {
+ AssemblyGraph,
+ AssemblyGraphNode,
+ AssemblyStep,
+ CameraPose,
+ Fastener,
+ HelixMotion,
+ LinearMotion,
+ LMotion,
+ Motion,
+ NoneMotion,
+ PathMotion,
+ Quat,
+ Vec3
+} from "./types";
+export { type UseAssemblyResult, useAssembly } from "./useAssembly";
+export { type ComponentVisual, visualForComponent } from "./visibility";
diff --git a/packages/viewer/src/motion.test.ts b/packages/viewer/src/motion.test.ts
new file mode 100644
index 0000000000..627ec77092
--- /dev/null
+++ b/packages/viewer/src/motion.test.ts
@@ -0,0 +1,738 @@
+import {
+ AnimationMixer,
+ Group,
+ Matrix4,
+ Object3D,
+ Quaternion,
+ Vector3
+} from "three";
+import { describe, expect, it } from "vitest";
+import { indexAssemblyGraph } from "./graph";
+import {
+ buildStepClip,
+ DEFAULT_WAYPOINT_DISTANCE,
+ displayMotionForStep,
+ exaggerateMotion,
+ type MotionKeyframes,
+ motionDuration,
+ motionToKeyframes,
+ motionToWaypoints,
+ motionTravelDistance,
+ type Pose,
+ waypointsToMotion
+} from "./motion";
+import type { AssemblyStep, Motion, Vec3 } from "./types";
+
+const IDENTITY_POSE: Pose = {
+ position: [0, 0, 0],
+ quaternion: [0, 0, 0, 1]
+};
+
+function positionAt(keyframes: MotionKeyframes, index: number): number[] {
+ return keyframes.positions.slice(index * 3, index * 3 + 3);
+}
+
+function quaternionAt(keyframes: MotionKeyframes, index: number): number[] {
+ return keyframes.quaternions.slice(index * 4, index * 4 + 4);
+}
+
+function lastIndex(keyframes: MotionKeyframes): number {
+ return keyframes.times.length - 1;
+}
+
+function expectVectorClose(actual: number[], expected: number[]) {
+ expect(actual.length).toBe(expected.length);
+ actual.forEach((value, index) => {
+ expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
+ });
+}
+
+function expectMonotonicTimes(keyframes: MotionKeyframes) {
+ expect(keyframes.times[0]).toBe(0);
+ for (let i = 1; i < keyframes.times.length; i++) {
+ expect(keyframes.times[i]).toBeGreaterThan(
+ keyframes.times[i - 1] ?? Number.POSITIVE_INFINITY
+ );
+ }
+}
+
+function makeStep(motion: Motion, componentNodeIds: string[]): AssemblyStep {
+ return {
+ id: "step-1",
+ title: null,
+ instructionText: null,
+ componentNodeIds,
+ motion,
+ camera: null,
+ fastener: null
+ };
+}
+
+describe("motionTravelDistance", () => {
+ it("computes travel for each motion type", () => {
+ expect(
+ motionTravelDistance({
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 80
+ })
+ ).toBe(80);
+ expect(
+ motionTravelDistance({
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 60 },
+ { direction: [0, 0, -1], distance: 20 }
+ ]
+ })
+ ).toBe(80);
+ expect(
+ motionTravelDistance({
+ type: "helix",
+ axis: [0, 0, -1],
+ origin: [0, 0, 0],
+ pitch: 0.8,
+ turns: 6,
+ approach: 30
+ })
+ ).toBeCloseTo(34.8);
+ expect(motionTravelDistance({ type: "none" })).toBe(0);
+ });
+});
+
+describe("motionDuration", () => {
+ it("scales with travel distance and clamps to 1-4 s", () => {
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6 })
+ ).toBe(1);
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 120 })
+ ).toBeCloseTo(2);
+ expect(
+ motionDuration({ type: "linear", direction: [0, 0, 1], distance: 6000 })
+ ).toBe(4);
+ expect(motionDuration({ type: "none" })).toBe(0);
+ });
+});
+
+describe("motionToKeyframes", () => {
+ it("returns null for none motions", () => {
+ expect(motionToKeyframes({ type: "none" }, IDENTITY_POSE)).toBeNull();
+ });
+
+ it("linear: starts displaced against the insertion direction and ends at the final pose", () => {
+ const basePose: Pose = {
+ position: [10, 20, 30],
+ quaternion: [0, 0, 0, 1]
+ };
+ const keyframes = motionToKeyframes(
+ { type: "linear", direction: [0, 0, -1], distance: 80 },
+ basePose,
+ { duration: 2 }
+ );
+ expect(keyframes).not.toBeNull();
+ if (!keyframes) return;
+
+ expectMonotonicTimes(keyframes);
+ expect(keyframes.times).toEqual([0, 2]);
+ expectVectorClose(positionAt(keyframes, 0), [10, 20, 110]);
+ expectVectorClose(
+ positionAt(keyframes, lastIndex(keyframes)),
+ [10, 20, 30]
+ );
+ expectVectorClose(quaternionAt(keyframes, 0), [0, 0, 0, 1]);
+ expectVectorClose(
+ quaternionAt(keyframes, lastIndex(keyframes)),
+ [0, 0, 0, 1]
+ );
+ });
+
+ it("linear: normalizes the direction vector", () => {
+ const keyframes = motionToKeyframes(
+ { type: "linear", direction: [0, 0, -10], distance: 80 },
+ IDENTITY_POSE
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ expectVectorClose(positionAt(keyframes, 0), [0, 0, 80]);
+ });
+
+ it("L: walks segments backwards from the final pose with proportional times", () => {
+ const keyframes = motionToKeyframes(
+ {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 60 },
+ { direction: [0, 0, -1], distance: 20 }
+ ]
+ },
+ IDENTITY_POSE,
+ { duration: 2 }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+
+ expectMonotonicTimes(keyframes);
+ expect(keyframes.times.length).toBe(3);
+ // 60 of 80 mm in segment 1 → 75% of the duration
+ expect(keyframes.times[1]).toBeCloseTo(1.5);
+ expect(keyframes.times[2]).toBeCloseTo(2);
+ expectVectorClose(positionAt(keyframes, 0), [-60, 0, 20]);
+ expectVectorClose(positionAt(keyframes, 1), [0, 0, 20]);
+ expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
+ });
+
+ it("helix: retracts by approach + pitch*turns and ends seated at the final pose", () => {
+ const basePose: Pose = {
+ position: [10, 20, 5],
+ quaternion: [0, 0, 0, 1]
+ };
+ const motion: Motion = {
+ type: "helix",
+ axis: [0, 0, -1],
+ origin: [10, 20, 5], // through the component center so rotation keeps position
+ pitch: 0.8,
+ turns: 6,
+ approach: 30
+ };
+ const keyframes = motionToKeyframes(motion, basePose, {
+ samplesPerTurn: 4
+ });
+ if (!keyframes) throw new Error("expected keyframes");
+
+ expectMonotonicTimes(keyframes);
+ // 1 approach start + 1 threading start + turns * samplesPerTurn samples
+ expect(keyframes.times.length).toBe(2 + 6 * 4);
+ expect(keyframes.quaternions.length).toBe((2 + 6 * 4) * 4);
+
+ // Start fully retracted along the axis: approach + pitch*turns = 34.8 mm
+ expectVectorClose(positionAt(keyframes, 0), [10, 20, 5 + 34.8]);
+ // Threading start: approach consumed, thread advance remaining
+ expectVectorClose(positionAt(keyframes, 1), [10, 20, 5 + 4.8]);
+ // Seated
+ const last = lastIndex(keyframes);
+ expectVectorClose(positionAt(keyframes, last), [10, 20, 5]);
+ expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
+
+ // Rotation actually happens between thread samples (quarter turns)
+ const intermediate = quaternionAt(keyframes, 2);
+ const final = quaternionAt(keyframes, last);
+ const dot = intermediate.reduce(
+ (sum, value, index) => sum + value * (final[index] ?? Number.NaN),
+ 0
+ );
+ expect(Math.abs(dot)).toBeLessThan(0.999);
+ });
+
+ it("helix: ends exactly at the final pose even when origin is off-axis from the component", () => {
+ const basePose: Pose = {
+ position: [10, 0, 0],
+ quaternion: [0, 0, 0, 1]
+ };
+ const keyframes = motionToKeyframes(
+ {
+ type: "helix",
+ axis: [0, 0, 1],
+ origin: [0, 0, 0],
+ pitch: 1,
+ turns: 2.5,
+ approach: 10
+ },
+ basePose
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ const last = lastIndex(keyframes);
+ expectVectorClose(positionAt(keyframes, last), [10, 0, 0]);
+ expectVectorClose(quaternionAt(keyframes, last), [0, 0, 0, 1]);
+ expectMonotonicTimes(keyframes);
+ });
+
+ it("path: passes absolute world poses through, scaling t by duration", () => {
+ const keyframes = motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 50, 50], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE,
+ { duration: 2 }
+ );
+ if (!keyframes) throw new Error("expected keyframes");
+ expect(keyframes.times).toEqual([0, 1, 2]);
+ expectVectorClose(positionAt(keyframes, 0), [0, 0, 100]);
+ expectVectorClose(positionAt(keyframes, 1), [0, 50, 50]);
+ expectVectorClose(positionAt(keyframes, 2), [0, 0, 0]);
+ });
+
+ it("path: rejects non-monotonic times", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 0, 50], quaternion: [0, 0, 0, 1] },
+ { t: 0.5, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/strictly increasing/);
+ });
+
+ it("path: rejects a last keyframe that is not the final pose", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 5], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/final pose/);
+ });
+
+ it("path: requires t to span 0..1 and at least 2 keyframes", () => {
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [{ t: 0, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/at least 2/);
+ expect(() =>
+ motionToKeyframes(
+ {
+ type: "path",
+ keyframes: [
+ { t: 0.1, position: [0, 0, 100], quaternion: [0, 0, 0, 1] },
+ { t: 1, position: [0, 0, 0], quaternion: [0, 0, 0, 1] }
+ ]
+ },
+ IDENTITY_POSE
+ )
+ ).toThrow(/span/);
+ });
+});
+
+describe("buildStepClip", () => {
+ function makeAssembly() {
+ const root = new Group();
+ const parent = new Group();
+ parent.position.set(5, 0, 0);
+ root.add(parent);
+ const component = new Object3D();
+ component.position.set(1, 2, 3);
+ component.userData.nodeId = "node-a";
+ parent.add(component);
+ root.updateMatrixWorld(true);
+ return {
+ root,
+ component,
+ parent,
+ nodesById: new Map([["node-a", component]])
+ };
+ }
+
+ it("returns null for none motions and for steps with no resolvable components", () => {
+ const { nodesById } = makeAssembly();
+ expect(
+ buildStepClip(makeStep({ type: "none" }, ["node-a"]), nodesById)
+ ).toBeNull();
+ expect(
+ buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, []),
+ nodesById
+ )
+ ).toBeNull();
+ expect(
+ buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 10 }, [
+ "missing-node"
+ ]),
+ nodesById
+ )
+ ).toBeNull();
+ });
+
+ it("builds uuid-bound position/quaternion tracks in parent-local space with a seated hold", () => {
+ const { component, nodesById } = makeAssembly();
+ const step = makeStep(
+ { type: "linear", direction: [1, 0, 0], distance: 10 },
+ ["node-a"]
+ );
+ const clip = buildStepClip(step, nodesById, {
+ duration: 2,
+ holdSeconds: 0.5
+ });
+ expect(clip).not.toBeNull();
+ if (!clip) return;
+
+ expect(clip.name).toBe("step:step-1");
+ expect(clip.duration).toBeCloseTo(2.5);
+ expect(clip.tracks.length).toBe(2);
+ const [positionTrack, quaternionTrack] = clip.tracks;
+ if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
+ expect(positionTrack.name).toBe(`${component.uuid}.position`);
+ expect(quaternionTrack.name).toBe(`${component.uuid}.quaternion`);
+
+ // World start [6,2,3] - [10,0,0] = [-4,2,3] → parent-local [-9,2,3]
+ expectVectorClose([...positionTrack.values.slice(0, 3)], [-9, 2, 3]);
+ // Seated keyframe and hold keyframe both equal the component's local pose
+ expectVectorClose([...positionTrack.values.slice(-6, -3)], [1, 2, 3]);
+ expectVectorClose([...positionTrack.values.slice(-3)], [1, 2, 3]);
+ // Hold keyframe extends the timeline
+ const times = positionTrack.times;
+ expect(times[times.length - 1]).toBeCloseTo(2.5);
+ expect(times[times.length - 2]).toBeCloseTo(2);
+ });
+
+ it("converts world-space motion into the local space of a rotated parent", () => {
+ const root = new Group();
+ const parent = new Group();
+ parent.rotation.z = Math.PI / 2;
+ root.add(parent);
+ const component = new Object3D();
+ component.userData.nodeId = "node-b";
+ parent.add(component);
+ root.updateMatrixWorld(true);
+ const nodesById = new Map([["node-b", component]]);
+
+ const step = makeStep(
+ { type: "linear", direction: [0, 1, 0], distance: 10 },
+ ["node-b"]
+ );
+ const clip = buildStepClip(step, nodesById, { holdSeconds: 0 });
+ if (!clip) throw new Error("expected clip");
+
+ const expectedStart = new Vector3(0, -10, 0).applyMatrix4(
+ new Matrix4().copy(parent.matrixWorld).invert()
+ );
+ const [positionTrack, quaternionTrack] = clip.tracks;
+ if (!positionTrack || !quaternionTrack) throw new Error("expected tracks");
+ expectVectorClose(
+ [...positionTrack.values.slice(0, 3)],
+ expectedStart.toArray()
+ );
+ expectVectorClose([...positionTrack.values.slice(-3)], [0, 0, 0]);
+
+ const localQuaternion = new Quaternion().copy(component.quaternion);
+ expectVectorClose(
+ [...quaternionTrack.values.slice(-4)],
+ [
+ localQuaternion.x,
+ localQuaternion.y,
+ localQuaternion.z,
+ localQuaternion.w
+ ]
+ );
+ });
+
+ it("clamps the default duration to 1-4 s based on travel distance", () => {
+ const { nodesById } = makeAssembly();
+ const short = buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 1 }, [
+ "node-a"
+ ]),
+ nodesById,
+ { holdSeconds: 0 }
+ );
+ const long = buildStepClip(
+ makeStep({ type: "linear", direction: [1, 0, 0], distance: 6000 }, [
+ "node-a"
+ ]),
+ nodesById,
+ { holdSeconds: 0 }
+ );
+ expect(short?.duration).toBeCloseTo(1);
+ expect(long?.duration).toBeCloseTo(4);
+ });
+
+ it("drives nodes through an AnimationMixer via uuid-bound tracks", () => {
+ const { root, component, nodesById } = makeAssembly();
+ const step = makeStep(
+ { type: "linear", direction: [1, 0, 0], distance: 10 },
+ ["node-a"]
+ );
+ const clip = buildStepClip(step, nodesById, {
+ duration: 2,
+ holdSeconds: 0
+ });
+ if (!clip) throw new Error("expected clip");
+
+ const mixer = new AnimationMixer(root);
+ mixer.clipAction(clip).play();
+
+ mixer.update(0); // t = 0 → displaced start pose (local [-9, 2, 3])
+ expect(component.position.x).toBeCloseTo(-9);
+ mixer.update(1); // t = 1 → halfway back to seated
+ expect(component.position.x).toBeCloseTo(-4);
+ expect(component.position.y).toBeCloseTo(2);
+ expect(component.position.z).toBeCloseTo(3);
+ });
+});
+
+describe("exaggerateMotion", () => {
+ const lift = {
+ type: "linear",
+ direction: [0, 0, -1] as [number, number, number],
+ distance: 15
+ } as const;
+
+ it("stretches small-component travel to a readable distance", () => {
+ // 20mm bolt in a 1000mm assembly travels at least 2.5x its size
+ const result = exaggerateMotion(lift, 20, 1000);
+ expect(result.type).toBe("linear");
+ if (result.type === "linear") {
+ expect(result.distance).toBe(50);
+ }
+ });
+
+ it("leaves large components unchanged", () => {
+ expect(exaggerateMotion(lift, 400, 1000)).toBe(lift);
+ });
+
+ it("leaves already-long travels unchanged", () => {
+ const long = { ...lift, distance: 200 };
+ expect(exaggerateMotion(long, 20, 1000)).toBe(long);
+ });
+
+ it("scales L segments proportionally", () => {
+ const motion: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 6 },
+ { direction: [0, 0, -1], distance: 4 }
+ ]
+ };
+ const result = exaggerateMotion(motion, 20, 1000);
+ if (result.type === "L") {
+ const total = result.segments.reduce((sum, s) => sum + s.distance, 0);
+ expect(total).toBeCloseTo(50);
+ expect(
+ result.segments[0]!.distance / result.segments[1]!.distance
+ ).toBeCloseTo(6 / 4);
+ } else {
+ throw new Error("expected L motion");
+ }
+ });
+
+ it("does not exaggerate none motions", () => {
+ const none = { type: "none" } as const;
+ expect(exaggerateMotion(none, 20, 1000)).toBe(none);
+ });
+});
+
+describe("displayMotionForStep", () => {
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ const graphIndex = indexAssemblyGraph({
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: 2,
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 0], max: [50, 50, 20] },
+ volume: null,
+ color: null,
+ children: [
+ {
+ nodeId: "base",
+ name: "base",
+ isAssembly: false,
+ geometryHash: "hash-base",
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 0], max: [50, 50, 10] },
+ volume: 1000,
+ color: null,
+ children: []
+ },
+ {
+ nodeId: "top",
+ name: "top",
+ isAssembly: false,
+ geometryHash: "hash-top",
+ transform: IDENTITY,
+ bbox: { min: [-10, -10, 10], max: [10, 10, 20] },
+ volume: 1000,
+ color: null,
+ children: []
+ }
+ ]
+ }
+ });
+
+ const step = (
+ overrides: Partial<
+ Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">
+ >
+ ) => ({
+ motion: { type: "none" } as Motion,
+ componentNodeIds: ["top"],
+ ...overrides
+ });
+
+ const present = new Set(["base"]);
+
+ it("keeps motion none for flagged steps — no fabricated fallback", () => {
+ expect(
+ displayMotionForStep(step({ flagged: true }), 1, graphIndex, present)
+ ).toEqual({ type: "none" });
+ });
+
+ it("synthesizes a fallback for unflagged none-motion steps after the base", () => {
+ const motion = displayMotionForStep(step({}), 1, graphIndex, present);
+ expect(motion.type).toBe("linear");
+ });
+
+ it("keeps the base step still", () => {
+ expect(displayMotionForStep(step({}), 0, graphIndex, present)).toEqual({
+ type: "none"
+ });
+ });
+
+ it("passes stored motions through untouched", () => {
+ const stored: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 5
+ };
+ expect(
+ displayMotionForStep(step({ motion: stored }), 1, graphIndex, present)
+ ).toBe(stored);
+ });
+
+ it("only treats present components as obstacles", () => {
+ // "base" fully covers the region above "top"… here instead: a canopy leaf
+ // over "top" that is NOT in the present set must not redirect the fallback
+ const canopyIndex = indexAssemblyGraph({
+ ...graphIndex.graph,
+ root: {
+ ...graphIndex.graph.root,
+ children: [
+ ...graphIndex.graph.root.children,
+ {
+ nodeId: "canopy",
+ name: "canopy",
+ isAssembly: false,
+ geometryHash: "hash-canopy",
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 30], max: [50, 50, 40] },
+ volume: 1000,
+ color: null,
+ children: []
+ }
+ ]
+ }
+ });
+ const motion = displayMotionForStep(step({}), 1, canopyIndex, present);
+ // Insertion still approaches from above: the absent canopy doesn't block
+ if (motion.type !== "linear") throw new Error("expected linear");
+ expect(motion.direction[2]).toBe(-1);
+ });
+});
+
+describe("motionToWaypoints / waypointsToMotion", () => {
+ const seated: Vec3 = [10, 5, -2];
+
+ function expectVec3Close(actual: Vec3, expected: Vec3) {
+ actual.forEach((value, index) => {
+ expect(value).toBeCloseTo(expected[index] ?? Number.NaN, 6);
+ });
+ }
+
+ it("samples a linear motion to a start + seated waypoint", () => {
+ const motion: Motion = {
+ type: "linear",
+ direction: [0, 1, 0],
+ distance: 20
+ };
+ const waypoints = motionToWaypoints(motion, seated);
+ expect(waypoints).toHaveLength(2);
+ expectVec3Close(waypoints[0]!, [10, -15, -2]); // seated - dir*distance
+ expectVec3Close(waypoints[1]!, seated); // last === seated
+ });
+
+ it("round-trips a linear motion exactly", () => {
+ const motion: Motion = {
+ type: "linear",
+ direction: [0, 0, 1],
+ distance: 12
+ };
+ const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
+ expect(back.type).toBe("linear");
+ if (back.type === "linear") {
+ expectVec3Close(back.direction, [0, 0, 1]);
+ expect(back.distance).toBeCloseTo(12, 6);
+ }
+ });
+
+ it("round-trips an L motion, preserving segment order and directions", () => {
+ const motion: Motion = {
+ type: "L",
+ segments: [
+ { direction: [1, 0, 0], distance: 8 },
+ { direction: [0, 1, 0], distance: 5 }
+ ]
+ };
+ const back = waypointsToMotion(motionToWaypoints(motion, seated), seated);
+ expect(back.type).toBe("L");
+ if (back.type === "L") {
+ expect(back.segments).toHaveLength(2);
+ expectVec3Close(back.segments[0]!.direction, [1, 0, 0]);
+ expect(back.segments[0]!.distance).toBeCloseTo(8, 6);
+ expectVec3Close(back.segments[1]!.direction, [0, 1, 0]);
+ expect(back.segments[1]!.distance).toBeCloseTo(5, 6);
+ }
+ });
+
+ it("forces the last waypoint to the seated position", () => {
+ const back = waypointsToMotion(
+ [
+ [0, 0, 0],
+ [99, 99, 99]
+ ],
+ seated
+ );
+ // The seated end is pinned, so travel is start -> seated.
+ expect(back.type).toBe("linear");
+ if (back.type === "linear") {
+ expect(back.distance).toBeCloseTo(
+ Math.hypot(seated[0], seated[1], seated[2]),
+ 6
+ );
+ }
+ });
+
+ it("synthesizes a default straight path for a none motion", () => {
+ const waypoints = motionToWaypoints({ type: "none" }, seated);
+ expect(waypoints).toHaveLength(2);
+ expectVec3Close(waypoints[0]!, [
+ seated[0],
+ seated[1] + DEFAULT_WAYPOINT_DISTANCE,
+ seated[2]
+ ]);
+ expectVec3Close(waypoints[1]!, seated);
+ });
+
+ it("collapses degenerate (coincident) waypoints to none", () => {
+ expect(waypointsToMotion([seated, seated], seated)).toEqual({
+ type: "none"
+ });
+ });
+
+ it("drops a zero-length middle segment (3 pts, collinear) to linear", () => {
+ const back = waypointsToMotion([[0, 0, 0], [0, 0, 0], seated], seated);
+ expect(back.type).toBe("linear");
+ });
+});
diff --git a/packages/viewer/src/motion.ts b/packages/viewer/src/motion.ts
new file mode 100644
index 0000000000..0882fd457f
--- /dev/null
+++ b/packages/viewer/src/motion.ts
@@ -0,0 +1,595 @@
+import {
+ AnimationClip,
+ Matrix4,
+ type Object3D,
+ Quaternion,
+ QuaternionKeyframeTrack,
+ Vector3,
+ VectorKeyframeTrack
+} from "three";
+import { synthesizeFallbackMotion } from "./fallback";
+import type { AssemblyGraphIndex } from "./graph";
+import type { AssemblyStep, Motion, Quat, Vec3 } from "./types";
+
+/**
+ * Pure keyframe construction for step motions. No WebGL — everything here is
+ * unit-testable in node.
+ *
+ * Motion JSON describes the INSERTION of a component: keyframes start at the
+ * displaced (pre-insertion) pose and end at the component's final (seated) pose.
+ * All poses produced by `motionToKeyframes` are world-space; `buildStepClip`
+ * converts them into each node's parent-local space for animation.
+ */
+
+/** A world-space pose: position + quaternion ([x, y, z, w]) */
+export type Pose = {
+ position: Vec3;
+ quaternion: Quat;
+};
+
+export type MotionKeyframes = {
+ /** Seconds, monotonically non-decreasing, starting at 0 */
+ times: number[];
+ /** Flat [x, y, z] per keyframe, world space */
+ positions: number[];
+ /** Flat [x, y, z, w] per keyframe, world space */
+ quaternions: number[];
+};
+
+export type MotionKeyframeOptions = {
+ /** Total animation duration in seconds. Defaults to `motionDuration(motion)`. */
+ duration?: number;
+ /** Helix sampling density (quaternion slerp needs <180° between samples). */
+ samplesPerTurn?: number;
+};
+
+export type StepClipOptions = MotionKeyframeOptions & {
+ /** Seconds to hold the seated pose at the end of each loop. */
+ holdSeconds?: number;
+};
+
+const INSERTION_SPEED_MM_PER_S = 60;
+const MIN_DURATION_S = 1;
+const MAX_DURATION_S = 4;
+const DEFAULT_SAMPLES_PER_TURN = 4;
+export const DEFAULT_HOLD_SECONDS = 0.6;
+/** Coincident-waypoint threshold (mm) and the fallback travel for `none`. */
+const WAYPOINT_EPSILON = 1e-3;
+export const DEFAULT_WAYPOINT_DISTANCE = 50;
+/** Timeline length of a process-only (none-motion) step without an explicit duration */
+const NONE_STEP_SECONDS = 2;
+
+/**
+ * Seconds a step occupies on the continuous timeline: the explicit
+ * `durationSeconds` override when set, otherwise the natural animation
+ * length (motion duration + seated hold), or a fixed slot for process-only
+ * steps.
+ */
+export function stepTimelineSeconds(
+ step: Pick<AssemblyStep, "motion" | "durationSeconds">
+): number {
+ if (step.durationSeconds && step.durationSeconds > 0) {
+ return step.durationSeconds;
+ }
+ if (step.motion.type === "none") return NONE_STEP_SECONDS;
+ return motionDuration(step.motion) + DEFAULT_HOLD_SECONDS;
+}
+
+/** Total travel distance (mm) implied by a motion. */
+export function motionTravelDistance(motion: Motion): number {
+ switch (motion.type) {
+ case "linear":
+ return Math.abs(motion.distance);
+ case "L":
+ return motion.segments.reduce(
+ (sum, segment) => sum + Math.abs(segment.distance),
+ 0
+ );
+ case "helix":
+ return Math.abs(motion.approach) + Math.abs(motion.pitch * motion.turns);
+ case "path": {
+ let total = 0;
+ for (let i = 1; i < motion.keyframes.length; i++) {
+ const current = motion.keyframes[i];
+ const previous = motion.keyframes[i - 1];
+ if (!current || !previous) continue;
+ total += toVector3(current.position).distanceTo(
+ toVector3(previous.position)
+ );
+ }
+ return total;
+ }
+ case "none":
+ return 0;
+ }
+}
+
+/** Animation duration (s) scaled to travel distance, clamped to 1–4 s. */
+export function motionDuration(motion: Motion): number {
+ if (motion.type === "none") return 0;
+ const travel = motionTravelDistance(motion);
+ return Math.min(
+ MAX_DURATION_S,
+ Math.max(MIN_DURATION_S, travel / INSERTION_SPEED_MM_PER_S)
+ );
+}
+
+/**
+ * The motion a step should display. Flagged steps (the planner proved no
+ * collision-free path exists) keep motion "none" — the player fades their
+ * components in at the seated pose rather than animating a fabricated
+ * fly-through. Other non-first steps stored with "none" (legacy plans,
+ * manually authored steps) get the AABB fallback so components never pop into
+ * place; the fallback's obstacle world is `presentNodeIds`, the components
+ * already installed by EARLIER steps — later-step and never-installed
+ * components are not on the canvas. When no collision-free fallback exists the
+ * step keeps "none" and fades in. The first step is the base: placed, not
+ * inserted.
+ */
+export function displayMotionForStep(
+ step: Pick<AssemblyStep, "motion" | "componentNodeIds" | "flagged">,
+ index: number,
+ graphIndex: AssemblyGraphIndex | null,
+ presentNodeIds: ReadonlySet<string>
+): Motion {
+ if (
+ index === 0 ||
+ step.flagged ||
+ step.motion.type !== "none" ||
+ step.componentNodeIds.length === 0 ||
+ !graphIndex
+ ) {
+ return step.motion;
+ }
+ const fallback = synthesizeFallbackMotion(
+ graphIndex,
+ step.componentNodeIds,
+ presentNodeIds
+ );
+ return fallback && fallback.type !== "none" ? fallback : step.motion;
+}
+
+/** Components smaller than this fraction of the assembly count as "small". */
+const SMALL_COMPONENT_FRACTION = 0.15;
+/** Small components travel at least this many times their own size. */
+const SMALL_COMPONENT_TRAVEL_FACTOR = 2.5;
+
+/**
+ * Exaggerates the travel of small components (bolts, washers, pins) so their
+ * insertion reads clearly at assembly scale. Display-only: the stored plan
+ * keeps the geometric travel. Returns the motion unchanged for large components
+ * or non-translating motions.
+ */
+export function exaggerateMotion(
+ motion: Motion,
+ componentDiagonal: number,
+ assemblyDiagonal: number
+): Motion {
+ if (componentDiagonal <= 0 || assemblyDiagonal <= 0) return motion;
+ if (componentDiagonal >= assemblyDiagonal * SMALL_COMPONENT_FRACTION)
+ return motion;
+
+ const minTravel = componentDiagonal * SMALL_COMPONENT_TRAVEL_FACTOR;
+
+ switch (motion.type) {
+ case "linear": {
+ if (motion.distance >= minTravel) return motion;
+ return { ...motion, distance: minTravel };
+ }
+ case "L": {
+ const total = motion.segments.reduce(
+ (sum, segment) => sum + Math.abs(segment.distance),
+ 0
+ );
+ if (total >= minTravel || total <= 0) return motion;
+ const scale = minTravel / total;
+ return {
+ ...motion,
+ segments: motion.segments.map((segment) => ({
+ ...segment,
+ distance: segment.distance * scale
+ }))
+ };
+ }
+ default:
+ return motion;
+ }
+}
+
+/**
+ * Builds world-space insertion keyframes for a component whose final (seated)
+ * world pose is `basePose`. The last keyframe always equals `basePose`.
+ * Returns `null` for `none` motions.
+ */
+export function motionToKeyframes(
+ motion: Motion,
+ basePose: Pose,
+ options: MotionKeyframeOptions = {}
+): MotionKeyframes | null {
+ const duration = options.duration ?? motionDuration(motion);
+ const finalPosition = toVector3(basePose.position);
+ const finalQuaternion = toQuaternion(basePose.quaternion);
+
+ switch (motion.type) {
+ case "none":
+ return null;
+
+ case "linear": {
+ const direction = toVector3(motion.direction).normalize();
+ const start = finalPosition
+ .clone()
+ .addScaledVector(direction, -motion.distance);
+ return fromPoses(
+ [0, duration],
+ [
+ { position: start, quaternion: finalQuaternion },
+ { position: finalPosition, quaternion: finalQuaternion }
+ ]
+ );
+ }
+
+ case "L": {
+ // Walk backwards from the final pose through the segments (insertion
+ // order means the last segment ends at the final pose).
+ const positions: Vector3[] = [finalPosition.clone()];
+ for (let i = motion.segments.length - 1; i >= 0; i--) {
+ const segment = motion.segments[i];
+ const previous = positions[0];
+ if (!segment || !previous) continue;
+ const direction = toVector3(segment.direction).normalize();
+ positions.unshift(
+ previous.clone().addScaledVector(direction, -segment.distance)
+ );
+ }
+ const distances = motion.segments.map((s) => Math.abs(s.distance));
+ const total = distances.reduce((sum, d) => sum + d, 0);
+ const times: number[] = [0];
+ let elapsed = 0;
+ for (const distance of distances) {
+ elapsed += total > 0 ? (distance / total) * duration : 0;
+ times.push(elapsed);
+ }
+ if (total === 0) times[times.length - 1] = duration;
+ return fromPoses(
+ times,
+ positions.map((position) => ({
+ position,
+ quaternion: finalQuaternion
+ }))
+ );
+ }
+
+ case "helix": {
+ const axis = toVector3(motion.axis).normalize();
+ const origin = toVector3(motion.origin);
+ const samplesPerTurn = options.samplesPerTurn ?? DEFAULT_SAMPLES_PER_TURN;
+ const totalAngle = Math.PI * 2 * motion.turns;
+ const threadAdvance = motion.pitch * motion.turns;
+ const threadSamples = Math.max(
+ 1,
+ Math.ceil(motion.turns * samplesPerTurn)
+ );
+
+ // Pose at the given remaining (un-inserted) thread fraction. r = 1 is
+ // the start of threading, r = 0 is seated. The screw transform rotates
+ // the final pose backwards about `axis` through `origin` and retracts
+ // it along the axis.
+ const threadPoseAt = (
+ r: number
+ ): { position: Vector3; quaternion: Quaternion } => {
+ const unscrew = new Quaternion().setFromAxisAngle(
+ axis,
+ -totalAngle * r
+ );
+ const position = finalPosition
+ .clone()
+ .sub(origin)
+ .applyQuaternion(unscrew)
+ .add(origin)
+ .addScaledVector(axis, -threadAdvance * r);
+ const quaternion = unscrew.clone().multiply(finalQuaternion);
+ return { position, quaternion };
+ };
+
+ const approachWeight = Math.abs(motion.approach);
+ const threadWeight =
+ Math.abs(threadAdvance) > 0
+ ? Math.abs(threadAdvance)
+ : motion.turns > 0
+ ? 1
+ : 0;
+ const totalWeight = approachWeight + threadWeight;
+ const approachTime =
+ totalWeight > 0 ? (approachWeight / totalWeight) * duration : 0;
+
+ const times: number[] = [];
+ const poses: { position: Vector3; quaternion: Quaternion }[] = [];
+
+ const threadStart = threadPoseAt(1);
+ if (motion.approach !== 0) {
+ times.push(0);
+ poses.push({
+ position: threadStart.position
+ .clone()
+ .addScaledVector(axis, -motion.approach),
+ quaternion: threadStart.quaternion
+ });
+ }
+ times.push(approachTime);
+ poses.push(threadStart);
+ for (let i = 1; i <= threadSamples; i++) {
+ const progress = i / threadSamples;
+ times.push(approachTime + (duration - approachTime) * progress);
+ poses.push(threadPoseAt(1 - progress));
+ }
+ return fromPoses(times, poses);
+ }
+
+ case "path": {
+ const keyframes = motion.keyframes;
+ const first = keyframes[0];
+ const last = keyframes[keyframes.length - 1];
+ if (keyframes.length < 2 || !first || !last) {
+ throw new Error("path motion requires at least 2 keyframes");
+ }
+ for (let i = 1; i < keyframes.length; i++) {
+ const current = keyframes[i];
+ const previous = keyframes[i - 1];
+ if (!current || !previous) continue;
+ if (current.t <= previous.t) {
+ throw new Error(
+ "path motion keyframe times must be strictly increasing"
+ );
+ }
+ }
+ if (first.t !== 0 || last.t !== 1) {
+ throw new Error("path motion keyframes must span t = 0 to t = 1");
+ }
+ const epsilon = 1e-3;
+ if (
+ toVector3(last.position).distanceTo(finalPosition) > epsilon ||
+ Math.abs(toQuaternion(last.quaternion).dot(finalQuaternion)) <
+ 1 - epsilon
+ ) {
+ throw new Error(
+ "path motion's last keyframe must equal the component's final pose"
+ );
+ }
+ return fromPoses(
+ keyframes.map((keyframe) => keyframe.t * duration),
+ keyframes.map((keyframe) => ({
+ position: toVector3(keyframe.position),
+ quaternion: toQuaternion(keyframe.quaternion)
+ }))
+ );
+ }
+ }
+}
+
+/**
+ * Builds a looping insertion AnimationClip for one step, with position and
+ * quaternion tracks for each of the step's components. Tracks are bound by node
+ * uuid so duplicate node names cannot collide. World-space keyframes are
+ * converted into each node's parent-local space, so nested assembly
+ * transforms are respected. Nodes are assumed to currently sit at their
+ * final (seated) pose.
+ *
+ * Returns `null` for `none` motions or when no component resolves to a node.
+ */
+export function buildStepClip(
+ step: AssemblyStep,
+ nodesById: Map<string, Object3D>,
+ options: StepClipOptions = {}
+): AnimationClip | null {
+ if (step.motion.type === "none" || step.componentNodeIds.length === 0) {
+ return null;
+ }
+
+ const duration = options.duration ?? motionDuration(step.motion);
+ const holdSeconds = options.holdSeconds ?? DEFAULT_HOLD_SECONDS;
+ const tracks: (VectorKeyframeTrack | QuaternionKeyframeTrack)[] = [];
+
+ for (const nodeId of step.componentNodeIds) {
+ const node = nodesById.get(nodeId);
+ if (!node) continue;
+
+ node.updateWorldMatrix(true, false);
+ const worldPosition = new Vector3();
+ const worldQuaternion = new Quaternion();
+ const worldScale = new Vector3();
+ node.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
+
+ const keyframes = motionToKeyframes(
+ step.motion,
+ {
+ position: worldPosition.toArray() as Vec3,
+ quaternion: toQuat(worldQuaternion)
+ },
+ { ...options, duration }
+ );
+ if (!keyframes) continue;
+
+ const parentWorldInverse = node.parent
+ ? node.parent.matrixWorld.clone().invert()
+ : new Matrix4();
+
+ const times: number[] = [];
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ const worldMatrix = new Matrix4();
+ const localMatrix = new Matrix4();
+ const localPosition = new Vector3();
+ const localQuaternion = new Quaternion();
+ const localScale = new Vector3();
+
+ const frameCount = keyframes.times.length;
+ for (let i = 0; i < frameCount; i++) {
+ const time = keyframes.times[i];
+ if (time === undefined) continue;
+ const position = new Vector3().fromArray(keyframes.positions, i * 3);
+ const quaternion = new Quaternion().fromArray(
+ keyframes.quaternions,
+ i * 4
+ );
+ worldMatrix.compose(position, quaternion, worldScale);
+ localMatrix.multiplyMatrices(parentWorldInverse, worldMatrix);
+ localMatrix.decompose(localPosition, localQuaternion, localScale);
+ times.push(time);
+ positions.push(localPosition.x, localPosition.y, localPosition.z);
+ quaternions.push(
+ localQuaternion.x,
+ localQuaternion.y,
+ localQuaternion.z,
+ localQuaternion.w
+ );
+ }
+
+ // Hold the seated pose so LoopRepeat pauses before restarting.
+ const lastTime = times[times.length - 1];
+ if (holdSeconds > 0 && lastTime !== undefined) {
+ times.push(lastTime + holdSeconds);
+ positions.push(...positions.slice(-3));
+ quaternions.push(...quaternions.slice(-4));
+ }
+
+ tracks.push(
+ new VectorKeyframeTrack(`${node.uuid}.position`, times, positions),
+ new QuaternionKeyframeTrack(`${node.uuid}.quaternion`, times, quaternions)
+ );
+ }
+
+ if (tracks.length === 0) return null;
+ return new AnimationClip(`step:${step.id}`, duration + holdSeconds, tracks);
+}
+
+/**
+ * World-space waypoints describing a step's insertion travel, for the visual
+ * path editor. The LAST waypoint is the seated reference position; earlier
+ * waypoints are where the component(s) travel FROM. Relative motions
+ * (linear/L/helix) are anchored to `seatedPosition`; a `path` motion's absolute
+ * keyframe positions are used directly. `none` — or any motion that can't be
+ * sampled — yields a straight default offset so there is always a path to drag.
+ *
+ * For a multi-component (rigid group) step, pass the centroid of the components' seated
+ * positions: the shared relative motion renders as one path anchored there.
+ */
+export function motionToWaypoints(
+ motion: Motion,
+ seatedPosition: Vec3,
+ options: { defaultDistance?: number } = {}
+): Vec3[] {
+ if (motion.type !== "none") {
+ try {
+ const keyframes = motionToKeyframes(motion, {
+ position: seatedPosition,
+ quaternion: [0, 0, 0, 1]
+ });
+ if (keyframes) {
+ const points = dedupePositions(keyframes.positions);
+ if (points.length >= 2) return points;
+ }
+ } catch {
+ // Unsamplable (e.g. an absolute path whose seated pose differs) — fall
+ // through to the default straight offset below.
+ }
+ }
+ const distance =
+ options.defaultDistance && options.defaultDistance > 0
+ ? options.defaultDistance
+ : DEFAULT_WAYPOINT_DISTANCE;
+ const start = toVector3(seatedPosition).add(new Vector3(0, distance, 0));
+ return [start.toArray() as Vec3, seatedPosition];
+}
+
+/**
+ * Converts dragged world-space waypoints back into a RELATIVE motion — 2
+ * waypoints → `linear`, 3+ → `L` (multi-segment). Relative (not absolute
+ * `path`) so it applies to every component in a rigid-group step. Pure translation:
+ * components keep their seated orientation. The last waypoint is forced to the
+ * seated position; zero-length segments are dropped; degenerate input collapses
+ * to `none`. Directions/distances match `motionToKeyframes`' reconstruction, so
+ * `motionToWaypoints` → `waypointsToMotion` round-trips exactly for linear/L.
+ */
+export function waypointsToMotion(
+ waypoints: Vec3[],
+ seatedPosition: Vec3
+): Motion {
+ const points = waypoints.map(toVector3);
+ if (points.length > 0) points[points.length - 1] = toVector3(seatedPosition);
+
+ const segments: { direction: Vec3; distance: number }[] = [];
+ for (let i = 1; i < points.length; i++) {
+ const from = points[i - 1];
+ const to = points[i];
+ if (!from || !to) continue;
+ const delta = to.clone().sub(from);
+ const distance = delta.length();
+ if (distance < WAYPOINT_EPSILON) continue;
+ segments.push({
+ direction: delta.divideScalar(distance).toArray() as Vec3,
+ distance
+ });
+ }
+
+ const first = segments[0];
+ if (!first) return { type: "none" };
+ if (segments.length === 1) {
+ return {
+ type: "linear",
+ direction: first.direction,
+ distance: first.distance
+ };
+ }
+ return { type: "L", segments };
+}
+
+/** Flat [x,y,z,…] → Vec3[], dropping consecutive coincident points. */
+function dedupePositions(flat: number[]): Vec3[] {
+ const points: Vec3[] = [];
+ for (let i = 0; i + 2 < flat.length; i += 3) {
+ const point: Vec3 = [flat[i] ?? 0, flat[i + 1] ?? 0, flat[i + 2] ?? 0];
+ const previous = points[points.length - 1];
+ if (
+ previous &&
+ Math.hypot(
+ point[0] - previous[0],
+ point[1] - previous[1],
+ point[2] - previous[2]
+ ) < WAYPOINT_EPSILON
+ ) {
+ continue;
+ }
+ points.push(point);
+ }
+ return points;
+}
+
+function toVector3(value: Vec3): Vector3 {
+ return new Vector3(value[0], value[1], value[2]);
+}
+
+function toQuaternion(value: Quat): Quaternion {
+ return new Quaternion(value[0], value[1], value[2], value[3]).normalize();
+}
+
+function toQuat(quaternion: Quaternion): Quat {
+ return [quaternion.x, quaternion.y, quaternion.z, quaternion.w];
+}
+
+function fromPoses(
+ times: number[],
+ poses: { position: Vector3; quaternion: Quaternion }[]
+): MotionKeyframes {
+ const positions: number[] = [];
+ const quaternions: number[] = [];
+ for (const pose of poses) {
+ positions.push(pose.position.x, pose.position.y, pose.position.z);
+ quaternions.push(
+ pose.quaternion.x,
+ pose.quaternion.y,
+ pose.quaternion.z,
+ pose.quaternion.w
+ );
+ }
+ return { times, positions, quaternions };
+}
diff --git a/packages/viewer/src/plan.test.ts b/packages/viewer/src/plan.test.ts
new file mode 100644
index 0000000000..d64ec99ed2
--- /dev/null
+++ b/packages/viewer/src/plan.test.ts
@@ -0,0 +1,451 @@
+import { describe, expect, it } from "vitest";
+import { indexAssemblyGraph } from "./graph";
+import type { AssemblyPlan } from "./plan";
+import { buildAssemblyStepGroups, planMotionForComponents } from "./plan";
+import type { AssemblyGraph, AssemblyGraphNode, Motion, Vec3 } from "./types";
+
+const lift: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 25
+};
+
+const slide: Motion = {
+ type: "linear",
+ direction: [-1, 0, 0],
+ distance: 80
+};
+
+const plan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["base", "bolt-1", "bolt-2", "cover"],
+ components: {
+ base: { motion: { type: "none" } },
+ "bolt-1": { motion: lift, confidence: "high" },
+ "bolt-2": { motion: lift, confidence: "high" },
+ cover: { motion: slide, confidence: "low" }
+ },
+ warnings: []
+};
+
+describe("planMotionForComponents", () => {
+ it("uses the component's own motion for a single component", () => {
+ expect(planMotionForComponents(plan, ["bolt-1"])).toEqual({
+ motion: lift,
+ confidence: "high"
+ });
+ });
+
+ it("uses the shared motion when all components agree", () => {
+ expect(planMotionForComponents(plan, ["bolt-1", "bolt-2"])).toEqual({
+ motion: lift,
+ confidence: "high"
+ });
+ });
+
+ it("falls back to the first motion with low confidence on disagreement", () => {
+ expect(planMotionForComponents(plan, ["bolt-1", "cover"])).toEqual({
+ motion: lift,
+ confidence: "low"
+ });
+ });
+
+ it("returns null for unplanned or unknown components", () => {
+ expect(planMotionForComponents(plan, ["base"])).toBeNull();
+ expect(planMotionForComponents(plan, ["missing"])).toBeNull();
+ expect(planMotionForComponents(plan, [])).toBeNull();
+ expect(planMotionForComponents(null, ["bolt-1"])).toBeNull();
+ });
+});
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+function graphLeaf(
+ nodeId: string,
+ bbox: { min: Vec3; max: Vec3 },
+ geometryHash = `hash-${nodeId}`
+): AssemblyGraphNode {
+ return {
+ nodeId,
+ name: nodeId,
+ isAssembly: false,
+ geometryHash,
+ transform: IDENTITY,
+ bbox,
+ volume: 1000,
+ color: null,
+ children: []
+ };
+}
+
+function graphOf(leaves: AssemblyGraphNode[]): AssemblyGraph {
+ return {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ componentCount: leaves.length,
+ root: {
+ nodeId: "root",
+ name: "Assembly",
+ isAssembly: true,
+ geometryHash: null,
+ transform: IDENTITY,
+ bbox: { min: [-50, -50, 0], max: [50, 50, 40] },
+ volume: null,
+ color: null,
+ children: leaves
+ }
+ };
+}
+
+describe("buildAssemblyStepGroups", () => {
+ const graphIndex = indexAssemblyGraph(
+ graphOf([
+ graphLeaf("base", { min: [-50, -50, 0], max: [50, 50, 10] }),
+ graphLeaf(
+ "bolt-1",
+ { min: [-30, -30, 10], max: [-20, -20, 30] },
+ "hash-bolt"
+ ),
+ graphLeaf(
+ "bolt-2",
+ { min: [20, 20, 10], max: [30, 30, 30] },
+ "hash-bolt"
+ ),
+ graphLeaf("cover", { min: [-10, -10, 30], max: [10, 10, 40] })
+ ])
+ );
+
+ it("walks the sequence, merging consecutive identical components with the longest travel", () => {
+ const stepPlan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["base", "bolt-1", "bolt-2"],
+ components: {
+ base: { motion: { type: "none" } },
+ "bolt-1": {
+ motion: { type: "linear", direction: [0, 0, -1], distance: 20 },
+ confidence: "high"
+ },
+ "bolt-2": {
+ motion: { type: "linear", direction: [0, 0, -1], distance: 25 },
+ confidence: "high"
+ }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(stepPlan, graphIndex);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0]?.componentNodeIds).toEqual(["base"]);
+ expect(groups[0]?.motion).toEqual({ type: "none" });
+ expect(groups[1]?.componentNodeIds).toEqual(["bolt-1", "bolt-2"]);
+ expect(groups[1]?.motion).toEqual({
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 25
+ });
+ expect(groups[1]?.confidence).toBe("high");
+ expect(groups[1]?.blockedBy).toEqual([]);
+ });
+
+ it("drops fabricated motions on flagged components and never synthesizes a fallback for them", () => {
+ const fabricated: Motion = {
+ type: "linear",
+ direction: [1, 0, 0],
+ distance: 640
+ };
+ const stepPlan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["base", "bolt-1", "bolt-2"],
+ components: {
+ base: { motion: { type: "none" } },
+ "bolt-1": {
+ motion: fabricated,
+ confidence: "low",
+ blockedBy: ["base"]
+ },
+ "bolt-2": {
+ motion: fabricated,
+ confidence: "low",
+ blockedBy: ["cover"]
+ }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(stepPlan, graphIndex);
+
+ expect(groups).toHaveLength(2);
+ const flagged = groups[1];
+ // Identical flagged twins share a step; their blockers merge
+ expect(flagged?.componentNodeIds).toEqual(["bolt-1", "bolt-2"]);
+ expect(flagged?.motion).toEqual({ type: "none" });
+ expect(flagged?.blockedBy).toEqual(["base", "cover"]);
+ expect(flagged?.confidence).toBe("low");
+ });
+
+ it("keeps flagged and unflagged twins in separate steps", () => {
+ const stepPlan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["bolt-1", "bolt-2"],
+ components: {
+ "bolt-1": {
+ motion: { type: "linear", direction: [0, 0, -1], distance: 20 },
+ confidence: "high"
+ },
+ "bolt-2": {
+ motion: { type: "linear", direction: [0, 0, -1], distance: 20 },
+ confidence: "low",
+ blockedBy: ["base"]
+ }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(stepPlan, graphIndex);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0]?.blockedBy).toEqual([]);
+ expect(groups[1]?.componentNodeIds).toEqual(["bolt-2"]);
+ expect(groups[1]?.motion).toEqual({ type: "none" });
+ });
+
+ it("folds a v3 unit's members into one named step", () => {
+ const stepPlan: AssemblyPlan = {
+ version: 3,
+ unit: "mm",
+ sequence: ["pcb-a", "pcb-b"],
+ components: {
+ "pcb-a": {
+ motion: { type: "linear", direction: [0, 0, 1], distance: 30 },
+ confidence: "high",
+ groupId: "pcb"
+ },
+ "pcb-b": {
+ motion: { type: "linear", direction: [0, 0, 1], distance: 30 },
+ confidence: "high",
+ groupId: "pcb"
+ }
+ },
+ groups: {
+ pcb: {
+ componentNodeIds: ["pcb-a", "pcb-b"],
+ motion: { type: "linear", direction: [0, 0, 1], distance: 30 },
+ name: "PCB Assembly"
+ }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(stepPlan, graphIndex);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.componentNodeIds).toEqual(["pcb-a", "pcb-b"]);
+ expect(groups[0]?.name).toBe("PCB Assembly");
+ });
+
+ it("synthesizes an AABB fallback for unflagged none-motion components, but never the base", () => {
+ const stepPlan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["base", "cover"],
+ components: {
+ base: { motion: { type: "none" } },
+ // Legacy plan: unplanned but not flagged
+ cover: { motion: { type: "none" } }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(stepPlan, graphIndex);
+
+ expect(groups[0]?.motion).toEqual({ type: "none" });
+ expect(groups[1]?.motion.type).toBe("linear");
+ expect(groups[1]?.confidence).toBe("low");
+ });
+});
+
+describe("buildAssemblyStepGroups v2", () => {
+ const graphIndex = indexAssemblyGraph(
+ graphOf([
+ graphLeaf("rail", { min: [-100, -10, 0], max: [100, 10, 20] }),
+ graphLeaf("slider", { min: [-20, -12, 20], max: [20, 12, 40] }),
+ graphLeaf("knob", { min: [-5, 12, 25], max: [5, 22, 35] }),
+ graphLeaf("logo", { min: [-8, -1, 30], max: [8, 1, 34] })
+ ])
+ );
+
+ it("keeps subassembly members in one step regardless of geometry", () => {
+ const slide: Motion = {
+ type: "linear",
+ direction: [-1, 0, 0],
+ distance: 120
+ };
+ const v2: AssemblyPlan = {
+ version: 2,
+ unit: "mm",
+ sequence: ["rail", "slider", "knob"],
+ components: {
+ rail: { motion: { type: "none" }, tier: "base", verified: true },
+ slider: {
+ motion: slide,
+ confidence: "low",
+ tier: "group",
+ groupId: "g1",
+ verified: true
+ },
+ knob: {
+ motion: slide,
+ confidence: "low",
+ tier: "group",
+ groupId: "g1",
+ verified: true
+ }
+ },
+ groups: { g1: { componentNodeIds: ["slider", "knob"], motion: slide } },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(v2, graphIndex);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[1]?.componentNodeIds).toEqual(["slider", "knob"]);
+ expect(groups[1]?.motion).toEqual(slide);
+ });
+
+ it("folds rigidly merged components into their host's step", () => {
+ const lift: Motion = {
+ type: "linear",
+ direction: [0, 0, -1],
+ distance: 40
+ };
+ const v2: AssemblyPlan = {
+ version: 2,
+ unit: "mm",
+ sequence: ["rail", "slider"],
+ components: {
+ rail: { motion: { type: "none" }, tier: "base", verified: true },
+ slider: { motion: lift, confidence: "high", verified: true },
+ logo: { motion: { type: "none" }, mergedInto: "slider" }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(v2, graphIndex);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[1]?.componentNodeIds).toEqual(["slider", "logo"]);
+ expect(groups[1]?.motion).toEqual(lift);
+ });
+
+ it("treats verification failures as flagged", () => {
+ const v2: AssemblyPlan = {
+ version: 2,
+ unit: "mm",
+ sequence: ["rail", "slider"],
+ components: {
+ rail: { motion: { type: "none" }, tier: "base", verified: true },
+ slider: {
+ motion: { type: "linear", direction: [0, 0, -1], distance: 40 },
+ confidence: "high",
+ verified: false,
+ blockedBy: ["rail"]
+ }
+ },
+ warnings: []
+ };
+
+ const groups = buildAssemblyStepGroups(v2, graphIndex);
+
+ expect(groups[1]?.motion).toEqual({ type: "none" });
+ expect(groups[1]?.blockedBy).toEqual(["rail"]);
+ });
+});
+
+describe("corridor-aware simultaneous steps", () => {
+ // Four identical clips sliding along +X into a shared channel, seated
+ // one behind another: each clip's insertion corridor sweeps through the
+ // others' seats, so simultaneous animation would drive them through
+ // each other — every clip takes its own step.
+ const inlineSlide: Motion = {
+ type: "linear",
+ direction: [1, 0, 0],
+ distance: 60
+ };
+ const inlineGraph = indexAssemblyGraph(
+ graphOf(
+ [0, 1, 2, 3].map((index) =>
+ graphLeaf(
+ `clip-${index}`,
+ {
+ min: [index * 20, 0, 0],
+ max: [index * 20 + 15, 10, 10]
+ },
+ "hash-clip"
+ )
+ )
+ )
+ );
+ const inlinePlan: AssemblyPlan = {
+ version: 1,
+ unit: "mm",
+ sequence: ["clip-0", "clip-1", "clip-2", "clip-3"],
+ components: Object.fromEntries(
+ [0, 1, 2, 3].map((index) => [
+ `clip-${index}`,
+ { motion: inlineSlide, confidence: "high" as const }
+ ])
+ ),
+ warnings: []
+ };
+
+ it("splits in-line slide-ins into independent steps", () => {
+ const groups = buildAssemblyStepGroups(inlinePlan, inlineGraph);
+ expect(groups.map((group) => group.componentNodeIds)).toEqual([
+ ["clip-0"],
+ ["clip-1"],
+ ["clip-2"],
+ ["clip-3"]
+ ]);
+ });
+
+ it("keeps side-by-side same-direction components on one simultaneous step", () => {
+ // Same four clips, but seated side by side across Y: corridors are
+ // parallel and disjoint, simultaneous insertion is collision-free
+ const sideGraph = indexAssemblyGraph(
+ graphOf(
+ [0, 1, 2, 3].map((index) =>
+ graphLeaf(
+ `clip-${index}`,
+ {
+ min: [0, index * 20, 0],
+ max: [15, index * 20 + 10, 10]
+ },
+ "hash-clip"
+ )
+ )
+ )
+ );
+ const groups = buildAssemblyStepGroups(inlinePlan, sideGraph);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]?.componentNodeIds).toEqual([
+ "clip-0",
+ "clip-1",
+ "clip-2",
+ "clip-3"
+ ]);
+ });
+
+ it("never shares steps without a graph (hash falls back to nodeId)", () => {
+ // Pre-existing behavior, unchanged by the corridor gate: with no
+ // graph there is no geometryHash, so components can't be identified as
+ // identical in the first place
+ const groups = buildAssemblyStepGroups(inlinePlan, null);
+ expect(groups).toHaveLength(4);
+ });
+});
diff --git a/packages/viewer/src/plan.ts b/packages/viewer/src/plan.ts
new file mode 100644
index 0000000000..2efdf8715e
--- /dev/null
+++ b/packages/viewer/src/plan.ts
@@ -0,0 +1,318 @@
+import { synthesizeFallbackMotion } from "./fallback";
+import type { AssemblyGraphIndex } from "./graph";
+import type { Motion, Vec3 } from "./types";
+
+/**
+ * plan.json as written by the geometry service /plan endpoint (see
+ * docs/specs/animated-work-instructions-contracts.md). Keys join against
+ * graph.json nodeIds and GLB extras. Version 2 adds tiers, forward
+ * verification, subassembly groups, and rigid merges; all new fields are
+ * optional so version-1 files keep parsing.
+ */
+export type AssemblyPlanComponent = {
+ /** INSERTION motion (removal reversed) */
+ motion: Motion;
+ confidence?: "high" | "low";
+ removalDirection?: [number, number, number];
+ /** Obstructions for flagged components (no collision-free path exists) */
+ blockedBy?: string[];
+ /** v2: how the motion was found */
+ tier?: "linear" | "L" | "escape" | "group" | "flagged" | "base";
+ /** v2: insertion re-checked collision-free against its predecessors */
+ verified?: boolean;
+ /** v2: subassembly unit — members share one step and one motion */
+ groupId?: string;
+ /** v2: rigidly merged into this component (rides its step) */
+ mergedInto?: string;
+};
+
+/**
+ * The plan.json version the current planner writes. Stored plans below
+ * this are STALE — produced by an older algorithm — and consumers must
+ * treat them as absent so the pipeline re-plans instead of resurrecting
+ * old motions. Bump alongside the geometry service's PLAN_VERSION.
+ */
+export const CURRENT_PLAN_VERSION = 3;
+
+export type AssemblyPlan = {
+ version: 1 | 2 | 3;
+ unit: "mm";
+ /** Assembly order (constraint-consistent; v1: reversed greedy disassembly) */
+ sequence: string[];
+ components: Record<string, AssemblyPlanComponent>;
+ /**
+ * v2: subassembly units keyed by groupId. v3 adds `name` — a pre-grouped unit
+ * (e.g. a purchased PCB) carries its BOM/subassembly name for the step title.
+ */
+ groups?: Record<
+ string,
+ { componentNodeIds: string[]; motion: Motion; name?: string }
+ >;
+ warnings: string[];
+};
+
+export type PlannedMotion = {
+ motion: Motion;
+ confidence: "high" | "low";
+};
+
+/**
+ * The auto-planned motion for a step's components, per the contract: a single
+ * component uses its own motion; multiple components use the shared motion when all
+ * agree, otherwise the first component's motion with confidence low. Returns
+ * null when the plan has nothing useful for these components.
+ */
+export function planMotionForComponents(
+ plan: AssemblyPlan | null,
+ componentNodeIds: string[]
+): PlannedMotion | null {
+ if (!plan || componentNodeIds.length === 0) return null;
+
+ const entries = componentNodeIds
+ .map((nodeId) => plan.components[nodeId])
+ .filter(
+ (entry): entry is AssemblyPlanComponent =>
+ entry !== undefined && entry.motion.type !== "none"
+ );
+ if (entries.length === 0) return null;
+
+ const first = entries[0];
+ if (!first) return null;
+
+ if (entries.length === 1 && componentNodeIds.length === 1) {
+ return { motion: first.motion, confidence: first.confidence ?? "low" };
+ }
+
+ const firstKey = JSON.stringify(first.motion);
+ const allAgree =
+ entries.length === componentNodeIds.length &&
+ entries.every((entry) => JSON.stringify(entry.motion) === firstKey);
+
+ if (allAgree) {
+ const lowest = entries.some((entry) => entry.confidence !== "high")
+ ? "low"
+ : "high";
+ return { motion: first.motion, confidence: lowest };
+ }
+
+ return { motion: first.motion, confidence: "low" };
+}
+
+const MOTION_TYPES = new Set(["linear", "L", "helix", "path", "none"]);
+
+/** Structural guard for motions arriving from plan.json (untyped storage). */
+function isMotion(value: unknown): value is Motion {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ MOTION_TYPES.has((value as { type?: string }).type ?? "")
+ );
+}
+
+export type AssemblyStepGroup = {
+ componentNodeIds: string[];
+ motion: Motion;
+ confidence: "high" | "low";
+ /**
+ * Planner-recorded obstructions. Non-empty means the group is flagged: no
+ * collision-free path exists, the motion is "none", and the player fades
+ * the components in at their seated pose.
+ */
+ blockedBy: string[];
+ /** v3: the pre-grouped unit's name (e.g. "PCB Assembly"), for the step title. */
+ name?: string;
+};
+
+function motionKey(motion: Motion): string {
+ switch (motion.type) {
+ case "linear":
+ return `linear:${motion.direction.join(",")}`;
+ case "L":
+ return `L:${motion.segments
+ .map((segment) => segment.direction.join(","))
+ .join(";")}`;
+ default:
+ return motion.type;
+ }
+}
+
+type Aabb = { min: Vec3; max: Vec3 };
+
+/**
+ * Conservative swept volume of a component's insertion: the AABB of its seat
+ * pose union every pose along the motion (segment corners included). Two
+ * components whose corridors are AABB-disjoint cannot collide while animating
+ * simultaneously; overlapping corridors (e.g. clips sliding in-line into
+ * the same channel) must insert on separate steps.
+ */
+function motionCorridor(bbox: Aabb | undefined, motion: Motion): Aabb | null {
+ if (!bbox) return null;
+ const min: Vec3 = [bbox.min[0], bbox.min[1], bbox.min[2]];
+ const max: Vec3 = [bbox.max[0], bbox.max[1], bbox.max[2]];
+ const extend = (offset: Vec3) => {
+ min[0] = Math.min(min[0], bbox.min[0] + offset[0]);
+ min[1] = Math.min(min[1], bbox.min[1] + offset[1]);
+ min[2] = Math.min(min[2], bbox.min[2] + offset[2]);
+ max[0] = Math.max(max[0], bbox.max[0] + offset[0]);
+ max[1] = Math.max(max[1], bbox.max[1] + offset[1]);
+ max[2] = Math.max(max[2], bbox.max[2] + offset[2]);
+ };
+ if (motion.type === "linear") {
+ extend([
+ -motion.direction[0] * motion.distance,
+ -motion.direction[1] * motion.distance,
+ -motion.direction[2] * motion.distance
+ ]);
+ return { min, max };
+ }
+ if (motion.type === "L") {
+ // Insertion plays the segments in order and ends at the seat, so the
+ // poses walk backward from the seat through each segment corner
+ let offset: Vec3 = [0, 0, 0];
+ for (let index = motion.segments.length - 1; index >= 0; index--) {
+ const segment = motion.segments[index];
+ if (!segment) continue;
+ offset = [
+ offset[0] - segment.direction[0] * segment.distance,
+ offset[1] - segment.direction[1] * segment.distance,
+ offset[2] - segment.direction[2] * segment.distance
+ ];
+ extend(offset);
+ }
+ return { min, max };
+ }
+ return null;
+}
+
+function corridorsOverlap(a: Aabb, b: Aabb): boolean {
+ return (
+ a.min[0] <= b.max[0] &&
+ b.min[0] <= a.max[0] &&
+ a.min[1] <= b.max[1] &&
+ b.min[1] <= a.max[1] &&
+ a.min[2] <= b.max[2] &&
+ b.min[2] <= a.max[2]
+ );
+}
+
+/**
+ * Groups a plan's assembly sequence into draft steps: consecutive identical
+ * components (same geometry, same motion direction, same flag state) share a
+ * step, keeping the longest travel so instances at different depths all
+ * reach their seat. Subassembly units (shared `groupId`) always share one
+ * step regardless of geometry, and rigidly merged components ride their host's
+ * step. Components the planner flagged via `blockedBy` (or that failed forward
+ * verification) get motion "none" — a fabricated path would animate
+ * straight through geometry. Unflagged components old plans left with motion
+ * "none" get an AABB fallback checked against earlier groups' components only
+ * (the parts on the canvas when the step plays); with no collision-free
+ * fallback they keep "none" and fade in. The first group is exempt (the base
+ * is placed, not inserted).
+ */
+export function buildAssemblyStepGroups(
+ plan: AssemblyPlan,
+ graphIndex: AssemblyGraphIndex | null
+): AssemblyStepGroup[] {
+ type WorkingGroup = AssemblyStepGroup & { key: string; corridors: Aabb[] };
+ const groups: WorkingGroup[] = [];
+
+ // Rigidly merged components (v2) are absent from the sequence: they install
+ // with their host, animating as one body
+ const mergedByHost = new Map<string, string[]>();
+ for (const [nodeId, component] of Object.entries(plan.components)) {
+ if (!component.mergedInto) continue;
+ const members = mergedByHost.get(component.mergedInto) ?? [];
+ members.push(nodeId);
+ mergedByHost.set(component.mergedInto, members);
+ }
+
+ for (const nodeId of plan.sequence) {
+ const component = plan.components[nodeId];
+ if (component?.mergedInto) continue; // defensive: hosts carry their merges
+ const blockedBy = component?.blockedBy ?? [];
+ const flagged = blockedBy.length > 0 || component?.verified === false;
+ const motion: Motion = flagged
+ ? { type: "none" }
+ : component && isMotion(component.motion)
+ ? component.motion
+ : { type: "none" };
+ const confidence: "high" | "low" =
+ !flagged && component?.confidence === "high" ? "high" : "low";
+ const hash = graphIndex?.nodesById.get(nodeId)?.geometryHash ?? nodeId;
+ // Subassembly members share a step no matter their geometry
+ const key = component?.groupId
+ ? `group:${component.groupId}`
+ : `${hash}|${motionKey(motion)}|${confidence}|${flagged}`;
+
+ const withMerged = [nodeId, ...(mergedByHost.get(nodeId) ?? [])];
+
+ // A step's components animate SIMULTANEOUSLY, which is only legitimate
+ // when their swept corridors can't intersect — side-by-side screws
+ // pass, clips sliding in-line into the same channel must each take
+ // their own step. Subassembly units are one rigid body and exempt.
+ const corridor = component?.groupId
+ ? null
+ : motionCorridor(graphIndex?.nodesById.get(nodeId)?.bbox, motion);
+
+ const previous = groups[groups.length - 1];
+ const corridorClear =
+ component?.groupId != null ||
+ corridor == null ||
+ previous == null ||
+ previous.corridors.every((other) => !corridorsOverlap(corridor, other));
+ if (previous && previous.key === key && corridorClear) {
+ previous.componentNodeIds.push(...withMerged);
+ if (corridor) {
+ previous.corridors.push(corridor);
+ }
+ for (const blocker of blockedBy) {
+ if (!previous.blockedBy.includes(blocker)) {
+ previous.blockedBy.push(blocker);
+ }
+ }
+ // Identical components can sit at different depths: animate the longest
+ if (motion.type === "linear" && previous.motion.type === "linear") {
+ previous.motion = {
+ ...previous.motion,
+ distance: Math.max(previous.motion.distance, motion.distance)
+ };
+ }
+ continue;
+ }
+ groups.push({
+ componentNodeIds: withMerged,
+ motion,
+ confidence,
+ blockedBy: [...blockedBy],
+ name: component?.groupId
+ ? plan.groups?.[component.groupId]?.name
+ : undefined,
+ key,
+ corridors: corridor ? [corridor] : []
+ });
+ }
+
+ if (graphIndex) {
+ // Fallbacks see only earlier groups' components — the parts on the canvas
+ // when the group's step plays
+ const present = new Set<string>(groups[0]?.componentNodeIds ?? []);
+ for (let index = 1; index < groups.length; index++) {
+ const group = groups[index];
+ if (!group) continue;
+ if (group.motion.type === "none" && group.blockedBy.length === 0) {
+ const fallback = synthesizeFallbackMotion(
+ graphIndex,
+ group.componentNodeIds,
+ present
+ );
+ if (fallback && fallback.type !== "none") {
+ group.motion = fallback;
+ group.confidence = "low";
+ }
+ }
+ for (const nodeId of group.componentNodeIds) present.add(nodeId);
+ }
+ }
+
+ return groups.map(({ key: _key, corridors: _corridors, ...group }) => group);
+}
diff --git a/packages/viewer/src/steps.ts b/packages/viewer/src/steps.ts
new file mode 100644
index 0000000000..b4e0f9b266
--- /dev/null
+++ b/packages/viewer/src/steps.ts
@@ -0,0 +1,12 @@
+/**
+ * Three-free entry point for the pure plan → step-group logic, so server code
+ * (the Inngest worker) can build assembly steps without pulling in the viewer's
+ * three.js/react rendering deps that the package barrel (index.ts) re-exports.
+ */
+import { indexAssemblyGraph } from "./graph";
+import { buildAssemblyStepGroups, CURRENT_PLAN_VERSION } from "./plan";
+
+export { buildAssemblyStepGroups, CURRENT_PLAN_VERSION, indexAssemblyGraph };
+export type { AssemblyGraphIndex } from "./graph";
+export type { AssemblyPlan, AssemblyStepGroup } from "./plan";
+export type { AssemblyGraph } from "./types";
diff --git a/packages/viewer/src/types.ts b/packages/viewer/src/types.ts
new file mode 100644
index 0000000000..892e3c0a23
--- /dev/null
+++ b/packages/viewer/src/types.ts
@@ -0,0 +1,131 @@
+/**
+ * Shared contracts for animated work instructions (Phase 0).
+ * These types mirror `docs/specs/animated-work-instructions-contracts.md` exactly.
+ * Change them only by updating the geometry service, the ERP/Inngest layer, and
+ * this package together.
+ */
+
+export type Vec3 = [number, number, number];
+
+/** Quaternion as [x, y, z, w] */
+export type Quat = [number, number, number, number];
+
+/** Linear insertion along a vector. Distances in mm, GLB world space. */
+export type LinearMotion = {
+ type: "linear";
+ direction: Vec3;
+ distance: number;
+};
+
+/** Two-segment motion: travel1 then travel2 (insertion order), e.g. slide then drop. */
+export type LMotion = {
+ type: "L";
+ segments: { direction: Vec3; distance: number }[];
+};
+
+/**
+ * Threaded fastener: linear approach along `axis`, then `turns` rotations about
+ * `axis` (through `origin`) advancing `pitch` mm per turn until seated.
+ */
+export type HelixMotion = {
+ type: "helix";
+ axis: Vec3;
+ origin: Vec3;
+ pitch: number;
+ turns: number;
+ /** Linear travel (mm) along `axis` before threading begins */
+ approach: number;
+};
+
+/**
+ * Explicit keyframe path (planner tier 5 / manual freeform).
+ * Keyframes are absolute world poses for the component; `t` is normalized 0..1 and
+ * must be strictly increasing. The last keyframe must equal the component's final
+ * (seated) pose.
+ */
+export type PathMotion = {
+ type: "path";
+ keyframes: { t: number; position: Vec3; quaternion: Quat }[];
+};
+
+/** No geometry motion (process-only step: cure, inspect, torque pattern). */
+export type NoneMotion = {
+ type: "none";
+};
+
+/**
+ * Describes the insertion motion of a step's components into the assembly. The
+ * viewer derives removal (the reverse) and start poses from it.
+ */
+export type Motion =
+ | LinearMotion
+ | LMotion
+ | HelixMotion
+ | PathMotion
+ | NoneMotion;
+
+/** Step camera. `null` on a step means the viewer auto-frames the active components. */
+export type CameraPose = {
+ position: Vec3;
+ target: Vec3;
+ fov: number;
+};
+
+/** Fastener callout for a step. All fields optional. */
+export type Fastener = {
+ spec?: string;
+ count?: number;
+ torqueNm?: number;
+ tool?: string;
+};
+
+export type AssemblyStep = {
+ id: string;
+ title: string | null;
+ instructionText: string | null;
+ /** Components installed in this step (stable nodeIds from glTF extras/graph.json) */
+ componentNodeIds: string[];
+ motion: Motion;
+ camera: CameraPose | null;
+ fastener: Fastener | null;
+ /** Optional authored override for the step's timeline length (seconds) */
+ durationSeconds?: number | null;
+ /**
+ * The planner proved no collision-free path for these components. The player
+ * fades them in at the seated pose instead of synthesizing a fallback
+ * motion — a fabricated path would animate straight through geometry.
+ */
+ flagged?: boolean;
+};
+
+/** One node of the assembly tree in graph.json. */
+export type AssemblyGraphNode = {
+ /** sha1(geometryHash : parentPath : siblingOrdinal)[:16] */
+ nodeId: string;
+ name: string;
+ isAssembly: boolean;
+ /** null for assemblies */
+ geometryHash: string | null;
+ /** Local transform, column-major 4x4 */
+ transform: number[];
+ /** World-space bounds, mm */
+ bbox: { min: Vec3; max: Vec3 };
+ /** mm^3, leaf nodes only (null for assemblies) */
+ volume: number | null;
+ /** RGBA 0-1 or null */
+ color: [number, number, number, number] | null;
+ children: AssemblyGraphNode[];
+};
+
+/** graph.json as written by the geometry service /convert endpoint. */
+export type AssemblyGraph = {
+ version: 1;
+ /** Normalized output unit (always mm in Phase 0) */
+ unit: "mm";
+ /** Unit declared in the STEP file */
+ sourceUnit: string;
+ /** Count of leaf instances */
+ componentCount: number;
+ /** Assembly tree; root has no geometry */
+ root: AssemblyGraphNode;
+};
diff --git a/packages/viewer/src/useAssembly.ts b/packages/viewer/src/useAssembly.ts
new file mode 100644
index 0000000000..d20dbff01f
--- /dev/null
+++ b/packages/viewer/src/useAssembly.ts
@@ -0,0 +1,137 @@
+import { useEffect, useMemo, useState } from "react";
+import type { Group, Object3D } from "three";
+import { GLTFLoader, MeshoptDecoder } from "three-stdlib";
+import type { AssemblyGraph } from "./types";
+
+export type UseAssemblyResult = {
+ /** Root group of the loaded GLB, or null while loading */
+ scene: Group | null;
+ /** Stable nodeId (glTF extras.nodeId) → Object3D */
+ nodesById: Map<string, Object3D>;
+ /** Parsed graph.json, or null while loading / when no graphUrl given */
+ graph: AssemblyGraph | null;
+ isLoading: boolean;
+ error: Error | null;
+};
+
+/**
+ * Loads a meshopt-compressed GLB (EXT_meshopt_compression) plus its
+ * graph.json and indexes scene nodes by their stable nodeId (written into
+ * glTF node extras by the geometry service, surfaced as `userData.nodeId`).
+ *
+ * Plain three.js — no react-three-fiber dependency — so it can also back
+ * non-R3F consumers.
+ */
+export function useAssembly(
+ glbUrl: string | null,
+ graphUrl: string | null
+): UseAssemblyResult {
+ const [scene, setScene] = useState<Group | null>(null);
+ const [graph, setGraph] = useState<AssemblyGraph | null>(null);
+ const [isLoading, setIsLoading] = useState(Boolean(glbUrl));
+ const [error, setError] = useState<Error | null>(null);
+
+ useEffect(() => {
+ if (!glbUrl) {
+ setScene(null);
+ setIsLoading(false);
+ return;
+ }
+
+ let cancelled = false;
+ setIsLoading(true);
+ setError(null);
+ setScene(null);
+
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(
+ // three-stdlib exports MeshoptDecoder as a factory in some versions
+ typeof MeshoptDecoder === "function" ? MeshoptDecoder() : MeshoptDecoder
+ );
+
+ let loadedScene: Group | null = null;
+ loader.load(
+ glbUrl,
+ (gltf) => {
+ if (cancelled) {
+ disposeObject(gltf.scene);
+ return;
+ }
+ loadedScene = gltf.scene;
+ setScene(gltf.scene);
+ setIsLoading(false);
+ },
+ undefined,
+ (event) => {
+ if (cancelled) return;
+ setError(
+ event instanceof Error
+ ? event
+ : new Error(`Failed to load model: ${glbUrl}`)
+ );
+ setIsLoading(false);
+ }
+ );
+
+ return () => {
+ cancelled = true;
+ if (loadedScene) disposeObject(loadedScene);
+ };
+ }, [glbUrl]);
+
+ useEffect(() => {
+ if (!graphUrl) {
+ setGraph(null);
+ return;
+ }
+
+ let cancelled = false;
+ fetch(graphUrl)
+ .then((response) => {
+ if (!response.ok) {
+ throw new Error(`Failed to load assembly graph (${response.status})`);
+ }
+ return response.json() as Promise<AssemblyGraph>;
+ })
+ .then((data) => {
+ if (!cancelled) setGraph(data);
+ })
+ .catch((fetchError: Error) => {
+ if (!cancelled) setError(fetchError);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [graphUrl]);
+
+ const nodesById = useMemo(() => {
+ const map = new Map<string, Object3D>();
+ if (scene) {
+ scene.traverse((object) => {
+ const nodeId = object.userData?.nodeId;
+ if (typeof nodeId === "string" && nodeId.length > 0) {
+ map.set(nodeId, object);
+ }
+ });
+ }
+ return map;
+ }, [scene]);
+
+ return { scene, nodesById, graph, isLoading, error };
+}
+
+function disposeObject(root: Object3D) {
+ root.traverse((object) => {
+ const mesh = object as {
+ geometry?: { dispose: () => void };
+ material?: { dispose: () => void } | { dispose: () => void }[];
+ };
+ mesh.geometry?.dispose();
+ if (Array.isArray(mesh.material)) {
+ for (const material of mesh.material) material.dispose();
+ } else {
+ mesh.material?.dispose();
+ }
+ });
+}
diff --git a/packages/viewer/src/utils.ts b/packages/viewer/src/utils.ts
new file mode 100644
index 0000000000..9254e253c6
--- /dev/null
+++ b/packages/viewer/src/utils.ts
@@ -0,0 +1,8 @@
+/**
+ * Minimal class-name joiner. Kept local so @carbon/viewer stays free of
+ * @carbon/react (and its router/i18n peer dependencies) per the assembly
+ * design spec's decoupling requirement.
+ */
+export function cn(...classes: (string | false | null | undefined)[]): string {
+ return classes.filter(Boolean).join(" ");
+}
diff --git a/packages/viewer/src/visibility.test.ts b/packages/viewer/src/visibility.test.ts
new file mode 100644
index 0000000000..59bd67c319
--- /dev/null
+++ b/packages/viewer/src/visibility.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { visualForComponent } from "./visibility";
+
+describe("visualForComponent", () => {
+ it("shows earlier-step components solid", () => {
+ expect(visualForComponent(0, 2, "ghost")).toBe("solid");
+ expect(visualForComponent(1, 2, "hidden")).toBe("solid");
+ });
+
+ it("marks the active step's components active", () => {
+ expect(visualForComponent(2, 2, "ghost")).toBe("active");
+ expect(visualForComponent(0, 0, "hidden")).toBe("active");
+ });
+
+ it("renders later-step components per the future mode", () => {
+ expect(visualForComponent(3, 1, "ghost")).toBe("ghost");
+ expect(visualForComponent(3, 1, "hidden")).toBe("hidden");
+ expect(visualForComponent(3, 1, "solid")).toBe("solid");
+ });
+
+ it("treats never-installed components exactly like future-step ones", () => {
+ for (const mode of ["ghost", "hidden", "solid"] as const) {
+ expect(visualForComponent(undefined, 0, mode)).toBe(
+ visualForComponent(99, 0, mode)
+ );
+ expect(visualForComponent(undefined, 5, mode)).toBe(
+ visualForComponent(99, 5, mode)
+ );
+ }
+ });
+
+ it("never promotes a never-installed component to solid via step position", () => {
+ // Even at the last step, an unassigned component is not "already there"
+ expect(visualForComponent(undefined, 10, "hidden")).toBe("hidden");
+ expect(visualForComponent(undefined, 10, "ghost")).toBe("ghost");
+ });
+});
diff --git a/packages/viewer/src/visibility.ts b/packages/viewer/src/visibility.ts
new file mode 100644
index 0000000000..b7e56a251a
--- /dev/null
+++ b/packages/viewer/src/visibility.ts
@@ -0,0 +1,27 @@
+/** How components of steps after the active one are rendered. */
+export type FutureComponentsMode = "ghost" | "hidden" | "solid";
+
+export type ComponentVisual = "solid" | "active" | "hidden" | "ghost";
+
+/**
+ * The visual state of a component for the active step. `stepIndex` is the
+ * index of the first step that installs the component, or `undefined` when no
+ * step ever installs it. Presence is cumulative: a component exists on the
+ * canvas only once its step has run. A component no step installs is treated
+ * exactly like a future-step component — it is never "already there".
+ */
+export function visualForComponent(
+ stepIndex: number | undefined,
+ activeStepIndex: number,
+ futureMode: FutureComponentsMode
+): ComponentVisual {
+ if (stepIndex !== undefined) {
+ if (stepIndex < activeStepIndex) return "solid";
+ if (stepIndex === activeStepIndex) return "active";
+ }
+ return futureMode === "ghost"
+ ? "ghost"
+ : futureMode === "hidden"
+ ? "hidden"
+ : "solid";
+}
diff --git a/packages/viewer/tsconfig.json b/packages/viewer/tsconfig.json
new file mode 100644
index 0000000000..0da6e2cbd0
--- /dev/null
+++ b/packages/viewer/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "include": ["src"],
+ "exclude": ["node_modules"],
+ "extends": "@carbon/config/tsconfig/react-library.json"
+}
diff --git a/packages/viewer/vitest.config.ts b/packages/viewer/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/viewer/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 577c6ff7b8..47bbdacd32 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -626,6 +626,9 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../../packages/utils
+ '@carbon/viewer':
+ specifier: workspace:*
+ version: link:../../packages/viewer
'@dagrejs/dagre':
specifier: ^1.1.4
version: 1.1.8
@@ -682,7 +685,7 @@ importers:
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -727,7 +730,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -959,16 +962,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -1028,13 +1031,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -1083,6 +1086,9 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../../packages/utils
+ '@carbon/viewer':
+ specifier: workspace:*
+ version: link:../../packages/viewer
'@dagrejs/dagre':
specifier: ^1.1.4
version: 1.1.8
@@ -2237,7 +2243,7 @@ importers:
version: 5.8.3
vitest:
specifier: 'catalog:'
packages/env:
dependencies:
@@ -2442,6 +2448,9 @@ importers:
'@carbon/utils':
specifier: workspace:*
version: link:../utils
+ '@carbon/viewer':
+ specifier: workspace:*
+ version: link:../viewer
'@internationalized/date':
specifier: 'catalog:'
version: 3.12.0
@@ -3438,6 +3447,46 @@ importers:
specifier: 'catalog:'
+ packages/viewer:
+ dependencies:
+ '@react-three/drei':
+ specifier: 9.122.0
+ '@react-three/fiber':
+ specifier: 8.18.0
+ three:
+ specifier: 0.163.0
+ version: 0.163.0
+ three-stdlib:
+ specifier: 2.36.1
+ version: 2.36.1([email protected])
+ devDependencies:
+ '@carbon/config':
+ specifier: workspace:*
+ version: link:../config
+ '@types/react':
+ specifier: 18.3.28
+ version: 18.3.28
+ '@types/react-dom':
+ specifier: 18.3.7
+ version: 18.3.7(@types/[email protected])
+ '@types/three':
+ specifier: 0.163.0
+ version: 0.163.0
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ react-dom:
+ specifier: 18.3.1
+ version: 18.3.1([email protected])
+ typescript:
+ specifier: 'catalog:'
+ version: 5.8.3
+ vitest:
+ specifier: 'catalog:'
+
packages:
'@ai-sdk-tools/[email protected]':
@@ -5011,6 +5060,9 @@ packages:
'@mdx-js/[email protected]':
resolution: {integrity: sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==}
+ '@mediapipe/[email protected]':
+ resolution: {integrity: sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg==}
+
'@messageformat/[email protected]':
resolution: {integrity: sha512-3p0YRGCcTUCYvBKLIxtDDyrJ0YijGIwrTRu1DT8gIviIDZru8H23+FkY6MJBzM1n9n20CiM4VeDYuBsrrwnLjg==}
@@ -5037,6 +5089,11 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@monogrid/[email protected]':
+ resolution: {integrity: sha512-2Z0FATFHaoYJ8b+Y4y4Hgfn3FRFwuU5zRrk+9dFWp4uGAdHGqVEdP7HP+gLA3X469KXHmfupJaUbKo1b/aDKIg==}
+ peerDependencies:
+ three: '>= 0.159.0'
+
resolution: {integrity: sha512-vrOpWRmPJSuwLo23J62wggEm/jvGdzqctej+UOCtgDUz6nZJQuj3ByPccVyaa7eQmwAzUwKN56FQPMKkqbj1GA==}
@@ -7641,6 +7698,34 @@ packages:
peerDependencies:
react-router: 7.15.1
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-Tqrwz7pIlsSDITzxoLS3n/v/YCUHQdOIKtOJf4yL6kYVSDTSmVK1LI1Q3M/uu2Sx4X3pIWF3xLUhlsA6SPNTNg==}
+ peerDependencies:
+ react: 18.3.1
+
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-rmEqcxRcu7dWh7MnCcMXLvrf6/SDlSokLaLTxiPlAYi11nN3B5oiCUAblO72o+9z/87j2uzxa2Inm8UbLjXA+w==}
+ peerDependencies:
+ react: 18.3.1
+
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-5ZenDQMC48wjUzPAm1EtwQ5Ot3bLIAwwqP2w2owG5KoNdNHpEJV263nGhCeKKmuA3vG2zLLOdu3or6kuDjA6Aw==}
+
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-wdtoJrhUeeyD/PP/zo+np2s1Z820Ohr/BbuVYv+3dVLW7WctoiN7std8rISoYoHpUXtbkpesSKuPIw/6U1w1Pw==}
+ peerDependencies:
+ react: 18.3.1
+
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-RxIsCoQfUqOS3POmhVHa1wdWS0wyHAUway73uRLp3GAL5U2iYVNdnzQsep6M2NZ994BlW8TcKuMtQHUqOsy6WA==}
+ peerDependencies:
+ '@react-three/fiber': '>=6.0'
+ react: 18.3.1
+ three: '>=0.126'
+
+ '@react-spring/[email protected]':
+ resolution: {integrity: sha512-HVj7LrZ4ReHWBimBvu2SKND3cDVUPWKLqRTmWe/fNY6o1owGOX0cAHbdPDTMelgBlVbrTKrre6lFkhqGZErK/g==}
+
'@react-stately/[email protected]':
resolution: {integrity: sha512-uw7fCZXoypSBBUsVkbNvJMQWTihZReRbyLIGG3o/ZM630N3OCZhb/h4Uxke4pNu7n527H0V1bAnZgAldIzOYqg==}
peerDependencies:
@@ -7779,6 +7864,42 @@ packages:
peerDependencies:
react: 18.3.1
+ '@react-three/[email protected]':
+ resolution: {integrity: sha512-SEO/F/rBCTjlLez7WAlpys+iGe9hty4rNgjZvgkQeXFSiwqD4Hbk/wNHMAbdd8vprO2Aj81mihv4dF5bC7D0CA==}
+ peerDependencies:
+ '@react-three/fiber': ^8
+ react: 18.3.1
+ react-dom: 18.3.1
+ three: '>=0.137'
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+
+ '@react-three/[email protected]':
+ resolution: {integrity: sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==}
+ peerDependencies:
+ expo: '>=43.0'
+ expo-asset: '>=8.4'
+ expo-file-system: '>=11.0'
+ expo-gl: '>=11.0'
+ react: 18.3.1
+ react-dom: 18.3.1
+ react-native: '>=0.64'
+ three: '>=0.133'
+ peerDependenciesMeta:
+ expo:
+ optional: true
+ expo-asset:
+ optional: true
+ expo-file-system:
+ optional: true
+ expo-gl:
+ optional: true
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+
'@react-types/[email protected]':
resolution: {integrity: sha512-AnkyYYmzaM2QFi/N0P/kQLM8tHOyFi7p397B/jEMucXDfwMw5Ny1ObCXeIEqbh8KrIa2Xp8SxmQlCV+8FPs4LA==}
peerDependencies:
@@ -8997,6 +9118,9 @@ packages:
cpu: [arm64]
os: [win32]
+ '@tweenjs/[email protected]':
+ resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==}
+
resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
@@ -9174,6 +9298,9 @@ packages:
resolution: {integrity: sha512-IDBwO5IZhrKvHFUl+clZxgf3hn2b/lU6H1KaBShPkQyGJUQ0xwebezIPSuiyGwfz1UzJWQl4M7BDxtHtCCPlTg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==}
+
resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
@@ -9281,6 +9408,9 @@ packages:
resolution: {integrity: sha512-k7kRA033QNtC+gLc4VPlfnue58CM1iQLgn1IMAU8VPHGOj7oIHPp9UlhedEnD/Gl8evoCjwkZjlBORtZ3JByUA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==}
+
resolution: {integrity: sha512-kK1eBS/Adeyis+3OlBDMeQQuasIDLUYXsi2T15ccNJ0iyUpQ4xDF7svFu3+bGVrI0CMBUclPciz+lsQR3JX3TQ==}
@@ -9319,6 +9449,9 @@ packages:
peerDependencies:
'@types/react': 18.3.28
+ '@types/[email protected]':
+ resolution: {integrity: sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==}
+
resolution: {integrity: sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==}
peerDependencies:
@@ -9344,6 +9477,9 @@ packages:
resolution: {integrity: sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==}
+
resolution: {integrity: sha512-xevGOReSYGM7g/kUBZzPqCrR/KYAo+F0yiPc85WFTJa0MSLtyFTVTU6cJu/aV4mid7IffDIWqo69THF2o4JiEQ==}
@@ -9356,6 +9492,9 @@ packages:
resolution: {integrity: sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-uIdDhsXRpQiBUkflBS/i1l3JX14fW6Ot9csed60nfbZNXHDTRsnV2xnTVwXcgbvTiboAR4IW+t+lTL5f1rqIqA==}
+
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
@@ -9371,6 +9510,9 @@ packages:
resolution: {integrity: sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==}
+
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
@@ -9443,6 +9585,14 @@ packages:
'@upstash/[email protected]':
resolution: {integrity: sha512-LqOJ3+XWPLSZ2rGSed5DYG3ixybxb8EhZu3yQqF7MdZX1wLBG/FRcI6xcUZXHy/SS7mmXWyadrud0HJHkOc+uw==}
+ '@use-gesture/[email protected]':
+ resolution: {integrity: sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==}
+
+ '@use-gesture/[email protected]':
+ resolution: {integrity: sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==}
+ peerDependencies:
+ react: 18.3.1
+
'@vercel/[email protected]':
resolution: {integrity: sha512-oH9He/bEM+6oKlv3chWuOOcp8Y6fo6/PSro8hEkgCW3pu9/OiCXiUpRUogDh3Fs3LH2sosDrx8CxeOLBEE+afg==}
peerDependencies:
@@ -9952,6 +10102,11 @@ packages:
resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-KnaKdcvkBJ1Irbrzl8XD6WtZltkRjp869Jx8c0ujs9K+9WD+1D7ryBsCiVqJYUqt6i/HR5FxT7RLASieUD+Q5w==}
+ peerDependencies:
+ three: '>=0.126.1'
+
resolution: {integrity: sha512-mNcrMN9KeI68u7muanUpEejSLghOKlVhRqS/Za2IeyGllJ9I9otGpR9g3nsw7n4W378TE/LyIteA0+/FOZm4Kg==}
@@ -10580,6 +10735,9 @@ packages:
resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
+ resolution: {integrity: sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==}
+
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
@@ -10636,6 +10794,9 @@ packages:
resolution: {integrity: sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==}
+
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
@@ -10954,6 +11115,9 @@ packages:
resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==}
+ resolution: {integrity: sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg==}
+
resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}
@@ -11295,6 +11459,9 @@ packages:
resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==}
+
resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==}
engines: {node: '>=14'}
@@ -11390,6 +11557,9 @@ packages:
resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==}
+
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
@@ -11733,6 +11903,9 @@ packages:
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==}
+
resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}
@@ -11917,6 +12090,7 @@ packages:
resolution: {integrity: sha512-Dep8wO3Fr5wNjQevO2Z8Y7yeee/nYSGRsi7q6zJDKEVHxXkXT+v21vxHmDX923UzmCXXkSo62HaTz6eTWzFLaw==}
engines: {node: '>= 16'}
+ deprecated: A security vulnerability has been reported with the preventCsvInjection option which has been fixed in version 5.5.11. Please upgrade as soon as possible.
resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}
@@ -12215,6 +12389,12 @@ packages:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
+ resolution: {integrity: sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==}
+ peerDependencies:
+ '@types/three': '>=0.134.0'
+ three: '>=0.134.0'
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -12346,6 +12526,14 @@ packages:
resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==}
+ peerDependencies:
+ three: '>=0.137'
+
+ resolution: {integrity: sha512-ZhoIoL7TNV4s5B6+rx5mC//fw8/POGyNxS/DZyCJeiZ12ScLfVwRE/GfsxwiTkMYYD5DmK2/JXnEVXqL4rF+Sw==}
+
resolution: {integrity: sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==}
engines: {node: '>= 0.6'}
@@ -13215,6 +13403,9 @@ packages:
resolution: {integrity: sha512-jWNwB8XjlVUC9PbGaIlmsyohUDMBrwf7cvLuOY3lIOmWVO3L6VxTE3GZShjxpFKQtmWcPxFbf1hcbct1YCb6xg==}
+ resolution: {integrity: sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==}
+
resolution: {integrity: sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==}
@@ -13252,6 +13443,9 @@ packages:
resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==}
engines: {node: '>= 0.6.0'}
+ resolution: {integrity: sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==}
+
resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}
@@ -13401,6 +13595,11 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ resolution: {integrity: sha512-1uWd07EME6XZvMfapwZmc7NgCZqDemcvicRi3wMJzXsQLvZ3L7fTHVyPy1bZdnWXM4iPjYuNE+uJ41MLKeTtnA==}
+ peerDependencies:
+ react: 18.3.1
+
resolution: {integrity: sha512-ow5ns/1ttzXsIlbbfJmWJNiyQK8lTHBL6lRSUXGaK44K/3NIMngR57Ja96l+D6txTeFhfe0BfXGvORMxhtRDng==}
peerDependencies:
@@ -13516,6 +13715,12 @@ packages:
resolution: {integrity: sha512-I42jl7L3Ze6kZaq+7zXWSunBa3b1on5yfvUW6Eo/3fFOj6dZ5Bqmcd264nJbTK/gn1HjjILAjSwnZbV4RpSaNQ==}
+ resolution: {integrity: sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==}
+ engines: {node: '>=0.10.0'}
+ peerDependencies:
+ react: 18.3.1
+
resolution: {integrity: sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==}
engines: {node: '>=0.10.0'}
@@ -13673,6 +13878,7 @@ packages:
resolution: {integrity: sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==}
engines: {node: '>=14'}
+ deprecated: 1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide
peerDependencies:
react: 18.3.1
react-dom: 18.3.1
@@ -13882,6 +14088,9 @@ packages:
resolution: {integrity: sha512-7rro8Io3tnCPuY4la/NuI5F2yfESpnfZyT6TtkXnSWVkcu0BCDJ+8gk5ozUaFaxpIyNuWAPXrH0yFcSi28fnDA==}
+ resolution: {integrity: sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==}
+
resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}
@@ -14136,6 +14345,15 @@ packages:
resolution: {integrity: sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==}
+ resolution: {integrity: sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==}
+ peerDependencies:
+ '@types/three': '*'
+ three: '*'
+
+ resolution: {integrity: sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==}
+
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
@@ -14293,6 +14511,11 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==}
+ peerDependencies:
+ react: 18.3.1
+
resolution: {integrity: sha512-djbJ/vZKZO+gPoSDThGNpKDO+o+bAeA4XQKovvkNCqnIS2t+S4qnLAGQhyyrulhCFRl1WWzAp0wUDV8PpTVU3g==}
@@ -14367,6 +14590,17 @@ packages:
resolution: {integrity: sha512-Mx5NBSHX3sQYR6iI9VYbgHKBLisyB+xROCBGjjWm1O9wb9vfLxdaGtmT/KCjUqMsSNW6nERzCW3T6H43LqjDZQ==}
+ resolution: {integrity: sha512-BGEZTOIC14U0XIRw3tO4jY7IjP7n7v24nv9JXS1CyeVRWOCkcOMhRnmENUjuV39gktAw4Ofhr0OvIAiTspQrrw==}
+ deprecated: Deprecated due to three.js version incompatibility. Please use v0.8.0, instead.
+ peerDependencies:
+ three: '>= 0.151.0'
+
+ resolution: {integrity: sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==}
+ peerDependencies:
+ three: '>=0.128.0'
+
resolution: {integrity: sha512-HlMgCb2TF/dTLRtknBnjUTsR8FsDqBY43itYop2+Zg822I+Kd0Ua2vs8CvfBVefXkBdNDrLMoRTGCIIpfCuDew==}
@@ -14449,6 +14683,19 @@ packages:
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
+ resolution: {integrity: sha512-V50EwcYGruV5rUZ9F4aNsrytGdKcXKALjEtQXIOBfhVoZU9VAqZNIoGQ3TMiooVqFAbR1w15T+f+8gkzoFzawg==}
+ peerDependencies:
+ three: '>=0.125.0'
+
+ resolution: {integrity: sha512-NORAStSVa/BDiG52Mfudk4j1FG4jC4ILutB3foPnfGbOeIs9+G5vZLa0pnmnaftZUGm4UwSoqEpWdqvC7zms3A==}
+ peerDependencies:
+ three: '>=0.125.0'
+
+ resolution: {integrity: sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw==}
+
resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
@@ -14671,6 +14918,10 @@ packages:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
+ resolution: {integrity: sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==}
+ engines: {node: '>= 4'}
+
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
engines: {node: '>= 0.4.0'}
@@ -14874,6 +15125,12 @@ packages:
resolution: {integrity: sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==}
+ resolution: {integrity: sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg==}
+
+ resolution: {integrity: sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==}
+
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
@@ -15039,6 +15296,15 @@ packages:
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
+ resolution: {integrity: sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==}
+ engines: {node: '>=12.7.0'}
+ peerDependencies:
+ react: 18.3.1
+ peerDependenciesMeta:
+ react:
+ optional: true
+
resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
engines: {node: '>=12.7.0'}
@@ -16659,6 +16925,16 @@ snapshots:
transitivePeerDependencies:
- typescript
+ dependencies:
+ '@lingui/cli': 5.9.4([email protected])([email protected])
+ '@lingui/conf': 5.9.4([email protected])
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - typescript
+
dependencies:
'@lingui/cli': 5.9.4([email protected])([email protected])
@@ -16721,6 +16997,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@mediapipe/[email protected]': {}
+
'@messageformat/[email protected]':
dependencies:
moo: 0.5.3
@@ -16760,6 +17038,11 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ promise-worker-transferable: 1.0.4
+ three: 0.163.0
+
'@mui/[email protected]': {}
@@ -19998,6 +20281,56 @@ snapshots:
- tsx
- yaml
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/generator': 7.29.1
+ '@babel/parser': 7.29.2
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/preset-typescript': 7.28.5(@babel/[email protected])
+ '@babel/traverse': 7.29.0
+ '@babel/types': 7.29.0
+ '@remix-run/node-fetch-server': 0.13.1
+ arg: 5.0.2
+ babel-dead-code-elimination: 1.0.12
+ chokidar: 4.0.3
+ dedent: 1.7.2([email protected])
+ es-module-lexer: 1.7.0
+ exit-hook: 2.2.1
+ isbot: 5.1.37
+ jsesc: 3.0.2
+ lodash: 4.17.21
+ p-map: 7.0.4
+ pathe: 1.1.2
+ picocolors: 1.1.1
+ pkg-types: 2.3.0
+ prettier: 3.8.1
+ react-refresh: 0.14.2
+ semver: 7.7.4
+ tinyglobby: 0.2.17
+ valibot: 1.3.1([email protected])
+ optionalDependencies:
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@types/node'
+ - babel-plugin-macros
+ - jiti
+ - less
+ - lightningcss
+ - sass
+ - sass-embedded
+ - stylus
+ - sugarss
+ - supports-color
+ - terser
+ - tsx
+ - yaml
+
dependencies:
'@babel/core': 7.29.0
@@ -20076,6 +20409,12 @@ snapshots:
optionalDependencies:
typescript: 5.8.3
+ dependencies:
+ optionalDependencies:
+ typescript: 5.8.3
+
dependencies:
@@ -20097,6 +20436,39 @@ snapshots:
- supports-color
- typescript
+ dependencies:
+ '@react-spring/shared': 9.7.5([email protected])
+ '@react-spring/types': 9.7.5
+ react: 18.3.1
+
+ dependencies:
+ '@react-spring/animated': 9.7.5([email protected])
+ '@react-spring/shared': 9.7.5([email protected])
+ '@react-spring/types': 9.7.5
+ react: 18.3.1
+
+ '@react-spring/[email protected]': {}
+
+ dependencies:
+ '@react-spring/rafz': 9.7.5
+ '@react-spring/types': 9.7.5
+ react: 18.3.1
+
+ dependencies:
+ '@react-spring/animated': 9.7.5([email protected])
+ '@react-spring/core': 9.7.5([email protected])
+ '@react-spring/shared': 9.7.5([email protected])
+ '@react-spring/types': 9.7.5
+ react: 18.3.1
+ three: 0.163.0
+
+ '@react-spring/[email protected]': {}
+
dependencies:
'@internationalized/date': 3.12.0
@@ -20330,6 +20702,61 @@ snapshots:
'@swc/helpers': 0.5.21
react: 18.3.1
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@mediapipe/tasks-vision': 0.10.17
+ '@monogrid/gainmap-js': 3.4.0([email protected])
+ '@use-gesture/react': 10.3.1([email protected])
+ camera-controls: 2.10.1([email protected])
+ cross-env: 7.0.3
+ detect-gpu: 5.0.70
+ glsl-noise: 0.0.0
+ hls.js: 1.6.16
+ maath: 0.10.8(@types/[email protected])([email protected])
+ meshline: 3.3.1([email protected])
+ react: 18.3.1
+ react-composer: 5.0.3([email protected])
+ stats-gl: 2.4.2(@types/[email protected])([email protected])
+ stats.js: 0.17.0
+ suspend-react: 0.1.3([email protected])
+ three: 0.163.0
+ three-mesh-bvh: 0.7.8([email protected])
+ three-stdlib: 2.36.1([email protected])
+ troika-three-text: 0.52.4([email protected])
+ utility-types: 3.11.0
+ optionalDependencies:
+ react-dom: 18.3.1([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/three'
+ - immer
+ - use-sync-external-store
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ '@types/react-reconciler': 0.26.7
+ '@types/webxr': 0.5.24
+ base64-js: 1.5.1
+ buffer: 6.0.3
+ its-fine: 1.2.5(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-reconciler: 0.27.0([email protected])
+ scheduler: 0.21.0
+ suspend-react: 0.1.3([email protected])
+ three: 0.163.0
+ zustand: 3.7.2([email protected])
+ optionalDependencies:
+ react-dom: 18.3.1([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+
dependencies:
'@react-types/link': 3.6.7([email protected])
@@ -21272,6 +21699,13 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.3.0
+ dependencies:
+ '@tailwindcss/node': 4.3.0
+ '@tailwindcss/oxide': 4.3.0
+ tailwindcss: 4.3.0
+
dependencies:
'@tailwindcss/node': 4.3.0
@@ -21596,6 +22030,8 @@ snapshots:
optional: true
+ '@tweenjs/[email protected]': {}
+
dependencies:
tslib: 2.8.1
@@ -21805,6 +22241,8 @@ snapshots:
dependencies:
'@types/trusted-types': 2.0.7
+ '@types/[email protected]': {}
+
dependencies:
'@types/estree': 1.0.8
@@ -21929,6 +22367,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 22.19.7
@@ -21967,6 +22407,10 @@ snapshots:
dependencies:
'@types/react': 18.3.28
+ '@types/[email protected]':
+ dependencies:
+ '@types/react': 18.3.28
+
dependencies:
'@types/react': 18.3.28
@@ -21995,6 +22439,8 @@ snapshots:
'@types/http-errors': 2.0.5
'@types/node': 22.19.7
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -22007,6 +22453,14 @@ snapshots:
dependencies:
'@types/node': 22.19.7
+ '@types/[email protected]':
+ dependencies:
+ '@tweenjs/tween.js': 23.1.3
+ '@types/stats.js': 0.17.4
+ '@types/webxr': 0.5.24
+ fflate: 0.8.2
+ meshoptimizer: 0.18.1
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -22017,6 +22471,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 22.19.7
@@ -22073,6 +22529,13 @@ snapshots:
dependencies:
uncrypto: 0.1.3
+ '@use-gesture/[email protected]': {}
+
+ dependencies:
+ '@use-gesture/core': 10.3.1
+ react: 18.3.1
+
optionalDependencies:
@@ -22080,6 +22543,16 @@ snapshots:
'@vercel/[email protected]': {}
+ dependencies:
+ '@vercel/static-config': 3.2.0
+ isbot: 5.1.37
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ ts-morph: 12.0.0
+
dependencies:
@@ -22681,6 +23154,10 @@ snapshots:
+ dependencies:
+ three: 0.163.0
+
@@ -23322,6 +23799,10 @@ snapshots:
+ dependencies:
+ webgl-constants: 1.1.1
+
@@ -23375,6 +23856,8 @@ snapshots:
+
dependencies:
call-bind-apply-helpers: 1.0.2
@@ -23886,6 +24369,8 @@ snapshots:
+
@@ -24250,6 +24735,8 @@ snapshots:
define-properties: 1.2.1
gopd: 1.2.0
+
@@ -24416,6 +24903,8 @@ snapshots:
+
dependencies:
react-is: 16.13.1
@@ -24813,6 +25302,8 @@ snapshots:
+
@@ -25273,6 +25764,11 @@ snapshots:
+ dependencies:
+ '@types/three': 0.163.0
+ three: 0.163.0
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -25494,6 +25990,12 @@ snapshots:
+ dependencies:
+ three: 0.163.0
+
+
@@ -26414,6 +26916,8 @@ snapshots:
query-selector-shadow-dom: 1.0.1
web-vitals: 5.2.0
+
@@ -26444,6 +26948,11 @@ snapshots:
+ dependencies:
+ is-promise: 2.2.2
+ lie: 3.1.1
+
dependencies:
loose-envify: 1.4.0
@@ -26699,6 +27208,11 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ prop-types: 15.8.1
+ react: 18.3.1
+
dependencies:
react: 18.3.1
@@ -26847,6 +27361,12 @@ snapshots:
dependencies:
fast-deep-equal: 2.0.1
+ dependencies:
+ loose-envify: 1.4.0
+ react: 18.3.1
+ scheduler: 0.21.0
+
dependencies:
loose-envify: 1.4.0
@@ -27365,6 +27885,10 @@ snapshots:
loose-envify: 1.4.0
object-assign: 4.1.1
+ dependencies:
+ loose-envify: 1.4.0
+
dependencies:
loose-envify: 1.4.0
@@ -27691,6 +28215,13 @@ snapshots:
+ dependencies:
+ '@types/three': 0.163.0
+ three: 0.163.0
+
+
@@ -27866,6 +28397,10 @@ snapshots:
+ dependencies:
+ react: 18.3.1
+
@@ -27984,6 +28519,20 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ three: 0.163.0
+
+ dependencies:
+ '@types/draco3d': 1.4.10
+ '@types/offscreencanvas': 2019.7.3
+ '@types/webxr': 0.5.24
+ draco3d: 1.5.7
+ fflate: 0.6.10
+ potpack: 1.0.2
+ three: 0.163.0
+
@@ -28049,6 +28598,20 @@ snapshots:
+ dependencies:
+ bidi-js: 1.0.3
+ three: 0.163.0
+ troika-three-utils: 0.52.4([email protected])
+ troika-worker-utils: 0.52.0
+ webgl-sdf-generator: 1.1.1
+
+ dependencies:
+ three: 0.163.0
+
+
@@ -28335,6 +28898,8 @@ snapshots:
+
@@ -28443,6 +29008,17 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-syntax-jsx': 7.28.6(@babel/[email protected])
+ '@babel/plugin-syntax-typescript': 7.28.6(@babel/[email protected])
+ '@types/babel__core': 7.20.5
+ babel-plugin-macros: 3.1.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -28814,6 +29390,10 @@ snapshots:
+
+
@@ -28978,6 +29558,10 @@ snapshots:
+ optionalDependencies:
+ react: 18.3.1
+
dependencies:
use-sync-external-store: 1.6.0([email protected])
diff --git a/scripts/create-agent.ts b/scripts/create-agent.ts
deleted file mode 100644
index c86866a392..0000000000
--- a/scripts/create-agent.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { existsSync, writeFileSync } from "fs";
-import { join } from "path";
-
-const agentName = process.argv[2];
-
-if (!agentName) {
- console.error("Error: Agent name is required");
- console.log("Usage: pnpm run agent:new <agentName>");
- console.log("Example: pnpm run agent:new inventory");
- process.exit(1);
-}
-
-// Convert agentName to kebab-case for file name
-const fileName = agentName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
-
-const AGENTS_DIR = join(
- process.cwd(),
- "apps",
- "erp",
- "app",
- "routes",
- "api+",
- "ai+",
- "chat+",
- "agents"
-);
-
-if (!existsSync(AGENTS_DIR)) {
- console.error(`Error: Agents directory not found at ${AGENTS_DIR}`);
- process.exit(1);
-}
-
-const agentFilePath = join(AGENTS_DIR, `${fileName}-agent.ts`);
-
-if (existsSync(agentFilePath)) {
- console.error(`Error: Agent file already exists at ${agentFilePath}`);
- process.exit(1);
-}
-
-// Convert to PascalCase for display name
-const displayName =
- agentName.charAt(0).toUpperCase() +
- agentName.slice(1).replace(/([A-Z])/g, " $1");
-
-const agentTemplate = `import { openai } from "@ai-sdk/openai";
-import { createAgent } from "./shared/agent";
-import { COMMON_AGENT_RULES, formatContextForLLM } from "./shared/prompts";
-import type { AgentConfig } from "./shared/tools";
-
-export const config: AgentConfig = {
- name: "${agentName}",
- displayName: "${displayName} Agent",
- description: "Description of what this agent does",
- executingMessage: "Calling the ${agentName} agent...",
-};
-
-export const ${agentName}Agent = createAgent({
- name: "${agentName}",
- model: openai("gpt-4o"),
- temperature: 0.5,
- instructions: (ctx) => \`You are a ${agentName} specialist for \${ctx.companyName}.
-
-<background-data>
-\${formatContextForLLM(ctx)}
-</background-data>
-
-\${COMMON_AGENT_RULES}
-
-<capabilities>
-- Add your agent capabilities here
-</capabilities>\`,
- tools: {
- // Add your tools here
- // exampleTool: exampleToolTool,
- },
- handoffs: [],
- maxTurns: 10,
-});
-`;
-
-try {
- writeFileSync(agentFilePath, agentTemplate, "utf-8");
- console.log(`✅ Successfully created agent at ${agentFilePath}`);
- console.log(`\nNext steps:`);
- console.log(`1. Edit ${agentFilePath} to implement your agent logic`);
- console.log(`2. Add tools to the tools object`);
- console.log(`3. Update the instructions and capabilities`);
- console.log(`4. Configure handoffs to other agents if needed`);
- console.log(
- `5. Add the agent to the AgentStatus type in app/components/Chat/lib/types.ts`
- );
- console.log(
- `6. Import and add the agent to handoffs in orchestration-agent.ts if needed`
- );
-} catch (error) {
- console.error(`Failed to create agent file:`, error);
- process.exit(1);
-}
diff --git a/scripts/create-tool.ts b/scripts/create-tool.ts
deleted file mode 100644
index d5360d55c3..0000000000
--- a/scripts/create-tool.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { existsSync, writeFileSync } from "fs";
-import { join } from "path";
-
-const toolName = process.argv[2];
-
-if (!toolName) {
- console.error("Error: Tool name is required");
- console.log("Usage: pnpm run tool:new <toolName>");
- console.log("Example: pnpm run tool:new getPart");
- process.exit(1);
-}
-
-// Convert toolName to kebab-case for file name
-const fileName = toolName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
-
-const TOOLS_DIR = join(
- process.cwd(),
- "apps",
- "erp",
- "app",
- "routes",
- "api+",
- "ai+",
- "chat+",
- "tools"
-);
-
-if (!existsSync(TOOLS_DIR)) {
- console.error(`Error: Tools directory not found at ${TOOLS_DIR}`);
- process.exit(1);
-}
-
-const toolFilePath = join(TOOLS_DIR, `${fileName}.ts`);
-
-if (existsSync(toolFilePath)) {
- console.error(`Error: Tool file already exists at ${toolFilePath}`);
- process.exit(1);
-}
-
-const toolTemplate = `import { tool } from "ai";
-import { LuSearch } from "react-icons/lu";
-import { z } from "zod";
-import type { ToolConfig } from "../agents/shared/tools";
-import type { ChatContext } from "../agents/shared/context";
-
-export const config: ToolConfig = {
- name: "${toolName}",
- icon: LuSearch,
- displayText: "Processing ${toolName}",
- message: "Processing ${toolName.toLowerCase()}...",
-};
-
-export const ${toolName}Schema = z.object({
- // Add your schema properties here
-});
-
-export const ${toolName}Tool = tool({
- description: "Description of what this tool does",
- inputSchema: ${toolName}Schema,
- execute: async function (args, executionOptions) {
- const context = executionOptions.experimental_context as ChatContext;
-
- // TODO: Implement tool logic here
-
- return {
- message: "Hello from ${toolName}!",
- };
- },
-});
-`;
-
-try {
- writeFileSync(toolFilePath, toolTemplate, "utf-8");
- console.log(`✅ Successfully created tool at ${toolFilePath}`);
- console.log(`\nNext steps:`);
- console.log(`1. Edit ${toolFilePath} to implement your tool logic`);
- console.log(`2. Update the schema in ${toolName}Schema`);
- console.log(`3. Update the description and execute function`);
- console.log(`4. Change the icon if needed (from react-icons/lu)`);
-} catch (error) {
- console.error(`Failed to create tool file:`, error);
- process.exit(1);
-}
diff --git a/scripts/get-lb-info.sh b/scripts/get-lb-info.sh
deleted file mode 100755
index 0186e699a6..0000000000
--- a/scripts/get-lb-info.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/bin/bash
-
-# Script to get Load Balancer DNS names for Carbon ERP services
-# Run this after deploying your SST application
-
-echo "Getting Load Balancer information for Carbon services..."
-echo "==========================================================="
-
-# Get the region from your SST config
-REGION="us-gov-east-1"
-
-# Find load balancers with Carbon in the name or tags
-echo "Finding Load Balancers..."
-aws elbv2 describe-load-balancers \
- --region $REGION \
- --query 'LoadBalancers[?contains(LoadBalancerName, `carbon`) || contains(LoadBalancerName, `Carbon`)].{Name:LoadBalancerName,DNSName:DNSName,Type:Type,State:State.Code}' \
- --output table
-
-echo ""
-echo "If no results above, trying to find by tags..."
-
-# Alternative: Find by tags (SST usually tags resources)
-aws elbv2 describe-load-balancers \
- --region $REGION \
- --query 'LoadBalancers[].{Name:LoadBalancerName,DNSName:DNSName,Type:Type,State:State.Code}' \
- --output table
-
-echo ""
-echo "To get more detailed information about a specific load balancer, run:"
-echo "aws elbv2 describe-load-balancers --region us-gov-east-1 --load-balancer-arns <ARN>"
-echo ""
-echo "Once you have the DNS name(s), create these DNS records in your domain provider:"
-echo "1. CNAME record: itar.carbon.ms -> <ERP_LOAD_BALANCER_DNS_NAME>"
-echo "2. CNAME record: mes.itar.carbon.ms -> <MES_LOAD_BALANCER_DNS_NAME>"
-
-carbonmesservic-suwrtafs-1163782910.us-gov-east-1.elb.amazonaws.com
-carbonerpservic-ktfsohkb-1407316043.us-gov-east-1.elb.amazonaws.com
\ No newline at end of file
diff --git a/scripts/govcloud-test.ts b/scripts/govcloud-test.ts
deleted file mode 100644
index 0d1be0b814..0000000000
--- a/scripts/govcloud-test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// import type { User } from "@supabase/supabase-js";
-import { createClient } from "@supabase/supabase-js";
-import * as dotenv from "dotenv";
-
-dotenv.config();
-(async () => {
- const supabase = createClient(
- process.env.GOVCLOUD_SUPABASE_URL!,
- process.env.GOVCLOUD_SUPABASE_SERVICE_ROLE_KEY!
- );
-
- try {
- // Upload to test bucket
- const { data, error } = await supabase.functions.invoke("seed-company", {});
-
- console.log({ data, error });
- } catch (err) {
- console.error("Error:", err);
- }
-})();
diff --git a/scripts/make-users-admins.ts b/scripts/make-users-admins.ts
deleted file mode 100644
index ddedf23485..0000000000
--- a/scripts/make-users-admins.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-// import type { User } from "@supabase/supabase-js";
-import { createClient } from "@supabase/supabase-js";
-import * as dotenv from "dotenv";
-
-dotenv.config();
-
-console.log(process.env.PROD_SUPABASE_URL);
-
-const supabaseAdmin = createClient(
- process.env.PROD_SUPABASE_URL!,
- process.env.PROD_SUPABASE_SERVICE_ROLE_KEY!,
- {
- auth: {
- autoRefreshToken: false,
- persistSession: false,
- },
- }
-);
-
-(async () => {
- const { data: users } = await supabaseAdmin
- .from("user")
- .select("id, email")
- .ilike("email", "%@carbon.ms");
-
- if (!users) throw new Error("No users found");
-
- const userIds = users.map((user) => user.id);
- const commaSeparatedIds = userIds.join(", ");
-
- console.log("User IDs:", commaSeparatedIds);
-
- // Save to file
- const fs = require("fs");
- fs.writeFileSync("user-ids.txt", commaSeparatedIds);
- console.log("User IDs saved to user-ids.txt");
-})();
diff --git a/scripts/restore-database.sh b/scripts/restore-database.sh
new file mode 100644
index 0000000000..2a117575c8
--- /dev/null
+++ b/scripts/restore-database.sh
@@ -0,0 +1,272 @@
+#!/usr/bin/env bash
+#
+# Restores a Supabase backup into this worktree's local Postgres, keeping
+# all data (including emails) exactly as in prod. Accepts either a
+# plain-text cluster dump (.backup) or a custom-format pg_dump archive
+# (.dump) — the format is auto-detected. Optionally upgrades one user to
+# Admin in the companies they already belong to.
+#
+# ⚠ NOTE: emails are NOT scrubbed — real production email addresses will be
+# present in the local DB. Make sure local email sending is disabled or
+# pointed at a sandbox (e.g. Mailpit) before triggering any email flows.
+#
+# Usage:
+# ./packages/database/scripts/restore-prod-backup.sh /path/to/db_cluster-XX.backup
+# ./packages/database/scripts/restore-prod-backup.sh /path/to/postgres_YYYYMMDD.dump
+#
+# Optional env vars:
+# ADMIN_EMAIL your prod email — script looks it up, upgrades you to
+# Admin in the companies you ALREADY belong to, then
+# resets the password
+# ADMIN_PASSWORD password to set on that account locally (default: localpass)
+#
+# Examples:
+# [email protected] ./packages/database/scripts/restore-prod-backup.sh ~/Downloads/db_cluster.backup
+#
+# Safety:
+# - Only ever connects to 127.0.0.1 on the port crbn assigned this worktree.
+# - Refuses to run if the worktree isn't registered in ~/.carbon/dev-ports.json.
+#
+set -euo pipefail
+ADMIN_EMAIL="${ADMIN_EMAIL:-}"
+ADMIN_PASSWORD="${ADMIN_PASSWORD:-localpass}"
+BACKUP_FILE="${1:-}"
+if [[ -z "$BACKUP_FILE" || ! -f "$BACKUP_FILE" ]]; then
+ echo "usage: $0 <path-to-.backup-file>" >&2
+ exit 1
+fi
+# Determine which Carbon worktree to restore into. Works no matter where this
+# script file lives: prefer the git worktree of the current directory, then fall
+# back to the git worktree containing the script itself.
+REPO_ROOT="$(git -C "$PWD" rev-parse --show-toplevel 2>/dev/null || true)"
+if [[ -z "$REPO_ROOT" ]]; then
+ REPO_ROOT="$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel 2>/dev/null || true)"
+fi
+if [[ -z "$REPO_ROOT" ]]; then
+ echo "Could not determine the Carbon worktree. Run this from inside the worktree you want to restore." >&2
+ exit 1
+fi
+PORT_DB=$(node -e "
+ const fs = require('fs'), path = require('path'), os = require('os');
+ const reg = JSON.parse(fs.readFileSync(path.join(os.homedir(), '.carbon/dev-ports.json'), 'utf8'));
+ for (const slot of Object.values(reg)) {
+ if (path.resolve(slot.worktreeRoot) === '$REPO_ROOT') {
+ process.stdout.write(String(slot.ports.PORT_DB));
+ process.exit(0);
+ }
+ }
+ console.error('No slot in ~/.carbon/dev-ports.json for $REPO_ROOT');
+ process.exit(1);
+")
+export PGPASSWORD=postgres
+PSQL_PG="psql -h 127.0.0.1 -p $PORT_DB -U postgres -d postgres"
+PSQL_SA="psql -h 127.0.0.1 -p $PORT_DB -U supabase_admin -d postgres"
+echo "▶ Local Postgres: 127.0.0.1:$PORT_DB"
+$PSQL_PG -c 'SELECT 1' > /dev/null \
+ || { echo "Postgres not reachable. Run 'crbn up' first." >&2; exit 1; }
+# ── 1. Restore superuser on postgres (in case a prior dump demoted it) ──────
+$PSQL_SA -c "ALTER ROLE postgres WITH SUPERUSER CREATEROLE CREATEDB LOGIN REPLICATION BYPASSRLS;" \
+ >/dev/null 2>&1 || true
+# ── 2. Drop existing public schema (per-object to avoid lock-table exhaustion)
+echo "▶ Dropping existing public-schema objects"
+$PSQL_PG -At -c "SELECT format('DROP TABLE IF EXISTS public.%I CASCADE;', tablename) FROM pg_tables WHERE schemaname='public'" \
+ | $PSQL_PG -v ON_ERROR_STOP=0 >/dev/null
+$PSQL_PG -At -c "
+ SELECT format('DROP VIEW IF EXISTS public.%I CASCADE;', viewname) FROM pg_views WHERE schemaname='public'
+ UNION ALL SELECT format('DROP MATERIALIZED VIEW IF EXISTS public.%I CASCADE;', matviewname) FROM pg_matviews WHERE schemaname='public'
+ UNION ALL SELECT format('DROP FUNCTION IF EXISTS public.%I(%s) CASCADE;', p.proname, pg_get_function_identity_arguments(p.oid))
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname='public'
+ UNION ALL SELECT format('DROP TYPE IF EXISTS public.%I CASCADE;', t.typname)
+ FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
+ WHERE n.nspname='public' AND t.typcategory IN ('E','C')
+ UNION ALL SELECT format('DROP SEQUENCE IF EXISTS public.%I CASCADE;', sequencename) FROM pg_sequences WHERE schemaname='public'
+" | $PSQL_PG -v ON_ERROR_STOP=0 >/dev/null
+$PSQL_PG -c "TRUNCATE auth.users CASCADE; TRUNCATE storage.objects CASCADE; TRUNCATE storage.buckets CASCADE;" >/dev/null
+# ── 3. Restore ───────────────────────────────────────────────────────────────
+# Supports both plain-text SQL dumps (Supabase cluster .backup files) and
+# custom-format pg_dump archives (.dump, magic bytes 'PGDMP').
+echo "▶ Restoring backup (this can take several minutes)"
+if head -c 5 "$BACKUP_FILE" | grep -q '^PGDMP'; then
+ echo " → custom-format archive detected, using pg_restore"
+ pg_restore -h 127.0.0.1 -p "$PORT_DB" -U supabase_admin -d postgres \
+ --no-owner --no-privileges \
+ "$BACKUP_FILE" 2> /tmp/restore-errors.log || true
+else
+ # Plain-text SQL: strip PG17 \restrict/\unrestrict so psql isn't sandboxed
+ sed -E '/^\\(restrict|unrestrict)([[:space:]]|$)/d' "$BACKUP_FILE" \
+ | $PSQL_SA -v ON_ERROR_STOP=0 2> /tmp/restore-errors.log
+fi
+err_count=$(grep -ci '^\(pg_restore: \)\?error' /tmp/restore-errors.log || true)
+echo " → /tmp/restore-errors.log ($err_count errors; most are harmless 'already exists' / role permission noise)"
+# Reapply superuser to postgres (the dump's ALTER ROLE strips it).
+$PSQL_SA -c "ALTER ROLE postgres WITH SUPERUSER CREATEROLE CREATEDB LOGIN REPLICATION BYPASSRLS;" \
+ >/dev/null 2>&1 || true
+# Realign pgmq queue sequences with restored max msg_id. The dump COPYs
+# pgmq.q_* rows but doesn't reset the underlying sequences, so the first
+# trigger-fired INSERT after restore collides on the primary key.
+$PSQL_PG -c "
+DO \$\$
+DECLARE r RECORD;
+BEGIN
+ FOR r IN
+ SELECT c.relname
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'pgmq' AND c.relname LIKE 'q\_%' AND c.relkind = 'r'
+ LOOP
+ EXECUTE format(
+ 'SELECT setval(pg_get_serial_sequence(%L, ''msg_id''), GREATEST(1, COALESCE((SELECT max(msg_id) FROM pgmq.%I), 1)))',
+ 'pgmq.' || r.relname, r.relname
+ );
+ END LOOP;
+END \$\$;
+" >/dev/null 2>&1 || true
+# pgmq queue tables restored from a prod DB whose queues predate pgmq >= 1.4 are
+# missing the `headers` column the local pgmq read/send functions write to. This
+# surfaces at runtime as: `column m.headers does not exist` (from pgmq.read/send,
+# e.g. packages/jobs event queue). The dump also omits the pgmq.meta registry
+# rows, so list_queues() comes back empty. Backfill both directly against the
+# restored q_*/a_* tables — idempotent, safe on fresh DBs (no queues → no-op).
+echo "▶ Backfilling pgmq queue headers + meta registry"
+$PSQL_PG -c "
+DO \$\$
+DECLARE t RECORD;
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pgmq') THEN RETURN; END IF;
+ FOR t IN
+ SELECT c.relname
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'pgmq' AND c.relkind = 'r'
+ AND (c.relname LIKE 'q\_%' OR c.relname LIKE 'a\_%')
+ LOOP
+ EXECUTE format('ALTER TABLE pgmq.%I ADD COLUMN IF NOT EXISTS headers JSONB', t.relname);
+ END LOOP;
+END \$\$;
+INSERT INTO pgmq.meta (queue_name, is_partitioned, is_unlogged, created_at)
+SELECT substring(c.relname FROM 3), false, false, now()
+FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+WHERE n.nspname = 'pgmq' AND c.relkind = 'r' AND c.relname LIKE 'q\_%'
+ON CONFLICT (queue_name) DO NOTHING;
+" >/dev/null 2>&1 || true
+# Storage: custom-format dumps DO carry storage.objects/prefixes rows, but
+# the actual file bytes live in prod's storage backend, not in the DB — so
+# those rows would point at files that don't exist locally and downloads
+# would 404. Clear the metadata, keep/create the buckets the app expects.
+echo "▶ Resetting storage metadata + ensuring buckets (fixed + per-company)"
+# Guard each TRUNCATE with to_regclass so a table that doesn't exist in this
+# Supabase version can't abort — and thereby roll back — the whole block.
+$PSQL_SA -v ON_ERROR_STOP=0 -c "
+DO \$\$
+BEGIN
+ IF to_regclass('storage.objects') IS NOT NULL THEN TRUNCATE storage.objects CASCADE; END IF;
+ IF to_regclass('storage.prefixes') IS NOT NULL THEN TRUNCATE storage.prefixes CASCADE; END IF;
+ IF to_regclass('storage.s3_multipart_uploads_parts') IS NOT NULL THEN TRUNCATE storage.s3_multipart_uploads_parts CASCADE; END IF;
+ IF to_regclass('storage.s3_multipart_uploads') IS NOT NULL THEN TRUNCATE storage.s3_multipart_uploads CASCADE; END IF;
+ IF to_regclass('storage.buckets') IS NOT NULL THEN TRUNCATE storage.buckets CASCADE; END IF;
+END \$\$;
+" >/dev/null 2>&1 || true
+# Re-seed buckets in a SEPARATE statement so the TRUNCATE outcome above can never
+# roll it back: the fixed app buckets plus one private bucket per restored
+# company (id = company id), matching the bucket-seeding migrations.
+$PSQL_SA -v ON_ERROR_STOP=0 -c "
+INSERT INTO storage.buckets (id, name, public) VALUES
+ ('public', 'public', true),
+ ('avatars', 'avatars', true),
+ ('private', 'private', false),
+ ('feedback', 'feedback', true),
+ ('company-templates', 'company-templates', false)
+ON CONFLICT (id) DO NOTHING;
+INSERT INTO storage.buckets (id, name, public)
+SELECT id, id, false FROM public.company
+ON CONFLICT (id) DO NOTHING;
+" >/dev/null 2>&1 || true
+BUCKET_COUNT=$($PSQL_PG -At -c "SELECT count(*) FROM storage.buckets;" 2>/dev/null || echo "?")
+echo " ✓ $BUCKET_COUNT storage buckets present (5 fixed + one per company)"
+# ── 4. If ADMIN_EMAIL is set, resolve the user_id ───────────────────────────
+ADMIN_USER_ID=""
+if [[ -n "$ADMIN_EMAIL" ]]; then
+ ADMIN_USER_ID=$($PSQL_PG -At -c "SELECT id FROM public.\"user\" WHERE lower(email) = lower('$ADMIN_EMAIL') LIMIT 1" || true)
+ if [[ -z "$ADMIN_USER_ID" ]]; then
+ echo " ⚠ ADMIN_EMAIL=$ADMIN_EMAIL not found in public.user — skipping access grant"
+ else
+ echo " ✓ Found user $ADMIN_USER_ID for $ADMIN_EMAIL — will upgrade to Admin in existing companies"
+ fi
+fi
+# ── 5. Upgrade admin in user's existing companies ───────────────────────────
+# Scope is intentionally narrow: only the companies the user already
+# belongs to from prod. Granting the user access to all 1000+ tenants
+# blows past PostgREST's statement timeout (RLS array checks on
+# 1300-element arrays + the `employees` view).
+if [[ -n "$ADMIN_USER_ID" ]]; then
+ echo "▶ Upgrading $ADMIN_USER_ID to Admin in their existing companies"
+ $PSQL_PG -v ON_ERROR_STOP=1 -v uid="$ADMIN_USER_ID" -v pw="$ADMIN_PASSWORD" <<'SQL' >/dev/null
+SET session_replication_role = 'replica';
+-- Upgrade (or create) the employee row to Admin in every company the
+-- user belongs to. Falls back to that company's first employeeType
+-- if no Admin type exists; skips companies with no employeeType at all.
+INSERT INTO public.employee (id, "companyId", "employeeTypeId", active)
+SELECT :'uid', uc."companyId",
+ COALESCE(
+ (SELECT et.id FROM public."employeeType" et WHERE et."companyId" = uc."companyId" AND et.name = 'Admin' LIMIT 1),
+ (SELECT et.id FROM public."employeeType" et WHERE et."companyId" = uc."companyId" LIMIT 1)
+ ),
+ true
+FROM public."userToCompany" uc
+WHERE uc."userId" = :'uid'
+ AND EXISTS (SELECT 1 FROM public."employeeType" et WHERE et."companyId" = uc."companyId")
+ON CONFLICT (id, "companyId") DO UPDATE
+ SET "employeeTypeId" = EXCLUDED."employeeTypeId", active = true;
+-- Convert the user into a password-auth-capable account, regardless of
+-- whether they originally signed up via Google / GitHub / etc. Supabase
+-- gates password sign-in on (a) encrypted_password being set, (b) the
+-- account being confirmed, and (c) an auth.identities row with
+-- provider='email'.
+-- confirmed_at is a GENERATED column in newer Supabase (least of
+-- email_confirmed_at, phone_confirmed_at) — set the source instead.
+UPDATE auth.users SET
+ encrypted_password = crypt(:'pw', gen_salt('bf')),
+ email_confirmed_at = COALESCE(email_confirmed_at, now()),
+ aud = COALESCE(NULLIF(aud, ''), 'authenticated'),
+ role = COALESCE(NULLIF(role, ''), 'authenticated'),
+ banned_until = NULL
+WHERE id = :'uid';
+-- Ensure an email-provider identity exists (idempotent).
+-- auth.identities.email is a GENERATED column from identity_data->>'email',
+-- so we don't include it in the column list.
+INSERT INTO auth.identities (id, user_id, provider_id, provider, identity_data, last_sign_in_at, created_at, updated_at)
+SELECT
+ gen_random_uuid(),
+ u.id,
+ u.id::text,
+ 'email',
+ jsonb_build_object('sub', u.id::text, 'email', u.email, 'email_verified', true),
+ now(), now(), now()
+FROM auth.users u
+WHERE u.id = :'uid'
+ AND NOT EXISTS (
+ SELECT 1 FROM auth.identities i WHERE i.user_id = u.id AND i.provider = 'email'
+ );
+-- Permissions are stored flat per-user in public.userPermission as
+-- { "<module>_<action>": ["companyId", ...] } and read at request time
+-- (not from employeeTypePermission). Without this expansion the user
+-- only sees nav modules in the companies their permissions row already
+-- listed — typically just their original prod companies.
+WITH all_companies AS (
+ SELECT jsonb_agg(DISTINCT "companyId") AS ids
+ FROM public."userToCompany"
+ WHERE "userId" = :'uid'
+)
+UPDATE public."userPermission" SET
+ permissions = (
+ SELECT jsonb_object_agg(key, (SELECT ids FROM all_companies))
+ FROM jsonb_object_keys(permissions) AS key
+ )
+WHERE id = :'uid';
+SQL
+ LOGIN_EMAIL=$($PSQL_PG -At -c "SELECT email FROM auth.users WHERE id = '$ADMIN_USER_ID';")
+ COMPANY_COUNT=$($PSQL_PG -At -c "SELECT count(*) FROM public.\"userToCompany\" WHERE \"userId\" = '$ADMIN_USER_ID';")
+ echo " ✓ $ADMIN_USER_ID is Admin in $COMPANY_COUNT companies with full module permissions"
+ echo " ✓ Login as: $LOGIN_EMAIL / $ADMIN_PASSWORD"
+ echo " ℹ If you were already logged in: log OUT and back IN — the permission"
+ echo " cache (Redis: permissions:$ADMIN_USER_ID) is cleared on logout."
+fi
+echo "✅ Done — Studio: http://127.0.0.1:$((PORT_DB+2)) (port_db+2 is the Studio port crbn assigned)"
diff --git a/services/geometry/.gitignore b/services/geometry/.gitignore
new file mode 100644
index 0000000000..20f968f344
--- /dev/null
+++ b/services/geometry/.gitignore
@@ -0,0 +1,7 @@
+.venv/
+__pycache__/
+*.pyc
+*.egg-info/
+.pytest_cache/
+build/
+dist/
diff --git a/services/geometry/Dockerfile b/services/geometry/Dockerfile
new file mode 100644
index 0000000000..87de9ba33b
--- /dev/null
+++ b/services/geometry/Dockerfile
@@ -0,0 +1,32 @@
+# syntax=docker/dockerfile:1
+
+# --- Python dependencies -----------------------------------------------------
+FROM python:3.12-slim-bookworm AS python-deps
+WORKDIR /build
+COPY pyproject.toml ./
+COPY app ./app
+RUN pip install --no-cache-dir --prefix=/opt/python .
+
+# --- Node tooling (gltf-transform for the meshopt compression pass) ----------
+FROM node:20-bookworm-slim AS node-tools
+RUN npm install -g @gltf-transform/[email protected]
+
+# --- Runtime ------------------------------------------------------------------
+FROM python:3.12-slim-bookworm
+
+# Shared libs required by the OCCT (cadquery-ocp) wheel.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ libgl1 libglu1-mesa libxrender1 libxext6 libsm6 libice6 libfontconfig1 \
+ && rm -rf /var/lib/apt/lists/*
+
+# Node 20 runtime + gltf-transform CLI (same Debian base, glibc-compatible).
+COPY --from=node-tools /usr/local/bin/node /usr/local/bin/node
+COPY --from=node-tools /usr/local/lib/node_modules /usr/local/lib/node_modules
+RUN ln -s /usr/local/lib/node_modules/@gltf-transform/cli/bin/cli.js /usr/local/bin/gltf-transform
+
+COPY --from=python-deps /opt/python /usr/local
+
+EXPOSE 8000
+HEALTHCHECK --interval=30s --timeout=5s --start-period=15s \
+ CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=4)"]
+CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
diff --git a/services/geometry/README.md b/services/geometry/README.md
new file mode 100644
index 0000000000..77f741dc33
--- /dev/null
+++ b/services/geometry/README.md
@@ -0,0 +1,90 @@
+# Geometry Service
+
+Stateless Python/FastAPI service that converts STEP files into a meshopt-compressed
+GLB plus a `graph.json` assembly tree with stable node IDs. Consumed by the Inngest
+convert pipeline and `packages/viewer`.
+
+The wire contracts (request/response shapes, `graph.json` schema, stable nodeId
+derivation) are defined in
+[`docs/specs/animated-work-instructions-contracts.md`](../../docs/specs/animated-work-instructions-contracts.md).
+Do not change them here without updating that document and its consumers.
+
+## API
+
+- `GET /health` → `{ "ok": true, "version": "0.1.0" }` (unauthenticated, for load balancers)
+- `POST /convert` → downloads the STEP from a signed GET URL, converts, PUTs the GLB
+ (`model/gltf-binary`) and `graph.json` (`application/json`) to signed URLs, and
+ returns `{ ok, partCount, unit, stats }` synchronously. Errors return
+ `{ ok: false, error, code }` with code in `READ_FAILED | TESSELLATION_FAILED |
+ UPLOAD_FAILED | INVALID_INPUT`.
+
+Options: `linearDeflection` (default 0.1), `angularDeflection` (default 0.5), and
+`compress` (default true; set false to skip the meshopt pass).
+
+Per-part tessellation failures never abort a run: the part gets a bounding-box proxy
+mesh and a note in `stats.warnings`. Only an unreadable STEP fails the request.
+
+## Auth
+
+`Authorization: Bearer <GEOMETRY_SERVICE_API_KEY>` on `/convert`.
+
+| Env var | Behavior |
+| --- | --- |
+| `GEOMETRY_SERVICE_API_KEY` | Shared secret. When set, every `/convert` request must present it as a bearer token. |
+| `GEOMETRY_DEV_MODE` | Only consulted when the API key is **unset**: `true` allows unauthenticated requests (local dev); anything else rejects all requests with 401 (secure default). |
+
+## Local development
+
+Requires Python 3.11+ (the Docker image uses 3.12). The `cadquery-ocp` wheel is
+~70 MB.
+
+```bash
+cd services/geometry
+python3 -m venv .venv
+.venv/bin/pip install -e '.[dev]'
+
+GEOMETRY_DEV_MODE=true .venv/bin/uvicorn app.main:app --reload --port 8000
+```
+
+The meshopt compression pass shells out to `gltf-transform` (Node 20+):
+
+```bash
+npm install -g @gltf-transform/[email protected]
+```
+
+Without it the service logs a warning and serves uncompressed GLBs.
+
+### Tests
+
+```bash
+.venv/bin/pytest
+```
+
+STEP fixtures are generated programmatically (no binary files in the repo) by
+`tests/fixtures/make_fixtures.py`. API/auth tests run even without `cadquery-ocp`;
+conversion tests skip when it is missing, and compression tests skip when
+`gltf-transform` is not on PATH.
+
+## Docker
+
+```bash
+docker build -t carbon-geometry .
+docker run -p 8000:8000 -e GEOMETRY_SERVICE_API_KEY=dev-secret carbon-geometry
+```
+
+The image is multi-stage: Python deps are wheel-installed in a builder stage, and
+Node 20 + `@gltf-transform/cli` are copied into the runtime stage for the
+compression pass. (A docker-compose entry is added in a later task; this service
+has no entry in the repo root compose files yet.)
+
+## Implementation notes
+
+- STEP is read via `STEPCAFControl_Reader` into an XCAF document and the assembly
+ tree is walked through `XCAFDoc_ShapeTool` (names, per-instance transforms,
+ colors via `XCAFDoc_ColorTool`).
+- Geometry is normalized to **mm** (`xstep.cascade.unit = MM`); the source unit is
+ read best-effort from the STEP header and recorded as `sourceUnit`.
+- The GLB is written directly with `pygltflib` from the same tessellated tree as
+ `graph.json` (not `RWGltf_CafWriter`), guaranteeing a 1:1 node mapping so each
+ glTF node's `extras.nodeId` provably matches the graph. Identical parts share one
+ glTF mesh.
diff --git a/services/geometry/app/__init__.py b/services/geometry/app/__init__.py
new file mode 100644
index 0000000000..3dc1f76bc6
--- /dev/null
+++ b/services/geometry/app/__init__.py
@@ -0,0 +1 @@
+__version__ = "0.1.0"
diff --git a/services/geometry/app/auth.py b/services/geometry/app/auth.py
new file mode 100644
index 0000000000..0a6e5bfa7f
--- /dev/null
+++ b/services/geometry/app/auth.py
@@ -0,0 +1,23 @@
+import os
+import secrets
+
+from fastapi import Header, HTTPException
+
+
+def require_auth(authorization: str | None = Header(default=None)) -> None:
+ """Bearer auth against GEOMETRY_SERVICE_API_KEY.
+
+ If the key is unset, requests are allowed only when GEOMETRY_DEV_MODE=true;
+ otherwise everything is rejected (secure default for misconfigured deploys).
+ """
+ api_key = os.environ.get("GEOMETRY_SERVICE_API_KEY")
+ if not api_key:
+ if os.environ.get("GEOMETRY_DEV_MODE") == "true":
+ return
+ raise HTTPException(
+ status_code=401, detail="GEOMETRY_SERVICE_API_KEY is not configured"
+ )
+
+ scheme, _, token = (authorization or "").partition(" ")
+ if scheme.lower() != "bearer" or not secrets.compare_digest(token, api_key):
+ raise HTTPException(status_code=401, detail="Invalid or missing bearer token")
diff --git a/services/geometry/app/config.py b/services/geometry/app/config.py
new file mode 100644
index 0000000000..2902adc1ad
--- /dev/null
+++ b/services/geometry/app/config.py
@@ -0,0 +1,51 @@
+"""Operational limits, configurable via environment variables."""
+
+import os
+
+
+def _int_env(name: str, default: int) -> int:
+ raw = os.environ.get(name, "")
+ try:
+ return int(raw) if raw else default
+ except ValueError:
+ return default
+
+
+def max_source_bytes() -> int:
+ """Maximum size of the source CAD file (default 250 MB)."""
+ return _int_env("GEOMETRY_MAX_SOURCE_MB", 250) * 1024 * 1024
+
+
+def max_parts() -> int:
+ """Maximum leaf part instances in an assembly (default 5000)."""
+ return _int_env("GEOMETRY_MAX_PARTS", 5000)
+
+
+def max_concurrency() -> int:
+ """Maximum concurrent conversions per worker process (default 2)."""
+ return _int_env("GEOMETRY_MAX_CONCURRENCY", 2)
+
+
+def allowed_url_hosts() -> list[str]:
+ """If set, source/output URLs must point at one of these hosts.
+
+ Comma-separated, e.g. "abc.supabase.co". Empty means any host.
+ """
+ raw = os.environ.get("GEOMETRY_ALLOWED_URL_HOSTS", "")
+ return [host.strip().lower() for host in raw.split(",") if host.strip()]
+
+
+def require_https() -> bool:
+ """Require https URLs unless explicitly disabled for local development."""
+ return os.environ.get("GEOMETRY_DEV_MODE", "").lower() != "true"
+
+
+def verify_tls() -> bool:
+ """Verify TLS certificates.
+
+ Disabled in dev mode: local stacks serve storage through a self-signed
+ proxy CA (portless) that recent Python releases reject outright
+ ("Missing Authority Key Identifier"), even when the CA is trusted via
+ SSL_CERT_FILE.
+ """
+ return os.environ.get("GEOMETRY_DEV_MODE", "").lower() != "true"
diff --git a/services/geometry/app/convert.py b/services/geometry/app/convert.py
new file mode 100644
index 0000000000..2ecc628641
--- /dev/null
+++ b/services/geometry/app/convert.py
@@ -0,0 +1,594 @@
+"""STEP -> assembly tree -> GLB + graph.json.
+
+Reads a STEP file into an XCAF document, walks the assembly structure,
+tessellates each unique part once, derives stable nodeIds per the contract in
+docs/specs/animated-work-instructions-contracts.md, and writes a GLB whose node
+tree mirrors graph.json exactly (each glTF node carries extras.nodeId).
+
+The GLB is written directly with pygltflib (app/glb.py) instead of
+RWGltf_CafWriter: writing it ourselves from the same tessellated tree
+guarantees a 1:1, verifiable mapping between graph.json nodes and glTF nodes,
+which is what the nodeId contract depends on.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+from OCP.Bnd import Bnd_Box
+from OCP.BRep import BRep_Tool
+from OCP.BRepBndLib import BRepBndLib
+from OCP.BRepGProp import BRepGProp
+from OCP.BRepMesh import BRepMesh_IncrementalMesh
+from OCP.GProp import GProp_GProps
+from OCP.IFSelect import IFSelect_ReturnStatus
+from OCP.Interface import Interface_Static
+from OCP.Quantity import Quantity_ColorRGBA
+from OCP.STEPCAFControl import STEPCAFControl_Reader
+from OCP.TCollection import TCollection_AsciiString, TCollection_ExtendedString
+from OCP.TDataStd import TDataStd_Name
+from OCP.TDF import TDF_Label, TDF_LabelSequence, TDF_Tool
+from OCP.TDocStd import TDocStd_Document
+from OCP.TopAbs import TopAbs_Orientation, TopAbs_ShapeEnum
+from OCP.TopExp import TopExp_Explorer
+from OCP.TopLoc import TopLoc_Location
+from OCP.TopoDS import TopoDS, TopoDS_Shape
+from OCP.XCAFDoc import XCAFDoc_ColorTool, XCAFDoc_ColorType, XCAFDoc_DocumentTool, XCAFDoc_ShapeTool
+
+from app.errors import ConvertError
+from app.glb import write_glb
+
+GRAPH_VERSION = 1
+OUTPUT_UNIT = "mm"
+IDENTITY_4X4 = [
+ 1.0, 0.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0, 0.0,
+ 0.0, 0.0, 1.0, 0.0,
+ 0.0, 0.0, 0.0, 1.0,
+]
+
+
+@dataclass
+class PartMesh:
+ positions: np.ndarray # (n, 3) float32, part-local coordinates in mm
+ indices: np.ndarray # (m, 3) uint32
+ geometry_hash: str
+ is_proxy: bool = False
+
+
+@dataclass
+class AssemblyNode:
+ name: str
+ product_name: str
+ transform: list[float] # local 4x4, column-major
+ is_assembly: bool
+ mesh: PartMesh | None
+ color: list[float] | None
+ volume: float | None
+ children: list["AssemblyNode"] = field(default_factory=list)
+ node_id: str = ""
+ bbox_min: list[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])
+ bbox_max: list[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])
+
+
+@dataclass
+class ConversionResult:
+ graph: dict
+ component_count: int
+ triangles: int
+ warnings: list[str]
+
+
+def convert_step(
+ step_path: Path,
+ glb_path: Path,
+ linear_deflection: float = 0.1,
+ angular_deflection: float = 0.5,
+ max_parts: int | None = None,
+) -> ConversionResult:
+ """Convert a STEP file to a GLB (at glb_path) plus a graph.json dict."""
+ warnings: list[str] = []
+ doc = _read_step(step_path)
+ source_unit = _detect_source_unit(step_path)
+
+ if max_parts is not None:
+ instances = _count_leaf_instances(doc)
+ if instances > max_parts:
+ raise ConvertError(
+ "LIMIT_EXCEEDED",
+ f"assembly has {instances} part instances; the limit is {max_parts}",
+ 413,
+ )
+
+ try:
+ root = _build_tree(doc, linear_deflection, angular_deflection, warnings)
+ _assign_node_ids(root)
+ _compute_world_bboxes(root, np.eye(4))
+ write_glb(root, glb_path)
+ except ConvertError:
+ raise
+ except Exception as exc: # pragma: no cover - defensive
+ raise ConvertError(
+ "TESSELLATION_FAILED", f"failed to tessellate or export model: {exc}"
+ ) from exc
+
+ component_count = _count_leaves(root)
+ triangles = _count_triangles(root)
+ graph = {
+ "version": GRAPH_VERSION,
+ "unit": OUTPUT_UNIT,
+ "sourceUnit": source_unit,
+ "componentCount": component_count,
+ "root": _node_to_dict(root),
+ }
+ return ConversionResult(
+ graph=graph, component_count=component_count, triangles=triangles, warnings=warnings
+ )
+
+
+# --- STEP reading -----------------------------------------------------------
+
+
+def _read_step(step_path: Path) -> TDocStd_Document:
+ # Normalize geometry to mm regardless of the file's declared unit.
+ Interface_Static.SetCVal_s("xstep.cascade.unit", "MM")
+ reader = STEPCAFControl_Reader()
+ reader.SetColorMode(True)
+ reader.SetNameMode(True)
+ reader.SetLayerMode(False)
+ reader.SetMatMode(False)
+
+ status = reader.ReadFile(str(step_path))
+ if status != IFSelect_ReturnStatus.IFSelect_RetDone:
+ raise ConvertError("READ_FAILED", "could not read STEP file", 422)
+
+ doc = TDocStd_Document(TCollection_ExtendedString("BinXCAF"))
+ if not reader.Transfer(doc):
+ raise ConvertError("READ_FAILED", "STEP transfer to XCAF failed", 422)
+ return doc
+
+
+_UNIT_NAMES = {
+ "INCH": "inch",
+ "FOOT": "foot",
+ "MILE": "mile",
+ "YARD": "yard",
+}
+_SI_PREFIXES = {
+ "MILLI": "mm",
+ "CENTI": "cm",
+ "DECI": "dm",
+ "MICRO": "um",
+ "KILO": "km",
+ "": "m",
+}
+
+
+def _detect_source_unit(step_path: Path) -> str:
+ """Best-effort read of the STEP file's declared length unit (default mm)."""
+ try:
+ text = step_path.read_text(errors="ignore")[: 32 * 1024 * 1024]
+ except OSError:
+ return OUTPUT_UNIT
+ # Statements like: #41=( ... CONVERSION_BASED_UNIT('INCH',#38) LENGTH_UNIT() ... );
+ # or: #41=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );
+ for stmt in re.finditer(r"\(([^;]*?LENGTH_UNIT\(\)[^;]*?)\)\s*;", text, re.S):
+ body = stmt.group(1)
+ m = re.search(r"CONVERSION_BASED_UNIT\s*\(\s*'([^']+)'", body)
+ if m:
+ return _UNIT_NAMES.get(m.group(1).upper(), m.group(1).lower())
+ m = re.search(r"SI_UNIT\s*\(\s*(?:\.(\w+)\.|\$)\s*,\s*\.METRE\.", body)
+ if m:
+ return _SI_PREFIXES.get(m.group(1) or "", "m")
+ return OUTPUT_UNIT
+
+
+# --- XCAF traversal ---------------------------------------------------------
+
+
+def _label_name(label: TDF_Label) -> str:
+ attr = TDataStd_Name()
+ if label.FindAttribute(TDataStd_Name.GetID_s(), attr):
+ return TCollection_AsciiString(attr.Get()).ToCString()
+ return ""
+
+
+def _label_entry(label: TDF_Label) -> str:
+ entry = TCollection_AsciiString()
+ TDF_Tool.Entry_s(label, entry)
+ return entry.ToCString()
+
+
+def _label_color(*labels: TDF_Label) -> list[float] | None:
+ rgba = Quantity_ColorRGBA()
+ for label in labels:
+ if label.IsNull():
+ continue
+ for color_type in (
+ XCAFDoc_ColorType.XCAFDoc_ColorSurf,
+ XCAFDoc_ColorType.XCAFDoc_ColorGen,
+ ):
+ if XCAFDoc_ColorTool.GetColor_s(label, color_type, rgba):
+ rgb = rgba.GetRGB()
+ return [rgb.Red(), rgb.Green(), rgb.Blue(), rgba.Alpha()]
+ return None
+
+
+def _count_leaf_instances(doc: TDocStd_Document) -> int:
+ """Count leaf part instances without tessellating anything.
+
+ Used to reject oversized assemblies before the expensive meshing pass.
+ """
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+
+ def count(product_label: TDF_Label) -> int:
+ if not XCAFDoc_ShapeTool.IsAssembly_s(product_label):
+ return 1
+ components = TDF_LabelSequence()
+ XCAFDoc_ShapeTool.GetComponents_s(product_label, components)
+ total = 0
+ for i in range(1, components.Length() + 1):
+ referred = TDF_Label()
+ if XCAFDoc_ShapeTool.GetReferredShape_s(components.Value(i), referred):
+ total += count(referred)
+ return total
+
+ free_shapes = TDF_LabelSequence()
+ shape_tool.GetFreeShapes(free_shapes)
+ return sum(count(free_shapes.Value(i)) for i in range(1, free_shapes.Length() + 1))
+
+
+def _build_tree(
+ doc: TDocStd_Document,
+ linear_deflection: float,
+ angular_deflection: float,
+ warnings: list[str],
+) -> AssemblyNode:
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+ mesh_cache: dict[str, PartMesh] = {}
+
+ free_shapes = TDF_LabelSequence()
+ shape_tool.GetFreeShapes(free_shapes)
+ if free_shapes.Length() == 0:
+ raise ConvertError("READ_FAILED", "STEP file contains no shapes", 422)
+
+ roots = [
+ _node_from_product(
+ free_shapes.Value(i),
+ instance_label=None,
+ location=None,
+ shape_tool=shape_tool,
+ mesh_cache=mesh_cache,
+ linear_deflection=linear_deflection,
+ angular_deflection=angular_deflection,
+ warnings=warnings,
+ )
+ for i in range(1, free_shapes.Length() + 1)
+ ]
+ if len(roots) == 1:
+ return roots[0]
+ # Multiple free shapes: wrap in a synthetic root so graph.json has one tree.
+ return AssemblyNode(
+ name="ROOT",
+ product_name="ROOT",
+ transform=list(IDENTITY_4X4),
+ is_assembly=True,
+ mesh=None,
+ color=None,
+ volume=None,
+ children=roots,
+ )
+
+
+def _node_from_product(
+ product_label: TDF_Label,
+ instance_label: TDF_Label | None,
+ location: TopLoc_Location | None,
+ shape_tool: XCAFDoc_ShapeTool,
+ mesh_cache: dict[str, PartMesh],
+ linear_deflection: float,
+ angular_deflection: float,
+ warnings: list[str],
+) -> AssemblyNode:
+ # Prefer product names: instance labels frequently carry XCAF auto-names
+ # like "=>[0:1:1:2]" rather than anything meaningful.
+ product_name = _label_name(product_label)
+ instance_name = _label_name(instance_label) if instance_label is not None else ""
+ name = product_name or instance_name
+ transform = (
+ _location_to_column_major(location) if location is not None else list(IDENTITY_4X4)
+ )
+ color_labels = (
+ (instance_label, product_label) if instance_label is not None else (product_label,)
+ )
+ color = _label_color(*color_labels)
+
+ if XCAFDoc_ShapeTool.IsAssembly_s(product_label):
+ components = TDF_LabelSequence()
+ XCAFDoc_ShapeTool.GetComponents_s(product_label, components)
+ children = []
+ for i in range(1, components.Length() + 1):
+ comp = components.Value(i)
+ referred = TDF_Label()
+ if not XCAFDoc_ShapeTool.GetReferredShape_s(comp, referred):
+ warnings.append(
+ f"component {_label_entry(comp)} has no referred shape; skipped"
+ )
+ continue
+ children.append(
+ _node_from_product(
+ referred,
+ instance_label=comp,
+ location=XCAFDoc_ShapeTool.GetLocation_s(comp),
+ shape_tool=shape_tool,
+ mesh_cache=mesh_cache,
+ linear_deflection=linear_deflection,
+ angular_deflection=angular_deflection,
+ warnings=warnings,
+ )
+ )
+ return AssemblyNode(
+ name=name or "ASSEMBLY",
+ product_name=product_name or "ASSEMBLY",
+ transform=transform,
+ is_assembly=True,
+ mesh=None,
+ color=color,
+ volume=None,
+ children=children,
+ )
+
+ shape = XCAFDoc_ShapeTool.GetShape_s(product_label)
+ mesh = _mesh_for_product(
+ product_label,
+ shape,
+ mesh_cache,
+ linear_deflection,
+ angular_deflection,
+ warnings,
+ name or "part",
+ )
+ return AssemblyNode(
+ name=name or "PART",
+ product_name=product_name or "PART",
+ transform=transform,
+ is_assembly=False,
+ mesh=mesh,
+ color=color,
+ volume=_shape_volume(shape, name or "part", warnings),
+ )
+
+
+def _mesh_for_product(
+ product_label: TDF_Label,
+ shape: TopoDS_Shape,
+ mesh_cache: dict[str, PartMesh],
+ linear_deflection: float,
+ angular_deflection: float,
+ warnings: list[str],
+ display_name: str,
+) -> PartMesh:
+ key = _label_entry(product_label)
+ cached = mesh_cache.get(key)
+ if cached is not None:
+ return cached
+
+ try:
+ positions, indices = _tessellate(shape, linear_deflection, angular_deflection)
+ is_proxy = False
+ if len(indices) == 0:
+ raise ValueError("tessellation produced no triangles")
+ except Exception as exc:
+ warnings.append(f"tessellation failed for '{display_name}': {exc}; using bbox proxy")
+ positions, indices = _bbox_proxy_mesh(shape)
+ is_proxy = True
+
+ mesh = PartMesh(
+ positions=positions,
+ indices=indices,
+ geometry_hash=_geometry_hash(positions, indices),
+ is_proxy=is_proxy,
+ )
+ mesh_cache[key] = mesh
+ return mesh
+
+
+# --- Tessellation & measurement ---------------------------------------------
+
+
+def _tessellate(
+ shape: TopoDS_Shape, linear_deflection: float, angular_deflection: float
+) -> tuple[np.ndarray, np.ndarray]:
+ BRepMesh_IncrementalMesh(shape, linear_deflection, False, angular_deflection, True)
+
+ all_positions: list[np.ndarray] = []
+ all_indices: list[np.ndarray] = []
+ offset = 0
+ explorer = TopExp_Explorer(shape, TopAbs_ShapeEnum.TopAbs_FACE)
+ while explorer.More():
+ face = TopoDS.Face_s(explorer.Current())
+ explorer.Next()
+ loc = TopLoc_Location()
+ triangulation = BRep_Tool.Triangulation_s(face, loc)
+ if triangulation is None:
+ continue
+ trsf = loc.Transformation()
+ n_nodes = triangulation.NbNodes()
+ positions = np.empty((n_nodes, 3), dtype=np.float64)
+ for i in range(1, n_nodes + 1):
+ p = triangulation.Node(i).Transformed(trsf)
+ positions[i - 1] = (p.X(), p.Y(), p.Z())
+
+ n_tris = triangulation.NbTriangles()
+ indices = np.empty((n_tris, 3), dtype=np.uint32)
+ reversed_face = face.Orientation() == TopAbs_Orientation.TopAbs_REVERSED
+ for i in range(1, n_tris + 1):
+ a, b, c = triangulation.Triangle(i).Get()
+ indices[i - 1] = (a, c, b) if reversed_face else (a, b, c)
+
+ all_positions.append(positions)
+ all_indices.append(indices - 1 + offset)
+ offset += n_nodes
+
+ if not all_positions:
+ return np.empty((0, 3), dtype=np.float32), np.empty((0, 3), dtype=np.uint32)
+ return (
+ np.concatenate(all_positions).astype(np.float32),
+ np.concatenate(all_indices).astype(np.uint32),
+ )
+
+
+def _bbox_proxy_mesh(shape: TopoDS_Shape) -> tuple[np.ndarray, np.ndarray]:
+ box = Bnd_Box()
+ BRepBndLib.Add_s(shape, box)
+ if box.IsVoid():
+ return np.zeros((0, 3), dtype=np.float32), np.zeros((0, 3), dtype=np.uint32)
+ xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
+ corners = np.array(
+ [
+ [xmin, ymin, zmin], [xmax, ymin, zmin], [xmax, ymax, zmin], [xmin, ymax, zmin],
+ [xmin, ymin, zmax], [xmax, ymin, zmax], [xmax, ymax, zmax], [xmin, ymax, zmax],
+ ],
+ dtype=np.float32,
+ )
+ faces = np.array(
+ [
+ [0, 2, 1], [0, 3, 2], # bottom
+ [4, 5, 6], [4, 6, 7], # top
+ [0, 1, 5], [0, 5, 4], # front
+ [1, 2, 6], [1, 6, 5], # right
+ [2, 3, 7], [2, 7, 6], # back
+ [3, 0, 4], [3, 4, 7], # left
+ ],
+ dtype=np.uint32,
+ )
+ return corners, faces
+
+
+def _shape_volume(shape: TopoDS_Shape, display_name: str, warnings: list[str]) -> float:
+ try:
+ props = GProp_GProps()
+ BRepGProp.VolumeProperties_s(shape, props)
+ volume = props.Mass()
+ if volume > 0:
+ return volume
+ except Exception:
+ pass
+ # Fall back to bbox volume for open shells / failed parts.
+ box = Bnd_Box()
+ BRepBndLib.Add_s(shape, box)
+ if box.IsVoid():
+ warnings.append(f"could not compute volume for '{display_name}'")
+ return 0.0
+ xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
+ warnings.append(f"volume for '{display_name}' approximated from bbox")
+ return max(xmax - xmin, 0.0) * max(ymax - ymin, 0.0) * max(zmax - zmin, 0.0)
+
+
+def _location_to_column_major(location: TopLoc_Location) -> list[float]:
+ t = location.Transformation()
+ return [
+ t.Value(1, 1), t.Value(2, 1), t.Value(3, 1), 0.0,
+ t.Value(1, 2), t.Value(2, 2), t.Value(3, 2), 0.0,
+ t.Value(1, 3), t.Value(2, 3), t.Value(3, 3), 0.0,
+ t.Value(1, 4), t.Value(2, 4), t.Value(3, 4), 1.0,
+ ]
+
+
+# --- Stable node IDs (see contracts doc, section 1) --------------------------
+
+
+def _geometry_hash(positions: np.ndarray, indices: np.ndarray) -> str:
+ quantized = np.round(positions.astype(np.float64) * 1000.0).astype(np.int64)
+ digest = hashlib.sha1()
+ digest.update(quantized.tobytes())
+ digest.update(indices.astype(np.uint32).tobytes())
+ return digest.hexdigest()
+
+
+def _hash_key(node: AssemblyNode) -> str:
+ """Hash component of the nodeId. Assemblies have no geometry, so ''."""
+ return node.mesh.geometry_hash if node.mesh is not None else ""
+
+
+def _node_id(hash_key: str, parent_path: str, sibling_ordinal: int) -> str:
+ raw = f"{hash_key}:{parent_path}:{sibling_ordinal}"
+ return hashlib.sha1(raw.encode("utf-8")).hexdigest()[:16]
+
+
+def _assign_node_ids(root: AssemblyNode) -> None:
+ root.node_id = _node_id(_hash_key(root), "", 0)
+ _assign_child_ids(root, "")
+
+
+def _assign_child_ids(node: AssemblyNode, parent_path: str) -> None:
+ path = f"{parent_path}/{node.product_name}" if parent_path else node.product_name
+ ordinals: dict[str, int] = {}
+ for child in node.children:
+ key = _hash_key(child)
+ ordinal = ordinals.get(key, 0)
+ ordinals[key] = ordinal + 1
+ child.node_id = _node_id(key, path, ordinal)
+ _assign_child_ids(child, path)
+
+
+# --- World-space bounding boxes ----------------------------------------------
+
+
+def _compute_world_bboxes(node: AssemblyNode, parent_world: np.ndarray) -> None:
+ local = np.asarray(node.transform, dtype=np.float64).reshape(4, 4).T
+ world = parent_world @ local
+
+ if node.mesh is not None and len(node.mesh.positions) > 0:
+ positions = node.mesh.positions.astype(np.float64)
+ transformed = positions @ world[:3, :3].T + world[:3, 3]
+ node.bbox_min = transformed.min(axis=0).tolist()
+ node.bbox_max = transformed.max(axis=0).tolist()
+ else:
+ origin = world[:3, 3].tolist()
+ node.bbox_min = list(origin)
+ node.bbox_max = list(origin)
+
+ for child in node.children:
+ _compute_world_bboxes(child, world)
+
+ if node.children:
+ mins = np.array([c.bbox_min for c in node.children])
+ maxs = np.array([c.bbox_max for c in node.children])
+ if node.mesh is not None and len(node.mesh.positions) > 0:
+ mins = np.vstack([mins, node.bbox_min])
+ maxs = np.vstack([maxs, node.bbox_max])
+ node.bbox_min = mins.min(axis=0).tolist()
+ node.bbox_max = maxs.max(axis=0).tolist()
+
+
+# --- graph.json --------------------------------------------------------------
+
+
+def _count_leaves(node: AssemblyNode) -> int:
+ if not node.is_assembly:
+ return 1
+ return sum(_count_leaves(c) for c in node.children)
+
+
+def _count_triangles(node: AssemblyNode) -> int:
+ own = len(node.mesh.indices) if node.mesh is not None else 0
+ return own + sum(_count_triangles(c) for c in node.children)
+
+
+def _node_to_dict(node: AssemblyNode) -> dict:
+ return {
+ "nodeId": node.node_id,
+ "name": node.name,
+ "isAssembly": node.is_assembly,
+ "geometryHash": node.mesh.geometry_hash if node.mesh is not None else None,
+ "transform": node.transform,
+ "bbox": {"min": node.bbox_min, "max": node.bbox_max},
+ "volume": node.volume if not node.is_assembly else None,
+ "color": node.color,
+ "children": [_node_to_dict(c) for c in node.children],
+ }
diff --git a/services/geometry/app/errors.py b/services/geometry/app/errors.py
new file mode 100644
index 0000000000..bd2c584fdc
--- /dev/null
+++ b/services/geometry/app/errors.py
@@ -0,0 +1,18 @@
+from typing import Literal
+
+ErrorCode = Literal[
+ "READ_FAILED",
+ "TESSELLATION_FAILED",
+ "UPLOAD_FAILED",
+ "INVALID_INPUT",
+ "LIMIT_EXCEEDED",
+ "BUSY",
+]
+
+
+class ConvertError(Exception):
+ def __init__(self, code: ErrorCode, message: str, status_code: int = 500) -> None:
+ super().__init__(message)
+ self.code: ErrorCode = code
+ self.message = message
+ self.status_code = status_code
diff --git a/services/geometry/app/glb.py b/services/geometry/app/glb.py
new file mode 100644
index 0000000000..b35d90eb01
--- /dev/null
+++ b/services/geometry/app/glb.py
@@ -0,0 +1,180 @@
+"""Write a GLB from the tessellated assembly tree with pygltflib.
+
+The glTF node hierarchy mirrors graph.json one-to-one and every node carries
+extras.nodeId, so the viewer can address parts by stable ID. Identical parts
+(same geometryHash) share a single glTF mesh. Coordinates are millimeters, the
+unit the contracts fix for both GLB and graph.json.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import numpy as np
+from pygltflib import (
+ ARRAY_BUFFER,
+ ELEMENT_ARRAY_BUFFER,
+ FLOAT,
+ GLTF2,
+ UNSIGNED_INT,
+ Accessor,
+ Asset,
+ Attributes,
+ Buffer,
+ BufferView,
+ Material,
+ Mesh,
+ Node,
+ PbrMetallicRoughness,
+ Primitive,
+ Scene,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from app.convert import AssemblyNode, PartMesh
+
+DEFAULT_COLOR = (0.65, 0.65, 0.65, 1.0)
+IDENTITY = (
+ 1.0, 0.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0, 0.0,
+ 0.0, 0.0, 1.0, 0.0,
+ 0.0, 0.0, 0.0, 1.0,
+)
+
+
+class _GlbBuilder:
+ def __init__(self) -> None:
+ self.gltf = GLTF2(
+ asset=Asset(version="2.0", generator="carbon-geometry"),
+ scene=0,
+ scenes=[Scene(nodes=[])],
+ )
+ self.blob = bytearray()
+ self.mesh_by_hash: dict[str, int] = {}
+ self.material_by_color: dict[tuple[float, ...], int] = {}
+
+ def _append_buffer_view(self, data: bytes, target: int) -> int:
+ while len(self.blob) % 4:
+ self.blob.append(0)
+ offset = len(self.blob)
+ self.blob.extend(data)
+ self.gltf.bufferViews.append(
+ BufferView(buffer=0, byteOffset=offset, byteLength=len(data), target=target)
+ )
+ return len(self.gltf.bufferViews) - 1
+
+ def _material(self, color: list[float] | None) -> int:
+ rgba = tuple(color) if color is not None else DEFAULT_COLOR
+ index = self.material_by_color.get(rgba)
+ if index is not None:
+ return index
+ material = Material(
+ pbrMetallicRoughness=PbrMetallicRoughness(
+ baseColorFactor=list(rgba), metallicFactor=0.1, roughnessFactor=0.8
+ ),
+ alphaMode="BLEND" if rgba[3] < 1.0 else "OPAQUE",
+ doubleSided=False,
+ )
+ self.gltf.materials.append(material)
+ index = len(self.gltf.materials) - 1
+ self.material_by_color[rgba] = index
+ return index
+
+ def _mesh(self, part: PartMesh, color: list[float] | None, name: str) -> int:
+ index = self.mesh_by_hash.get(part.geometry_hash)
+ if index is not None:
+ return index
+
+ positions = np.ascontiguousarray(part.positions, dtype=np.float32)
+ indices = np.ascontiguousarray(part.indices, dtype=np.uint32).reshape(-1)
+ normals = _vertex_normals(positions, part.indices)
+
+ position_view = self._append_buffer_view(positions.tobytes(), ARRAY_BUFFER)
+ normal_view = self._append_buffer_view(normals.tobytes(), ARRAY_BUFFER)
+ index_view = self._append_buffer_view(indices.tobytes(), ELEMENT_ARRAY_BUFFER)
+
+ accessors = self.gltf.accessors
+ accessors.append(
+ Accessor(
+ bufferView=position_view,
+ componentType=FLOAT,
+ count=len(positions),
+ type="VEC3",
+ min=positions.min(axis=0).tolist(),
+ max=positions.max(axis=0).tolist(),
+ )
+ )
+ position_accessor = len(accessors) - 1
+ accessors.append(
+ Accessor(
+ bufferView=normal_view,
+ componentType=FLOAT,
+ count=len(normals),
+ type="VEC3",
+ )
+ )
+ normal_accessor = len(accessors) - 1
+ accessors.append(
+ Accessor(
+ bufferView=index_view,
+ componentType=UNSIGNED_INT,
+ count=len(indices),
+ type="SCALAR",
+ )
+ )
+ index_accessor = len(accessors) - 1
+
+ self.gltf.meshes.append(
+ Mesh(
+ name=name,
+ primitives=[
+ Primitive(
+ attributes=Attributes(
+ POSITION=position_accessor, NORMAL=normal_accessor
+ ),
+ indices=index_accessor,
+ material=self._material(color),
+ )
+ ],
+ )
+ )
+ index = len(self.gltf.meshes) - 1
+ self.mesh_by_hash[part.geometry_hash] = index
+ return index
+
+ def add_node(self, node: AssemblyNode) -> int:
+ gltf_node = Node(name=node.name, extras={"nodeId": node.node_id})
+ if tuple(node.transform) != IDENTITY:
+ gltf_node.matrix = list(node.transform)
+ if node.mesh is not None and len(node.mesh.positions) > 0:
+ gltf_node.mesh = self._mesh(node.mesh, node.color, node.product_name)
+ self.gltf.nodes.append(gltf_node)
+ index = len(self.gltf.nodes) - 1
+ children = [self.add_node(child) for child in node.children]
+ if children:
+ gltf_node.children = children
+ return index
+
+
+def write_glb(root: AssemblyNode, path: Path) -> None:
+ builder = _GlbBuilder()
+ root_index = builder.add_node(root)
+ builder.gltf.scenes[0].nodes = [root_index]
+ if builder.blob:
+ builder.gltf.buffers = [Buffer(byteLength=len(builder.blob))]
+ builder.gltf.set_binary_blob(bytes(builder.blob))
+ builder.gltf.save_binary(str(path))
+
+
+def _vertex_normals(positions: np.ndarray, indices: np.ndarray) -> np.ndarray:
+ """Area-weighted smooth vertex normals."""
+ normals = np.zeros(positions.shape, dtype=np.float64)
+ tris = positions[indices].astype(np.float64) # (m, 3, 3)
+ face_normals = np.cross(tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0])
+ for corner in range(3):
+ np.add.at(normals, indices[:, corner], face_normals)
+ lengths = np.linalg.norm(normals, axis=1, keepdims=True)
+ lengths[lengths == 0.0] = 1.0
+ return (normals / lengths).astype(np.float32)
diff --git a/services/geometry/app/main.py b/services/geometry/app/main.py
new file mode 100644
index 0000000000..b91bc4b013
--- /dev/null
+++ b/services/geometry/app/main.py
@@ -0,0 +1,354 @@
+"""FastAPI entrypoint for the Carbon geometry service.
+
+Wire format is defined in docs/specs/animated-work-instructions-contracts.md.
+"""
+
+import json
+import logging
+import shutil
+import tempfile
+import threading
+import time
+from pathlib import Path
+from urllib.parse import urlparse
+
+import httpx
+from fastapi import Depends, FastAPI, Request
+from fastapi.exceptions import RequestValidationError
+from fastapi.responses import JSONResponse
+
+from app import __version__, config
+from app.auth import require_auth
+from app.errors import ConvertError
+from app.schemas import (
+ ConvertRequest,
+ ConvertResponse,
+ ConvertStats,
+ HealthResponse,
+ PlanOptions,
+ PlanRequest,
+ PlanStartResponse,
+ PlanStats,
+ PlanStatusResponse,
+)
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger("geometry")
+
+HTTP_TIMEOUT_S = 120.0
+
+_conversion_slots = threading.BoundedSemaphore(config.max_concurrency())
+
+app = FastAPI(title="carbon-geometry", version=__version__)
+
+
[email protected]_handler(ConvertError)
+async def convert_error_handler(_: Request, exc: ConvertError) -> JSONResponse:
+ return JSONResponse(
+ status_code=exc.status_code,
+ content={"ok": False, "error": exc.message, "code": exc.code},
+ )
+
+
[email protected]_handler(RequestValidationError)
+async def validation_error_handler(
+ _: Request, exc: RequestValidationError
+) -> JSONResponse:
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": str(exc.errors()), "code": "INVALID_INPUT"},
+ )
+
+
[email protected]("/health", response_model=HealthResponse)
+def health() -> HealthResponse:
+ return HealthResponse(version=__version__)
+
+
[email protected]("/convert", response_model=ConvertResponse, dependencies=[Depends(require_auth)])
+def convert(request: ConvertRequest) -> ConvertResponse:
+ # OCP import is deferred so the API (auth, validation, /health) works in
+ # environments without the OCCT wheel (and fails with a clear error here).
+ try:
+ from app.convert import convert_step
+ except ImportError as exc:
+ raise ConvertError(
+ "TESSELLATION_FAILED", f"OCCT bindings unavailable: {exc}"
+ ) from exc
+ from app.optimize import compress_glb
+
+ for url in (
+ request.source.url,
+ request.outputs.glb.url,
+ request.outputs.graph.url,
+ ):
+ _validate_url(url)
+
+ if not _conversion_slots.acquire(blocking=False):
+ raise ConvertError("BUSY", "all conversion slots are in use; retry later", 429)
+
+ started = time.monotonic()
+ logger.info("[%s] convert start: %s", request.jobId, request.source.format)
+
+ try:
+ with tempfile.TemporaryDirectory(prefix="geometry-") as tmp:
+ tmp_dir = Path(tmp)
+ step_path = tmp_dir / "source.step"
+ glb_path = tmp_dir / "model.glb"
+ _download(request.source.url, step_path)
+
+ result = convert_step(
+ step_path,
+ glb_path,
+ linear_deflection=request.options.linearDeflection,
+ angular_deflection=request.options.angularDeflection,
+ max_parts=config.max_parts(),
+ )
+
+ if request.options.compress:
+ compressed_path = tmp_dir / "model.meshopt.glb"
+ if compress_glb(glb_path, compressed_path):
+ glb_path = compressed_path
+ else:
+ result.warnings.append(
+ "meshopt compression unavailable; GLB is uncompressed"
+ )
+
+ _upload(
+ request.outputs.glb.url, glb_path.read_bytes(), "model/gltf-binary"
+ )
+ _upload(
+ request.outputs.graph.url,
+ json.dumps(result.graph).encode("utf-8"),
+ "application/json",
+ )
+ finally:
+ _conversion_slots.release()
+
+ convert_ms = int((time.monotonic() - started) * 1000)
+ logger.info(
+ "[%s] convert done: %d parts, %d triangles, %dms",
+ request.jobId,
+ result.component_count,
+ result.triangles,
+ convert_ms,
+ )
+ return ConvertResponse(
+ componentCount=result.component_count,
+ unit=result.graph["unit"],
+ stats=ConvertStats(
+ convertMs=convert_ms,
+ meshTriangles=result.triangles,
+ warnings=result.warnings,
+ ),
+ )
+
+
+# --- Async plan jobs -----------------------------------------------------
+# Planning runs in a background thread keyed by jobId; the caller polls
+# GET /plan/{jobId}. Jobs live in-process (dev-scale) — a service restart drops
+# them and the caller re-submits. Slots are held only while a job runs, so
+# submissions queue rather than 429 when both slots are busy.
+_plan_jobs: dict[str, dict] = {}
+_plan_jobs_lock = threading.Lock()
+_PLAN_JOB_TTL_S = 60 * 60
+
+
+def _plan_job_get(job_id: str) -> dict | None:
+ with _plan_jobs_lock:
+ job = _plan_jobs.get(job_id)
+ return dict(job) if job else None
+
+
+def _plan_job_set(job_id: str, **fields: object) -> None:
+ with _plan_jobs_lock:
+ job = _plan_jobs.setdefault(job_id, {})
+ job.update(fields)
+ job["updatedAt"] = time.time()
+
+
+def _plan_jobs_prune() -> None:
+ cutoff = time.time() - _PLAN_JOB_TTL_S
+ with _plan_jobs_lock:
+ for key in [
+ k for k, v in _plan_jobs.items() if v.get("updatedAt", 0.0) < cutoff
+ ]:
+ _plan_jobs.pop(key, None)
+
+
+def _run_plan_job(job_id: str, source_url: str, options: PlanOptions) -> None:
+ from app.plan import plan_step
+
+ _conversion_slots.acquire()
+ tmp = tempfile.mkdtemp(prefix="geometry-")
+ started = time.monotonic()
+ logger.info("[%s] plan start: step", job_id)
+ try:
+ _plan_job_set(job_id, status="running")
+ step_path = Path(tmp) / "source.step"
+ _download(source_url, step_path)
+
+ result = plan_step(
+ step_path,
+ linear_deflection=options.linearDeflection,
+ angular_deflection=options.angularDeflection,
+ clearance=options.clearance,
+ path_samples=options.pathSamples,
+ max_parts=config.max_parts(),
+ units=(
+ [u.model_dump() for u in options.units] if options.units else None
+ ),
+ sequence=options.sequence,
+ )
+
+ plan_ms = int((time.monotonic() - started) * 1000)
+ logger.info(
+ "[%s] plan done: %d/%d parts planned, tiers=%s, %dms",
+ job_id,
+ result.planned_count,
+ result.component_count,
+ result.tiers,
+ plan_ms,
+ )
+ _plan_job_set(
+ job_id,
+ status="done",
+ plan=result.plan,
+ componentCount=result.component_count,
+ plannedCount=result.planned_count,
+ stats={
+ "planMs": plan_ms,
+ "tiers": result.tiers,
+ "warnings": result.warnings,
+ "verifiedCount": result.verified_count,
+ },
+ )
+ except ConvertError as exc:
+ logger.exception("[%s] plan failed", job_id)
+ _plan_job_set(job_id, status="error", error=exc.message)
+ except Exception as exc: # noqa: BLE001 - surface any planner failure to caller
+ logger.exception("[%s] plan failed", job_id)
+ _plan_job_set(job_id, status="error", error=str(exc))
+ finally:
+ _conversion_slots.release()
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
+ "/plan",
+ status_code=202,
+ response_model=PlanStartResponse,
+ dependencies=[Depends(require_auth)],
+)
+def plan(request: PlanRequest) -> PlanStartResponse:
+ try:
+ from app.plan import plan_step # noqa: F401 - fail fast if deps missing
+ except ImportError as exc:
+ raise ConvertError(
+ "TESSELLATION_FAILED", f"planner dependencies unavailable: {exc}"
+ ) from exc
+
+ _validate_url(request.source.url)
+
+ _plan_jobs_prune()
+ job_id = request.jobId
+ with _plan_jobs_lock:
+ existing = _plan_jobs.get(job_id)
+ if existing and existing.get("status") in ("pending", "running"):
+ # Idempotent: a duplicate submit (e.g. an Inngest retry) attaches to
+ # the run already in flight rather than starting a second planner.
+ return PlanStartResponse(jobId=job_id, status=str(existing["status"]))
+ _plan_jobs[job_id] = {"status": "pending", "updatedAt": time.time()}
+
+ threading.Thread(
+ target=_run_plan_job,
+ args=(job_id, request.source.url, request.options),
+ daemon=True,
+ ).start()
+ return PlanStartResponse(jobId=job_id, status="pending")
+
+
+ "/plan/{job_id}",
+ response_model=PlanStatusResponse,
+ dependencies=[Depends(require_auth)],
+)
+def plan_status(job_id: str) -> PlanStatusResponse:
+ job = _plan_job_get(job_id)
+ if job is None:
+ raise ConvertError("NOT_FOUND", f"no plan job {job_id}", 404)
+ status = str(job["status"])
+ if status == "done":
+ return PlanStatusResponse(
+ status="done",
+ plan=job["plan"],
+ componentCount=job["componentCount"],
+ plannedCount=job["plannedCount"],
+ stats=PlanStats(**job["stats"]),
+ )
+ if status == "error":
+ return PlanStatusResponse(status="error", error=job.get("error"))
+ return PlanStatusResponse(status=status)
+
+
+def _validate_url(url: str) -> None:
+ parsed = urlparse(url)
+ if config.require_https() and parsed.scheme != "https":
+ raise ConvertError("INVALID_INPUT", "URLs must use https", 400)
+ if parsed.scheme not in ("http", "https"):
+ raise ConvertError("INVALID_INPUT", f"unsupported URL scheme: {parsed.scheme}", 400)
+ allowed = config.allowed_url_hosts()
+ if allowed and (parsed.hostname or "").lower() not in allowed:
+ raise ConvertError("INVALID_INPUT", "URL host is not allowed", 400)
+
+
+def _download(url: str, destination: Path) -> None:
+ limit = config.max_source_bytes()
+ try:
+ with httpx.Client(
+ timeout=HTTP_TIMEOUT_S,
+ follow_redirects=True,
+ verify=config.verify_tls(),
+ ) as client:
+ with client.stream("GET", url) as response:
+ response.raise_for_status()
+ declared = response.headers.get("Content-Length")
+ if declared and int(declared) > limit:
+ raise ConvertError(
+ "LIMIT_EXCEEDED", "source file exceeds the size limit", 413
+ )
+ received = 0
+ with destination.open("wb") as out:
+ for chunk in response.iter_bytes():
+ received += len(chunk)
+ if received > limit:
+ raise ConvertError(
+ "LIMIT_EXCEEDED",
+ "source file exceeds the size limit",
+ 413,
+ )
+ out.write(chunk)
+ except httpx.HTTPError as exc:
+ raise ConvertError("READ_FAILED", f"could not download source: {exc}", 422) from exc
+
+
+def _upload(url: str, body: bytes, content_type: str) -> None:
+ try:
+ with httpx.Client(timeout=HTTP_TIMEOUT_S, verify=config.verify_tls()) as client:
+ response = client.put(
+ url,
+ content=body,
+ # Retried jobs re-upload to the same path; without upsert the
+ # storage API rejects the second attempt with a 400
+ headers={"Content-Type": content_type, "x-upsert": "true"},
+ )
+ response.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ detail = exc.response.text[:200] if exc.response is not None else ""
+ raise ConvertError(
+ "UPLOAD_FAILED",
+ f"could not upload artifact: {exc} {detail}".strip(),
+ 502,
+ ) from exc
+ except httpx.HTTPError as exc:
+ raise ConvertError("UPLOAD_FAILED", f"could not upload artifact: {exc}", 502) from exc
diff --git a/services/geometry/app/optimize.py b/services/geometry/app/optimize.py
new file mode 100644
index 0000000000..110b08ce17
--- /dev/null
+++ b/services/geometry/app/optimize.py
@@ -0,0 +1,41 @@
+"""Meshopt compression via the @gltf-transform/cli Node tool.
+
+gltf-transform preserves node extras (verified in tests), so the stamped
+nodeIds survive compression. If the CLI is unavailable or fails, the caller
+falls back to the uncompressed GLB.
+"""
+
+import logging
+import subprocess
+from pathlib import Path
+
+logger = logging.getLogger("geometry.optimize")
+
+COMPRESS_TIMEOUT_S = 600
+
+
+def compress_glb(source: Path, destination: Path) -> bool:
+ """Run `gltf-transform meshopt` (quantize + EXT_meshopt_compression).
+
+ The broader `optimize` command is deliberately not used: its join/flatten/
+ dedup passes restructure the node graph, which would break the per-instance
+ extras.nodeId contract. `meshopt` compresses geometry only.
+ """
+ command = ["gltf-transform", "meshopt", str(source), str(destination)]
+ try:
+ result = subprocess.run(
+ command, capture_output=True, text=True, timeout=COMPRESS_TIMEOUT_S
+ )
+ except FileNotFoundError:
+ logger.warning("gltf-transform CLI not found; serving uncompressed GLB")
+ return False
+ except subprocess.TimeoutExpired:
+ logger.warning("gltf-transform timed out; serving uncompressed GLB")
+ return False
+
+ if result.returncode != 0 or not destination.exists():
+ logger.warning(
+ "gltf-transform failed (exit %s): %s", result.returncode, result.stderr.strip()
+ )
+ return False
+ return True
diff --git a/services/geometry/app/plan.py b/services/geometry/app/plan.py
new file mode 100644
index 0000000000..c03e090fae
--- /dev/null
+++ b/services/geometry/app/plan.py
@@ -0,0 +1,4103 @@
+"""Assembly-by-disassembly motion planner.
+
+Computes a collision-free removal motion for every leaf part plus a greedy
+assembly sequence (see .ai/specs/2026-07-04-animated-work-instructions-contracts.md,
+POST /plan). The same STEP source is re-tessellated with the same nodeId
+derivation as /convert, so plan.json keys join against graph.json and the
+GLB extras.
+
+Pipeline (per .ai/research/animated-work-instructions.md):
+- Classify: named fasteners get their symmetry axis and their threaded
+ mates (parts they deeply interpenetrate at the seated pose — a solid
+ screw model geometrically interferes with its nut/tapped hole even
+ though it unscrews in reality). Collision checks along the fastener's
+ own axis ignore contacts with those mates ONLY — there is no blanket
+ penetration allowance, so thin blockers can never be tunneled through.
+ Sandwiched thin parts (gaskets, seals — seated contact on BOTH sides
+ along one axis) similarly exchange a seated-interference allowance with
+ their flanges: the observed compressed squish never reads as a blocking
+ collision, and they never rigid-merge into a flange.
+- Merge: non-threaded pairs that deeply interpenetrate when seated
+ (embedded logo solids, press fits) can never separate by rigid motion;
+ they plan as one rigid unit and members record `mergedInto`.
+- Tier 1: greedy disassembly testing straight-line candidate directions
+ (the part's symmetry axis first, then world axes; named fasteners only
+ ever exit along their bore axis). A path is clear when densely sampled
+ collision checks stay within a small surface-contact tolerance.
+- Tier 2: two-segment "L" motions (lift then slide) for tier-1 failures.
+- Tier 3: adaptive multi-segment escape search (BFS over axis-aligned
+ hops, each hop as far as the free space allows). Emits a multi-segment
+ "L" motion.
+- Flagged: when no collision-free escape exists the part keeps motion
+ "none" with its blockers recorded — the viewer fades it in at the
+ seated pose. The planner never fabricates a motion through geometry.
+
+Only the base part (the last one standing in the greedy disassembly, the
+first in the assembly sequence) keeps motion "none" with no flag — it is
+placed, not inserted.
+
+The recorded motion is the INSERTION motion (removal reversed), matching
+the viewer contract.
+"""
+
+from __future__ import annotations
+
+import re
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+from app.convert import (
+ AssemblyNode,
+ _assign_node_ids,
+ _build_tree,
+ _compute_world_bboxes,
+ _read_step,
+)
+from app.errors import ConvertError
+
+PLAN_VERSION = 3
+OUTPUT_UNIT = "mm"
+
+# Allowed surface penetration (mm) along a removal path. Parts in contact at
+# the seated pose report hairline collisions; sliding fits (pin in bore)
+# stay in surface contact for most of their travel. Collision truth is only
+# as sharp as the mesh: two mating curved surfaces tessellated at linear
+# deflection d can read up to ~2d of phantom penetration, so the effective
+# tolerance scales with the deflection used to mesh the model.
+PENETRATION_TOLERANCE_MM = 0.15
+
+
+def _mesh_tolerance(linear_deflection: float) -> float:
+ return max(PENETRATION_TOLERANCE_MM, 2.5 * float(linear_deflection))
+
+# Margin (mm) past the assembly bounds before a part counts as "out".
+EXIT_MARGIN_MM = 5.0
+
+# Densify sampling on long paths: never step more than this between
+# collision checks, or thin features (washers, flanges) slip between
+# samples and produce false "removable" results that scramble the sequence.
+MAX_SAMPLE_SPACING_MM = 2.0
+MAX_PATH_SAMPLES = 400
+
+# Seated interpenetration deeper than this marks a threaded mate for a
+# fastener: solid screw models interfere with their nuts/tapped holes by
+# roughly the thread depth. While the fastener travels along its own axis,
+# contacts with the mate are allowed up to the seated depth plus a margin
+# (the steady thread interference); every other contact is judged by the
+# strict tolerance, so nothing can tunnel through thin blockers.
+MATE_MIN_DEPTH_MM = 0.2
+MATE_DEPTH_MARGIN_MM = 0.3
+
+# Ordering adjacency: two parts "mate" when their meshes come within this
+# distance at the seated pose. Colliding pairs (pair_depths) are adjacent by
+# definition; this tolerance additionally captures real CAD clearances — an
+# SMD chip floats ~0.05mm above its pads, a clearance-fit boss sits ~0.2mm
+# from its pocket — which a penetration-only contact model cannot see. Used
+# ONLY for ordering (base selection, connected-growth constraint), never for
+# collision truth.
+ORDERING_CONTACT_MM = 0.5
+# AABB-prefiltered candidate pairs beyond this budget skip the exact distance
+# query and count as adjacent from the bbox overlap alone. Degrading to MORE
+# adjacency only weakens the connectivity constraint (extra candidate picks);
+# it can never wrongly block a part.
+MAX_ADJACENCY_DISTANCE_PAIRS = 20000
+
+EMPTY_SET: frozenset = frozenset()
+
+# A thin part whose seated contacts press from BOTH sides along one axis
+# (gasket, seal, shim) is sandwiched: it assembles after one flange and
+# before the one that compresses it. Its seated interference is compliant
+# squish — allowed during separation exactly like thread interference on a
+# fastener (and like thread mates, ONLY along the sandwich axis) — and it
+# must never rigid-merge into a flange. The gates are strict because a
+# false positive corrupts collision truth: thickness along the sandwich
+# axis is capped both relative to the part's largest extent AND absolutely
+# (gaskets are thin in millimeters, not just in proportion — a 33mm plate
+# in a long assembly is not a seal), every partner's dominant contact
+# normal must share the axis, and the observed interference must be
+# squish-scale (real gaskets compress a few tenths; a 10mm bite is a
+# press fit or broken CAD, never a compliance allowance).
+SANDWICH_MAX_THICKNESS_RATIO = 0.3
+SANDWICH_MAX_THICKNESS_MM = 6.0
+SANDWICH_AXIS_ALIGNMENT = 0.9
+SANDWICH_MAX_SQUISH_MM = 0.6
+
+# Rigid merging is evidence-based, never depth-based: coincident duplicate
+# shells (containment-grade bbox overlap + full-rank contact-normal tensor)
+# and fully-embedded solids (containment test — they produce NO surface
+# contacts). Deep local interpenetration alone is NOT a merge signal: a
+# spring plunger embeds millimeters into its detent yet must stay separate.
+
+# "pin" is deliberately absent: on real CAD it names connector pins, pin
+# headers, and pin COUNTS ("Electronics Box - 36 Pin") far more often than
+# hardware — a dowel pin still matches via "dowel". Plurals match too:
+# catalog names run "…Self Tapping Screws".
+FASTENER_NAME_RE = re.compile(
+ r"(?i)\b(screw|bolt|nut|washer|rivet|stud|dowel)s?\b"
+ r"|\bM\d+(x[\d.]+)?\b"
+ r"|\bDIN ?\d+|\bISO ?\d+"
+)
+# A fastener is SMALL — relative to its assembly AND in absolute terms.
+# A name-matched part bigger than BOTH bounds (a rail with a spec-suffixed
+# name, a housing) keeps its structural role: misclassifying structure as
+# hardware fronts it in removal priority, grants it bore exemptions, and
+# bars it from being the base. The absolute floor keeps tiny two-part
+# fixtures honest (a bolt IS a third of a 3-part test assembly).
+MAX_FASTENER_DIAGONAL_FRACTION = 0.35
+MAX_FASTENER_EXTENT_MM = 100.0
+
+# Tier-3 escape search bounds: BFS over axis-aligned hops. Each expansion
+# costs dense collision sampling, so the search is tightly capped.
+MAX_ESCAPE_SEGMENTS = 3
+MAX_ESCAPE_EXPANSIONS = 24
+# A hop must move the part at least this fraction of its own diagonal to
+# count as progress (avoids micro-hops that explode the search space).
+MIN_HOP_FRACTION = 0.25
+
+# Subassembly extraction bounds (stuck states only): interlocked parts —
+# a keyed hub, a slider with its captive lock — often remove cleanly as a
+# unit. Candidate groups grow from a seed part through a PROXIMITY graph
+# (inflated bboxes): clearance fits produce no surface contacts, so a
+# contact graph would miss exactly the relationships that interlock.
+MAX_GROUP_SIZE = 4
+MAX_GROUP_TESTS = 40
+GROUP_PROXIMITY_MM = 2.0
+
+
+def _is_fastener(part: "_Component") -> bool:
+ return bool(FASTENER_NAME_RE.search(part.name or ""))
+
+WORLD_AXES = [
+ np.array([0.0, 0.0, 1.0]),
+ np.array([0.0, 0.0, -1.0]),
+ np.array([1.0, 0.0, 0.0]),
+ np.array([-1.0, 0.0, 0.0]),
+ np.array([0.0, 1.0, 0.0]),
+ np.array([0.0, -1.0, 0.0]),
+]
+
+
+@dataclass
+class _Component:
+ node_id: str
+ name: str
+ mesh: "object" # trimesh.Trimesh, world space
+ bbox_min: np.ndarray
+ bbox_max: np.ndarray
+ is_proxy: bool
+ # Seated contact normals with neighbors — the natural separation
+ # directions (filled by _plan_parts from the seated broadphase pass)
+ contact_normals: list = field(default_factory=list)
+ # Seated-interference allowances with sandwich partners (nodeId → mm),
+ # each valid ONLY along its axis in seated_allowance_axes (nodeId →
+ # unit vector). A compliant part's squish against its flanges, granted
+ # during sweeps like thread interference on a fastener — and like
+ # thread mates, axis-gated so lateral motion is judged strictly
+ # (filled by _sandwiched_parts)
+ seated_allowance: dict = field(default_factory=dict)
+ seated_allowance_axes: dict = field(default_factory=dict)
+
+
+@dataclass
+class _FastenerInfo:
+ """A classified fastener: its insertion axis and its threaded mates.
+
+ `mates` maps mate nodeId → seated interpenetration depth (mm), the
+ steady thread interference a travelling fastener is allowed to keep.
+ `kind` distinguishes rod-like (bolts, screws, pins) from disc-like
+ (nuts, washers) — it decides which side of a threaded pair installs
+ first (bolt before nut).
+ """
+
+ axis: np.ndarray
+ mates: dict[str, float] = field(default_factory=dict)
+ kind: str | None = None # "rod" | "disc" | None
+ # Shank radius (mm) — thread radius from mate contacts, else the thin
+ # radial band of the part's own vertices. Drives joint detection.
+ shank_radius: float | None = None
+ # Joint through-parts (clearance holes, counterbores): while travelling
+ # along its own axis the fastener may keep sliding contact with them —
+ # a snug counterbore reads as shallow phantom penetration on a
+ # tessellated mesh. Allowance value, like mates, is depth before the
+ # shared margin applies.
+ sliding: dict[str, float] = field(default_factory=dict)
+
+
+@dataclass
+class _SandwichInfo:
+ """A sandwiched compliant part (gasket, seal, shim) and its two sides.
+
+ `axis` is the shared dominant contact normal; `side_a`/`side_b` hold
+ the partner unit ids on each side of the part along that axis. Which
+ side assembles first is decided later by total material volume (the
+ enclosure side outweighs the compressor side).
+ """
+
+ axis: np.ndarray
+ side_a: set = field(default_factory=set)
+ side_b: set = field(default_factory=set)
+
+
+@dataclass
+class PlannedComponent:
+ node_id: str
+ motion: dict
+ confidence: str | None # "high" | "low" | None for unplanned
+ removal_direction: list[float] | None
+ blocked_by: list[str] = field(default_factory=list)
+ # "linear" | "L" | "escape" | "group" | "flagged" | "base"
+ tier: str | None = None
+ # Forward-verified: the insertion path is collision-free against the
+ # parts present at that point in the final sequence
+ verified: bool = False
+ # Members of a subassembly unit share a groupId (one step, one motion)
+ group_id: str | None = None
+
+
+@dataclass
+class PlanResult:
+ plan: dict
+ component_count: int
+ planned_count: int
+ tiers: dict
+ warnings: list[str]
+ verified_count: int = 0
+
+
+def plan_step(
+ step_path: Path,
+ linear_deflection: float = 0.1,
+ angular_deflection: float = 0.5,
+ clearance: float = 0.5,
+ path_samples: int = 60,
+ max_parts: int | None = None,
+ units: list[dict] | None = None,
+ sequence: list[list[str]] | None = None,
+) -> PlanResult:
+ """Plan removal motions and an assembly sequence for a STEP file.
+
+ ``units`` pre-groups leaf nodeIds (e.g. a purchased PCB's hundreds of tiny
+ solids) into single rigid bodies: each multi-member unit is merged into one
+ collision mesh for planning, then expanded back to its member leaves at
+ emission (they share one step and one motion). This is what keeps a 400-part
+ model — really ~7 assembled units — from being planned as 400 loose bodies.
+
+ ``sequence`` switches to fixed-sequence mode: the caller supplies the
+ assembly ORDER and GROUPING as an ordered list of leaf-nodeId groups, and
+ the planner uses that order as-is (no reordering) — it only computes each
+ group's forward-collision insertion motion (see ``_plan_fixed_sequence``).
+ plan.json comes out in the same shape either way.
+ """
+ try:
+ import trimesh
+ except ImportError as exc: # pragma: no cover - dependency guard
+ raise ConvertError(
+ "TESSELLATION_FAILED", f"collision libraries unavailable: {exc}"
+ ) from exc
+
+ warnings: list[str] = []
+ doc = _read_step(step_path)
+ root = _build_tree(doc, linear_deflection, angular_deflection, warnings)
+ _assign_node_ids(root)
+ _compute_world_bboxes(root, np.eye(4))
+
+ parts = _collect_world_parts(root, trimesh)
+ leaf_count = len(parts)
+ expansion: dict[str, dict] = {}
+ if units and not sequence:
+ units = _eject_fastened_unit_members(parts, units, trimesh, warnings)
+ parts, expansion = _merge_units(parts, units, trimesh)
+
+ # The limit applies to the bodies actually planned, not the raw leaf count:
+ # post-unit-merge in the normal path (a PCB's 300 internal solids collapse
+ # to one body), one per caller group in fixed-sequence mode.
+ planned_body_count = len(sequence) if sequence else len(parts)
+ if max_parts is not None and planned_body_count > max_parts:
+ raise ConvertError(
+ "LIMIT_EXCEEDED",
+ f"assembly has {planned_body_count} part instances; "
+ f"the limit is {max_parts}",
+ 413,
+ )
+ if any(part.is_proxy for part in parts):
+ warnings.append(
+ "some parts use bounding-box proxy meshes; their motions are low confidence"
+ )
+
+ if sequence:
+ outcome = _plan_fixed_sequence(
+ parts,
+ sequence,
+ trimesh,
+ clearance=clearance,
+ path_samples=path_samples,
+ warnings=warnings,
+ tolerance=_mesh_tolerance(linear_deflection),
+ )
+ else:
+ outcome = _plan_parts(
+ parts,
+ trimesh,
+ clearance=clearance,
+ path_samples=path_samples,
+ warnings=warnings,
+ tolerance=_mesh_tolerance(linear_deflection),
+ # Multi-member caller units (a populated PCB) keep their own
+ # step: they must never rigid-merge into another part or vanish
+ # into an extracted interlock group
+ protected=set(expansion.keys()),
+ )
+
+ # Expand merged units back to their member leaves: each member carries the
+ # unit's motion + groupId, and the unit is one entry in `groups` (with its
+ # name) so the viewer/step generator render it as a single step.
+ groups: dict = dict(outcome.groups)
+ plan_components_payload: dict = {}
+ for entry in outcome.planned:
+ unit = expansion.get(entry.node_id)
+ if unit is None:
+ plan_components_payload[entry.node_id] = _part_to_dict(entry)
+ continue
+ member_payload = _part_to_dict(entry)
+ member_payload["groupId"] = entry.node_id
+ for member in unit["members"]:
+ plan_components_payload[member] = dict(member_payload)
+ group_payload: dict = {
+ "componentNodeIds": unit["members"],
+ "motion": entry.motion,
+ }
+ if unit.get("name"):
+ group_payload["name"] = unit["name"]
+ groups[entry.node_id] = group_payload
+
+ for member, rep in outcome.merged_into.items():
+ plan_components_payload[member] = {
+ "motion": {"type": "none"},
+ "mergedInto": rep,
+ }
+
+ sequence: list[str] = []
+ for node_id in outcome.sequence:
+ unit = expansion.get(node_id)
+ if unit is None:
+ sequence.append(node_id)
+ else:
+ sequence.extend(unit["members"])
+
+ plan = {
+ "version": PLAN_VERSION,
+ "unit": OUTPUT_UNIT,
+ "sequence": sequence,
+ "components": plan_components_payload,
+ "warnings": warnings,
+ }
+ if groups:
+ plan["groups"] = groups
+ planned_count = sum(
+ 1 for entry in outcome.planned if entry.motion.get("type") != "none"
+ )
+ return PlanResult(
+ plan=plan,
+ component_count=leaf_count,
+ planned_count=planned_count,
+ tiers=outcome.tiers,
+ warnings=warnings,
+ verified_count=outcome.verified_count,
+ )
+
+
+def _eject_fastened_unit_members(
+ parts: list[_Component],
+ units: list[dict],
+ trimesh_mod,
+ warnings: list[str],
+) -> list[dict]:
+ """Fastener joints define assembly boundaries.
+
+ A unit collapses parts that arrive pre-assembled (a purchased PCB's
+ solids). If a fastener OUTSIDE the unit clamps a member INSIDE it,
+ that member is assembled at THIS level — the joint is physical
+ evidence it was never part of the pre-assembly — so it leaves the
+ unit and plans as its own body (a connector screwed through the
+ enclosure wall, swallowed by an over-inclusive authored unit, would
+ otherwise hook the unit to the enclosure and poison the whole plan).
+
+ The unit's internal contact HUB — the member the rest of the unit is
+ mounted on, a PCB's bare board — is never ejected: the same fasteners
+ that secure the whole unit clamp it through its mounting holes, and
+ gutting the hub would orphan every other member.
+ """
+ by_id = {part.node_id: part for part in parts}
+ pair_depths = _seated_pair_depths(parts, trimesh_mod)
+ fasteners = _classify_fasteners(parts, pair_depths)
+ joints = _fastener_joints(parts, fasteners)
+
+ cleaned: list[dict] = []
+ for unit in units:
+ members = [n for n in unit.get("nodeIds", []) if n in by_id]
+ member_set = set(members)
+ if len(member_set) < 2:
+ cleaned.append(unit)
+ continue
+ internal: dict[str, int] = {node: 0 for node in member_set}
+ for pair in pair_depths:
+ a, b = tuple(pair)
+ if a in member_set and b in member_set:
+ internal[a] += 1
+ internal[b] += 1
+ # The most internally-connected member is the unit's fabric (a
+ # PCB's bare board) — the fasteners that secure the whole unit
+ # clamp it too, but ejecting it would orphan every other member
+ hub = max(member_set, key=lambda node: (internal[node], node))
+ ejected: list[str] = []
+ for fastener_id, joint in joints.items():
+ if fastener_id in member_set:
+ continue
+ for member in joint:
+ if member in member_set and member != hub:
+ member_set.discard(member)
+ ejected.append(member)
+ if ejected:
+ for node in sorted(ejected):
+ part = by_id[node]
+ warnings.append(
+ f"'{part.name or node}' ejected from unit "
+ f"'{unit.get('name') or unit.get('id')}': an outside "
+ "fastener assembles it at this level"
+ )
+ unit = {
+ **unit,
+ "nodeIds": [n for n in members if n in member_set],
+ }
+ cleaned.append(unit)
+ return cleaned
+
+
+def _merge_units(
+ parts: list[_Component], units: list[dict], trimesh_mod
+) -> tuple[list[_Component], dict[str, dict]]:
+ """Merge each multi-member unit's leaf meshes into one rigid collision body.
+
+ Returns the reduced parts list (unit bodies replace their members) plus an
+ expansion map ``unit_id -> {"members": [...], "name": str | None}`` used to
+ re-expand the plan afterward. Single-member units are left untouched.
+ """
+ by_id = {p.node_id: p for p in parts}
+ expansion: dict[str, dict] = {}
+ consumed: set[str] = set()
+ merged: list[_Component] = []
+
+ for unit in units:
+ unit_id = unit.get("id")
+ node_ids = unit.get("nodeIds") or []
+ members = [
+ nid for nid in node_ids if nid in by_id and nid not in consumed
+ ]
+ if not unit_id or len(members) <= 1:
+ continue # nothing to merge; the single leaf plans as itself
+
+ combined = trimesh_mod.util.concatenate([by_id[nid].mesh for nid in members])
+ bbox_min = np.min([by_id[nid].bbox_min for nid in members], axis=0)
+ bbox_max = np.max([by_id[nid].bbox_max for nid in members], axis=0)
+ merged.append(
+ _Component(
+ node_id=unit_id,
+ name=unit.get("name") or by_id[members[0]].name,
+ mesh=combined,
+ bbox_min=bbox_min,
+ bbox_max=bbox_max,
+ is_proxy=any(by_id[nid].is_proxy for nid in members),
+ )
+ )
+ expansion[unit_id] = {"members": members, "name": unit.get("name")}
+ consumed.update(members)
+
+ remaining = [p for p in parts if p.node_id not in consumed]
+ return remaining + merged, expansion
+
+
+@dataclass
+class _PlanOutcome:
+ planned: list[PlannedComponent]
+ sequence: list[str]
+ tiers: dict
+ merged_into: dict[str, str]
+ # groupId → { componentNodeIds, motion } for subassembly units
+ groups: dict = field(default_factory=dict)
+ verified_count: int = 0
+ # U → set of X meaning U must assemble before X (diagnostics)
+ edges: dict = field(default_factory=dict)
+ # Unit-level "mates with" graph used for ordering (diagnostics)
+ adjacency: dict = field(default_factory=dict)
+
+
+def _plan_parts(
+ parts: list[_Component],
+ trimesh_mod,
+ clearance: float,
+ path_samples: int,
+ warnings: list[str] | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ debug_trace: list | None = None,
+ protected: set[str] | None = None,
+) -> _PlanOutcome:
+ """The full pipeline over world-space parts.
+
+ Classification → rigid merge → greedy disassembly (motions) →
+ precedence DAG + preference topo sort (order) → forward verification.
+ Greedy alone yields a valid but arbitrary-reading order; the topo sort
+ re-orders freely within the collision constraints derived from the
+ final motions (bottom-up, fasteners right after the parts they secure,
+ identical parts adjacent).
+ """
+ if warnings is None:
+ warnings = []
+
+ pair_depths = _seated_pair_depths(parts, trimesh_mod)
+ # "Mates with" graph for ordering: colliding pairs plus near-contact
+ # pairs within real CAD clearance. Drives base selection and the
+ # connected-growth constraint; collision truth stays penetration-based.
+ leaf_adjacency = _ordering_adjacency(parts, pair_depths)
+ parts_by_id = {part.node_id: part for part in parts}
+ for _pair, (_depth, _points, normals, _tensor, _bounds) in pair_depths.items():
+ for node_id in _pair:
+ part = parts_by_id.get(node_id)
+ if part is None or len(part.contact_normals) >= 128:
+ continue
+ part.contact_normals.extend(normals)
+ fasteners = _classify_fasteners(parts, pair_depths)
+ units, merged_into = _merge_rigid_groups(
+ parts, pair_depths, fasteners, trimesh_mod, warnings
+ )
+
+ # Joints run over the original parts (merged meshes are soups that
+ # break containment tests), then remap members through the merges.
+ # Known BEFORE motion planning: a fastener travelling its bore axis is
+ # allowed sliding engagement with its joint members.
+ joints = _fastener_joints(parts, fasteners)
+ if merged_into:
+ remapped: dict[str, dict[str, float]] = {}
+ for fastener_id, members in joints.items():
+ if fastener_id in merged_into:
+ continue
+ entry: dict[str, float] = {}
+ for member, projection in members.items():
+ unit = merged_into.get(member, member)
+ if unit == fastener_id:
+ continue
+ if unit not in entry or abs(projection) < abs(entry[unit]):
+ entry[unit] = projection
+ remapped[fastener_id] = entry
+ joints = remapped
+ for fastener_id, members in joints.items():
+ info = fasteners.get(fastener_id)
+ if info is None:
+ continue
+ for member in members:
+ if member not in info.mates:
+ info.sliding[member] = tolerance
+
+ # Sandwiched compliant parts (gaskets, seals): detected before motion
+ # planning so their seated squish is granted as an allowance during
+ # every sweep, and so the greedy loop never rigid-merges them away
+ sandwiches = _sandwiched_parts(units, pair_depths, fasteners, merged_into)
+
+ # Secured-ness signals for ordering: which units a fastener engages
+ # (joints, post-remap so members are unit-level) and how many seated
+ # structural neighbors each unit has
+ fastened: set[str] = {
+ member for members in joints.values() for member in members
+ }
+ contact_count: dict[str, int] = {}
+ counted_pairs: set[frozenset] = set()
+ for pair in pair_depths:
+ a, b = tuple(pair)
+ unit_a = merged_into.get(a, a)
+ unit_b = merged_into.get(b, b)
+ if unit_a == unit_b:
+ continue
+ unit_pair = frozenset((unit_a, unit_b))
+ if unit_pair in counted_pairs:
+ continue
+ counted_pairs.add(unit_pair)
+ for me, other in ((unit_a, unit_b), (unit_b, unit_a)):
+ if other in fasteners:
+ continue
+ contact_count[me] = contact_count.get(me, 0) + 1
+
+ # Parts with a deep external bite (embedded collars, interference
+ # beyond thread scale) poison any group they join — deprioritize them
+ # as group members so clean pairs get tried first. Sandwiched parts are
+ # exempt: their bite is compliant squish, not an embedding.
+ deep_bitten: set[str] = set()
+ for pair, (depth, _p, _n, _t, _b) in pair_depths.items():
+ if depth > 1.0:
+ for node_id in pair:
+ info = fasteners.get(node_id)
+ (other,) = pair - {node_id}
+ if info is not None and other in info.mates:
+ continue
+ if merged_into.get(node_id, node_id) in sandwiches:
+ continue
+ deep_bitten.add(node_id)
+
+ group_units: dict[str, tuple[_Component, list[str]]] = {}
+ late_merges: dict[str, str] = {}
+ planned, greedy_sequence, _greedy_tiers = _greedy_disassembly(
+ units,
+ trimesh_mod,
+ clearance=clearance,
+ path_samples=path_samples,
+ warnings=warnings,
+ fasteners=fasteners,
+ group_units=group_units,
+ tolerance=tolerance,
+ late_merges=late_merges,
+ deep_bitten=deep_bitten,
+ sandwiched=set(sandwiches),
+ protected=protected,
+ )
+ if late_merges:
+ # Chase chains (A merged into B, B later merged into C)
+ for member, host in list(late_merges.items()):
+ while host in late_merges:
+ host = late_merges[host]
+ late_merges[member] = host
+ merged_into = {**merged_into, **late_merges}
+
+ # Subassembly units replace their members for ordering/verification:
+ # the combined mesh moves as one body under the representative's id
+ units_by_id = {unit.node_id: unit for unit in units}
+ for member in late_merges:
+ units_by_id.pop(member, None)
+ for rep_id, (combined, members) in group_units.items():
+ units_by_id[rep_id] = combined
+ for member_id in members:
+ if member_id != rep_id:
+ units_by_id.pop(member_id, None)
+
+ planned_by_id = {entry.node_id: entry for entry in planned}
+
+ # Lift the mate graph to the final planning units, then anchor the
+ # assembly on the most-connected massive part — the greedy loop's base is
+ # only "the last part it could remove", which inverts on enclosures.
+ unit_adjacency = _rollup_adjacency(
+ leaf_adjacency, merged_into, group_units, units_by_id
+ )
+ _reselect_base(planned, units_by_id, unit_adjacency, fasteners, warnings)
+
+ # Greedy-time blockers are an artifact of removal order: a part flagged
+ # late was tested against a half-emptied world ("blocked by the box"
+ # when the lid and seal were already removed). Recompute against the
+ # FULL seated assembly so blocked_by names everything that pins the part
+ # — the flagged-before-blocker edges below and the viewer's blocker list
+ # both depend on it.
+ flagged_structural = [
+ entry
+ for entry in planned
+ if entry.tier == "flagged"
+ and entry.node_id in units_by_id
+ and entry.node_id not in fasteners
+ ]
+ if flagged_structural:
+ from trimesh.collision import CollisionManager
+
+ seated = CollisionManager()
+ for unit_id, unit in units_by_id.items():
+ seated.add_object(unit_id, unit.mesh)
+ for entry in flagged_structural:
+ blockers = _escape_blockers(
+ units_by_id[entry.node_id],
+ units_by_id,
+ seated,
+ fasteners,
+ tolerance,
+ path_samples,
+ )
+ if blockers:
+ entry.blocked_by = blockers
+
+ edges = _derive_precedence(
+ planned, units_by_id, trimesh_mod, fasteners, path_samples, tolerance
+ )
+ _add_joint_edges(fasteners, joints, units_by_id, edges, warnings)
+ # Sandwich and support orderings are PREFERENCES (gravity stacking,
+ # enclosure-before-gasket-before-compressor), not collision physics —
+ # they live in a SOFT graph the sort favors but never blocks on. As hard
+ # DAG edges they can force the far end of a hanging pair before the end
+ # that touches the assembly, installing parts in mid-air. Sandwich goes
+ # in BEFORE support: the support pass compares bbox z-centers, which
+ # degenerate for a thin part on a thin flange — with the sandwich edge
+ # already present, a wrong-direction support edge is rejected by the
+ # cycle guard, and the right one is a no-op.
+ soft_edges: dict[str, set[str]] = {
+ unit_id: set() for unit_id in units_by_id
+ }
+ _add_sandwich_edges(
+ sandwiches, units_by_id, merged_into, soft_edges, warnings
+ )
+ _add_support_edges(
+ parts, pair_depths, fasteners, merged_into, soft_edges, warnings
+ )
+ # The base is PLACED, not inserted — nothing can be required to precede
+ # it. Derived/support/sandwich edges pointing INTO the base (a support
+ # edge from a part physically below it, a stale derived edge from a
+ # greedy replay where a re-anchored base was out of the world) would
+ # push the anchor into the middle of the sequence; drop them all. Any
+ # insertion that truly conflicts with the seated base is caught by
+ # forward verification and fades in instead.
+ base_id = next(
+ (entry.node_id for entry in planned if entry.tier == "base"), None
+ )
+ if base_id is not None:
+ for afters in edges.values():
+ afters.discard(base_id)
+ for afters in soft_edges.values():
+ afters.discard(base_id)
+ sequence = _preference_topo_sort(
+ planned,
+ units_by_id,
+ edges,
+ fasteners,
+ joints,
+ greedy_sequence,
+ warnings,
+ group_members={
+ rep_id: members
+ for rep_id, (_combined, members) in group_units.items()
+ },
+ debug_trace=debug_trace,
+ fastened=fastened,
+ contact_count=contact_count,
+ adjacency=unit_adjacency,
+ soft_edges=soft_edges,
+ )
+ _verify_sequence(
+ sequence,
+ planned_by_id,
+ units_by_id,
+ trimesh_mod,
+ fasteners,
+ path_samples,
+ warnings,
+ tolerance,
+ )
+
+ # Expand subassembly units: every member appears in the sequence and in
+ # the parts payload with the shared motion and groupId
+ groups_payload: dict = {}
+ if group_units:
+ group_ids = {
+ rep_id: f"g{index + 1}"
+ for index, rep_id in enumerate(
+ rep_id for rep_id in sequence if rep_id in group_units
+ )
+ }
+ expanded_sequence: list[str] = []
+ for node_id in sequence:
+ if node_id in group_units:
+ _combined, members = group_units[node_id]
+ expanded_sequence.extend(members)
+ else:
+ expanded_sequence.append(node_id)
+ sequence = expanded_sequence
+
+ for rep_id, (_combined, members) in group_units.items():
+ rep_entry = planned_by_id[rep_id]
+ group_id = group_ids[rep_id]
+ rep_entry.group_id = group_id
+ groups_payload[group_id] = {
+ "componentNodeIds": members,
+ "motion": rep_entry.motion,
+ }
+ for member_id in members:
+ if member_id == rep_id:
+ continue
+ planned.append(
+ PlannedComponent(
+ node_id=member_id,
+ motion=rep_entry.motion,
+ confidence=rep_entry.confidence,
+ removal_direction=rep_entry.removal_direction,
+ blocked_by=list(rep_entry.blocked_by),
+ tier=rep_entry.tier,
+ verified=rep_entry.verified,
+ group_id=group_id,
+ )
+ )
+
+ return _PlanOutcome(
+ planned=planned,
+ sequence=sequence,
+ tiers=_tally_tiers(planned),
+ merged_into=merged_into,
+ groups=groups_payload,
+ verified_count=sum(1 for entry in planned if entry.verified),
+ edges=edges,
+ adjacency=unit_adjacency,
+ )
+
+
+def _plan_fixed_sequence(
+ parts: list[_Component],
+ groups_in_order: list[list[str]],
+ trimesh_mod,
+ clearance: float,
+ path_samples: int,
+ warnings: list[str] | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ debug_trace: list | None = None,
+) -> _PlanOutcome:
+ """Plan a caller-fixed order and grouping (no reordering).
+
+ Unlike ``_plan_parts``, the assembly ORDER and GROUPING are GIVEN: each
+ inner list of ``groups_in_order`` is one assembly step — a set of leaf
+ nodeIds installed together as one rigid body — and step i installs after
+ every earlier step. The planner never re-derives the order; it only
+ computes each group's insertion motion so it clears the parts of PREVIOUS
+ groups (forward collision), demoting a group to ``flagged`` (motion
+ "none", blockers recorded) when no such motion exists. The first group is
+ the placed base and keeps motion "none".
+
+ The planning WORLD is the sequence: model parts absent from every group
+ are never on the canvas, so they are invisible here end to end — they are
+ not obstacles, they don't seed fastener mates/axes or contact normals, and
+ they don't weigh on the least-entanglement tie-break.
+
+ Returns a fully-expanded ``_PlanOutcome`` (one entry per member leaf, each
+ carrying its group's motion + groupId, plus a ``groups`` payload) so
+ ``plan_step`` emits plan.json identically to the normal path.
+ """
+ from trimesh.collision import CollisionManager
+
+ if warnings is None:
+ warnings = []
+
+ by_id = {part.node_id: part for part in parts}
+
+ # Map each caller group onto leaf parts, exactly like `_merge_units`: drop
+ # nodeIds absent from the model, drop leaves already claimed by an earlier
+ # group, and skip a group left with no members.
+ cleaned_groups: list[list[str]] = []
+ consumed: set[str] = set()
+ for index, group in enumerate(groups_in_order):
+ members: list[str] = []
+ for node_id in group:
+ if node_id not in by_id:
+ warnings.append(
+ f"group {index + 1}: nodeId '{node_id}' is not in the "
+ "model; dropped"
+ )
+ continue
+ if node_id in consumed:
+ warnings.append(
+ f"group {index + 1}: nodeId '{node_id}' already belongs "
+ "to an earlier group; dropped"
+ )
+ continue
+ members.append(node_id)
+ consumed.add(node_id)
+ if not members:
+ warnings.append(
+ f"group {index + 1} has no parts present in the model; skipped"
+ )
+ continue
+ cleaned_groups.append(members)
+
+ if not cleaned_groups:
+ return _PlanOutcome(
+ planned=[], sequence=[], tiers=_tally_tiers([]), merged_into={}
+ )
+
+ # Fastener axes are the only classification the motion search needs: they
+ # let a fastener exit through its bore and keep its threaded-mate
+ # interference. No greedy/precedence work runs — the order is given.
+ # Classification runs over the SEQUENCE parts only: components the caller
+ # never installs are not on the canvas, so they must not contribute mates,
+ # sliding allowances, bore axes, or contact normals.
+ sequence_parts = [part for part in parts if part.node_id in consumed]
+ pair_depths = _seated_pair_depths(sequence_parts, trimesh_mod)
+ for _pair, (_depth, _points, normals, _tensor, _bounds) in pair_depths.items():
+ for node_id in _pair:
+ part = by_id.get(node_id)
+ if part is None or len(part.contact_normals) >= 128:
+ continue
+ part.contact_normals.extend(normals)
+ fasteners = _classify_fasteners(sequence_parts, pair_depths)
+
+ # Each group becomes one rigid collision body: a multi-member group is
+ # concatenated under its first member's nodeId (via `_merge_units`); a
+ # single-member group is the leaf itself.
+ units_spec = [
+ {"id": members[0], "nodeIds": members} for members in cleaned_groups
+ ]
+ merged_parts, _expansion = _merge_units(parts, units_spec, trimesh_mod)
+ merged_by_id = {part.node_id: part for part in merged_parts}
+ groups_ordered = [
+ (f"g{index + 1}", merged_by_id[members[0]], members)
+ for index, members in enumerate(cleaned_groups)
+ ]
+
+ # Forward pass: place each group in the GIVEN order and compute its
+ # insertion motion against ONLY the already-placed groups. The first group
+ # is the placed base (no insertion motion), matching the normal path.
+ # `full_manager` holds every sequence body at its seated pose so the
+ # motion search's least-entanglement tie-break can rank multiple clear
+ # directions (the normal path builds the same thing from all parts).
+ manager = CollisionManager()
+ full_manager = CollisionManager()
+ placed: dict[str, _Component] = {}
+ planned: list[PlannedComponent] = []
+ planned_by_id: dict[str, PlannedComponent] = {}
+ units_by_id: dict[str, _Component] = {}
+
+ for _label, body, _members in groups_ordered:
+ full_manager.add_object(body.node_id, body.mesh)
+
+ for order_index, (_label, body, _members) in enumerate(groups_ordered):
+ units_by_id[body.node_id] = body
+ if order_index == 0:
+ entry = PlannedComponent(
+ node_id=body.node_id,
+ motion={"type": "none"},
+ confidence="high",
+ removal_direction=None,
+ tier="base",
+ )
+ else:
+ # remaining = this group + every already-placed group; the manager
+ # holds only the placed groups, so the motion search (which reverses
+ # a removal into an insertion) clears exactly the previous parts.
+ remaining = {**placed, body.node_id: body}
+ with _unregistered(full_manager, [body.node_id]):
+ entry = _plan_removal(
+ body,
+ remaining,
+ manager,
+ clearance,
+ path_samples,
+ fasteners,
+ tolerance,
+ full_manager=full_manager,
+ )
+ if entry is None:
+ entry = _plan_escape(
+ body,
+ remaining,
+ manager,
+ path_samples,
+ fasteners,
+ tolerance,
+ )
+ if entry is None:
+ warnings.append(
+ f"'{body.name or body.node_id}' has no collision-free "
+ "insertion after the earlier groups; flagged for review — "
+ "it fades in during playback"
+ )
+ entry = PlannedComponent(
+ node_id=body.node_id,
+ motion={"type": "none"},
+ confidence="low",
+ removal_direction=None,
+ blocked_by=_escape_blockers(
+ body,
+ remaining,
+ manager,
+ fasteners,
+ tolerance,
+ path_samples,
+ ),
+ tier="flagged",
+ )
+ planned.append(entry)
+ planned_by_id[body.node_id] = entry
+ manager.add_object(body.node_id, body.mesh)
+ placed[body.node_id] = body
+
+ # Confirm/flag each group's motion against exactly the parts present at its
+ # point in the fixed sequence (the same forward check the normal path runs)
+ # and record the verified flag; a numerical edge demotes to flagged.
+ sequence_bodies = [
+ body.node_id for _label, body, _members in groups_ordered
+ ]
+ _verify_sequence(
+ sequence_bodies,
+ planned_by_id,
+ units_by_id,
+ trimesh_mod,
+ fasteners,
+ path_samples,
+ warnings,
+ tolerance,
+ )
+ tiers = _tally_tiers(planned)
+
+ # Expand each group body back to its member leaves: every member carries
+ # the group's motion + groupId, and the group is one `groups` entry so the
+ # viewer/step-mapper renders it as a single step.
+ groups_payload: dict = {}
+ expanded_planned: list[PlannedComponent] = []
+ sequence: list[str] = []
+ for label, body, members in groups_ordered:
+ rep_entry = planned_by_id[body.node_id]
+ rep_entry.group_id = label
+ groups_payload[label] = {
+ "componentNodeIds": members,
+ "motion": rep_entry.motion,
+ }
+ sequence.extend(members)
+ for member_id in members:
+ if member_id == body.node_id:
+ expanded_planned.append(rep_entry)
+ else:
+ expanded_planned.append(
+ PlannedComponent(
+ node_id=member_id,
+ motion=rep_entry.motion,
+ confidence=rep_entry.confidence,
+ removal_direction=rep_entry.removal_direction,
+ blocked_by=list(rep_entry.blocked_by),
+ tier=rep_entry.tier,
+ verified=rep_entry.verified,
+ group_id=label,
+ )
+ )
+
+ return _PlanOutcome(
+ planned=expanded_planned,
+ sequence=sequence,
+ tiers=tiers,
+ merged_into={},
+ groups=groups_payload,
+ verified_count=sum(1 for entry in expanded_planned if entry.verified),
+ )
+
+
+def _tally_tiers(planned: list[PlannedComponent]) -> dict:
+ """Tier stats from the final planned entries (post-verification)."""
+ tiers = {
+ "linear": 0,
+ "l": 0,
+ "escape": 0,
+ "group": 0,
+ "flagged": 0,
+ "forced": 0,
+ "unplanned": 0,
+ }
+ counted_groups: set[str] = set()
+ for entry in planned:
+ if entry.tier == "linear":
+ tiers["linear"] += 1
+ elif entry.tier == "L":
+ tiers["l"] += 1
+ elif entry.tier == "escape":
+ tiers["escape"] += 1
+ elif entry.tier == "flagged":
+ tiers["flagged"] += 1
+ elif entry.tier == "group":
+ # One count per subassembly unit, not per member
+ if entry.group_id is None or entry.group_id not in counted_groups:
+ tiers["group"] += 1
+ if entry.group_id is not None:
+ counted_groups.add(entry.group_id)
+ return tiers
+
+
+def _part_volume(part: _Component) -> float:
+ """Material volume (mm³): mesh volume when watertight, else bbox.
+
+ Bbox volume lies for tilted parts (a 45° bolt inflates 5×) and for
+ wrap-around parts (a thin clamp spanning the rail reads as huge).
+ """
+ cached = getattr(part.mesh, "_carbon_volume", None)
+ if cached is not None:
+ return cached
+ volume = 0.0
+ try:
+ if part.mesh.is_watertight:
+ volume = float(abs(part.mesh.volume))
+ else:
+ # Multi-body soups (embossed text, concatenated hardware):
+ # sum the watertight bodies instead of trusting the bbox
+ bodies = part.mesh.split(only_watertight=True)
+ if len(bodies) > 0:
+ volume = float(sum(abs(body.volume) for body in bodies))
+ except Exception:
+ volume = 0.0
+ if volume <= 1e-9:
+ extents = np.abs(part.bbox_max - part.bbox_min)
+ volume = float(max(abs(np.prod(extents)), 1e-9))
+ part.mesh._carbon_volume = volume
+ return volume
+
+
+def _structural_key(
+ part: _Component, centroid: np.ndarray, diagonal: float
+) -> tuple[float, float]:
+ """Big first (ascending key).
+
+ Material volume descending, then horizontal proximity to the assembly
+ centroid in coarse buckets as the tiebreak: the skeleton and major
+ components assemble before brackets, hardware, and cosmetics. In
+ reverse (negated), disassembly strips small parts first so the biggest
+ part survives to become the base.
+ """
+ center = (part.bbox_min + part.bbox_max) / 2.0
+ offset = center - centroid
+ distance = float(np.hypot(float(offset[0]), float(offset[1])))
+ bucket = round(distance / max(diagonal, 1e-6) * 20.0) / 20.0
+ return (-_part_volume(part), bucket)
+
+
+def _assembly_centroid(parts) -> np.ndarray:
+ bbox_min = np.min([part.bbox_min for part in parts], axis=0)
+ bbox_max = np.max([part.bbox_max for part in parts], axis=0)
+ return (bbox_min + bbox_max) / 2.0
+
+
+def _removal_segments(motion: dict) -> list[tuple[np.ndarray, float]] | None:
+ """A stored INSERTION motion as removal segments (reverse order/sense)."""
+ if motion.get("type") == "linear":
+ direction = -np.asarray(motion["direction"], dtype=np.float64)
+ norm = float(np.linalg.norm(direction)) or 1.0
+ return [(direction / norm, float(motion["distance"]))]
+ if motion.get("type") == "L":
+ segments: list[tuple[np.ndarray, float]] = []
+ for segment in reversed(motion["segments"]):
+ direction = -np.asarray(segment["direction"], dtype=np.float64)
+ norm = float(np.linalg.norm(direction)) or 1.0
+ segments.append((direction / norm, float(segment["distance"])))
+ return segments
+ return None
+
+
+def _path_blockers(
+ part: _Component,
+ manager,
+ segments: list[tuple[np.ndarray, float]],
+ samples: int,
+ fasteners: dict[str, _FastenerInfo],
+ extra_exempt: dict[str, float] | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+) -> set[str]:
+ """Every present unit the part's removal path cuts through.
+
+ Same sampling and mate allowances as `_path_is_clear`, but collects
+ all offending partners instead of failing fast. `extra_exempt`
+ typically carries the moving part's own registered copy.
+ """
+ blockers: set[str] = set()
+ offset = np.zeros(3)
+ # Once a partner is identified as a blocker its identity is all this
+ # function returns — but left registered, every further sample INSIDE
+ # it enumerates its full triangle-contact set (thousands of contact
+ # objects per sample for a deep pass-through). Unregister each blocker
+ # for the remainder of the sweep; re-register before returning.
+ # Sound: a recorded blocker can't be un-recorded, and removing it
+ # never hides another partner's contacts (fcl enumerates all pairs
+ # independently).
+ objs = getattr(manager, "_objs", {})
+ parked: list = []
+ try:
+ for direction, distance in segments:
+ exempt = _mate_exempt(part, direction, fasteners)
+ seated = _seated_exempt(part, direction)
+ if seated:
+ # Compliant squish along the sandwich axis never blocks
+ exempt = {**seated, **(exempt or {})}
+ if extra_exempt:
+ exempt = {**(exempt or {}), **extra_exempt}
+ count = min(
+ max(samples, int(distance / MAX_SAMPLE_SPACING_MM) + 1),
+ MAX_PATH_SAMPLES,
+ )
+ for s in np.linspace(0.0, distance, count, endpoint=True)[1:]:
+ translation = offset + direction * float(s)
+ found = set()
+ for other, depth in _contacts_at(manager, part, translation):
+ if other is None:
+ continue
+ if exempt is not None and other in exempt:
+ if depth <= exempt[other] + MATE_DEPTH_MARGIN_MM:
+ continue
+ if depth > tolerance:
+ found.add(other)
+ fresh = found - blockers
+ if fresh:
+ blockers |= fresh
+ for other in fresh:
+ entry = objs.get(other)
+ if entry is not None:
+ manager._manager.unregisterObject(entry["obj"])
+ parked.append(entry["obj"])
+ if parked:
+ manager._manager.update()
+ offset = offset + direction * distance
+ finally:
+ for obj in parked:
+ manager._manager.registerObject(obj)
+ if parked:
+ manager._manager.update()
+ return blockers
+
+
+def _derive_precedence(
+ planned: list[PlannedComponent],
+ units_by_id: dict[str, _Component],
+ trimesh_mod,
+ fasteners: dict[str, _FastenerInfo],
+ path_samples: int,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+) -> dict[str, set[str]]:
+ """U → X edges: X's seated body blocks U's insertion path, so U must
+ be assembled while X is absent (U before X).
+
+ Greedy's own order satisfies every derivable edge — each removal was
+ validated against exactly the parts assembled before it — so this
+ graph is acyclic with the greedy order as a witness topo order. Any
+ other topo order is equally collision-consistent.
+ """
+ from trimesh.collision import CollisionManager
+
+ manager = CollisionManager()
+ for unit in units_by_id.values():
+ manager.add_object(unit.node_id, unit.mesh)
+
+ samples_segment = max(12, path_samples // 3)
+ edges: dict[str, set[str]] = {entry.node_id: set() for entry in planned}
+ for entry in planned:
+ segments = _removal_segments(entry.motion)
+ if not segments:
+ continue
+ part = units_by_id[entry.node_id]
+ with _unregistered(manager, [part.node_id]):
+ edges[entry.node_id] |= _path_blockers(
+ part,
+ manager,
+ segments,
+ samples_segment,
+ fasteners,
+ extra_exempt={part.node_id: float("inf")},
+ tolerance=tolerance,
+ )
+ return edges
+
+
+def _add_joint_edges(
+ fasteners: dict[str, _FastenerInfo],
+ joints: dict[str, dict[str, float]],
+ units_by_id: dict[str, _Component],
+ edges: dict[str, set[str]],
+ warnings: list[str],
+) -> None:
+ """Everything a fastener joins installs before the fastener.
+
+ Hard edges from the joint sets (through-parts + threaded mates), which
+ the collision constraints cannot fully express — a bolt passes through
+ clearance holes without touching, so nothing else forces its clamped
+ parts to precede it. One exception: a disc mate (nut) installs after
+ its rod fastener. Skipped with a warning if an edge would contradict
+ the collision DAG.
+ """
+
+ def reaches(source: str, target: str) -> bool:
+ stack, seen = [source], set()
+ while stack:
+ node = stack.pop()
+ if node == target:
+ return True
+ if node in seen:
+ continue
+ seen.add(node)
+ stack.extend(edges.get(node, ()))
+ return False
+
+ def add_edge(before: str, after: str, label: str) -> None:
+ if after in edges[before]:
+ return
+ if reaches(after, before):
+ warnings.append(
+ f"{label} preference between '{before}' and "
+ f"'{after}' conflicts with collision constraints; skipped"
+ )
+ return
+ edges[before].add(after)
+
+ for fastener_id, info in fasteners.items():
+ if fastener_id not in edges:
+ continue
+ chain: list[str] = []
+ for member in joints.get(fastener_id, ()):
+ if member not in edges:
+ continue
+ member_info = fasteners.get(member)
+ if (
+ member in info.mates
+ and member_info is not None
+ and info.kind == "rod"
+ and member_info.kind == "disc"
+ ):
+ add_edge(fastener_id, member, "joint-order") # bolt, then nut
+ else:
+ add_edge(member, fastener_id, "joint-order") # joint, then f
+ chain.append(member)
+
+ # The joint's members stack tip → head along the fastener's axis:
+ # the bolt clamps the head-side part ONTO the tip-side part, so the
+ # tip side assembles first (a bracket after the carriage it bolts
+ # to, even when their CAD surfaces never touch).
+ fastener_part = units_by_id.get(fastener_id)
+ if fastener_part is None or len(chain) < 2:
+ continue
+ head_dir = _head_direction(fastener_part, info, units_by_id)
+ # joints store projections along info.axis; orient tip → head
+ sign = 1.0 if float(head_dir @ info.axis) >= 0 else -1.0
+ member_projection = joints.get(fastener_id, {})
+
+ def head_projection(member: str) -> float:
+ return sign * member_projection.get(member, 0.0)
+
+ chain.sort(key=lambda member: (head_projection(member), member))
+ for tip_side, head_side in zip(chain, chain[1:]):
+ if abs(head_projection(head_side) - head_projection(tip_side)) < 0.5:
+ continue
+ add_edge(tip_side, head_side, "joint-stack")
+
+
+def _motion_travel(motion: dict) -> float:
+ if motion.get("type") == "linear":
+ return float(motion.get("distance", 0.0))
+ if motion.get("type") == "L":
+ return sum(
+ float(segment.get("distance", 0.0))
+ for segment in motion.get("segments", [])
+ )
+ return 0.0
+
+
+def _sandwiched_parts(
+ units: list[_Component],
+ pair_depths: dict[frozenset, tuple[float, list, list, np.ndarray, np.ndarray]],
+ fasteners: dict[str, _FastenerInfo],
+ merged_into: dict[str, str],
+) -> dict[str, _SandwichInfo]:
+ """Thin parts pressed from BOTH sides along one axis (gaskets, seals).
+
+ A candidate is a non-fastener unit, thin along the shared dominant
+ contact axis, with seated partners on both sides of its center along
+ that axis. Detection uses contact-point positions and the winding-
+ invariant structure tensor — never normal signs (fcl normals follow
+ triangle winding) and never bbox z-centers (degenerate when the part
+ and its flange are both thin).
+
+ Side effect: sandwich partners exchange seated-interference allowances
+ (`_Component.seated_allowance`) so a compliant part's observed squish never
+ reads as a blocking collision during removal sweeps — the seated state
+ itself is the evidence the interference is intentional, the same
+ reasoning as thread-mate allowances.
+ """
+ units_by_id = {unit.node_id: unit for unit in units}
+ # Unit-level accumulation: unit -> partner -> [tensor, points, depth]
+ contacts: dict[str, dict[str, list]] = {}
+ for pair, (depth, points, _normals, tensor, _bounds) in pair_depths.items():
+ a, b = tuple(pair)
+ unit_a = merged_into.get(a, a)
+ unit_b = merged_into.get(b, b)
+ if unit_a == unit_b:
+ continue
+ if unit_a not in units_by_id or unit_b not in units_by_id:
+ continue
+ for me, other in ((unit_a, unit_b), (unit_b, unit_a)):
+ slot = contacts.setdefault(me, {}).setdefault(
+ other, [np.zeros((3, 3)), [], 0.0]
+ )
+ slot[0] = slot[0] + tensor
+ slot[1].extend(points)
+ slot[2] = max(slot[2], float(depth))
+
+ result: dict[str, _SandwichInfo] = {}
+ for unit in units:
+ if unit.is_proxy or unit.node_id in fasteners:
+ continue
+ partners = {
+ other: slot
+ for other, slot in contacts.get(unit.node_id, {}).items()
+ if other not in fasteners and slot[1]
+ }
+ if len(partners) < 2:
+ continue
+ # Every partner's dominant contact normal must share one axis
+ axes = []
+ for _tensor, _points, _depth in partners.values():
+ eigvecs = np.linalg.eigh(np.asarray(_tensor, dtype=np.float64))[1]
+ axes.append(np.asarray(eigvecs[:, -1], dtype=np.float64))
+ axis = axes[0]
+ if any(
+ abs(float(np.dot(axis, other_axis))) < SANDWICH_AXIS_ALIGNMENT
+ for other_axis in axes[1:]
+ ):
+ continue
+ # Thin along the axis (AABB support extent — conservative for
+ # tilted axes: overestimates thickness, never under). Both the
+ # ratio AND the absolute cap must hold: proportional thinness
+ # alone lets 30mm plates in long assemblies through.
+ extents = unit.bbox_max - unit.bbox_min
+ thickness = float(np.abs(axis) @ extents)
+ if thickness > SANDWICH_MAX_THICKNESS_RATIO * float(np.max(extents)):
+ continue
+ if thickness > SANDWICH_MAX_THICKNESS_MM:
+ continue
+ # Squish-scale interference only: a bite past compliance scale
+ # means a press fit or broken CAD — granting it an allowance
+ # would tunnel real geometry, so the part is not a sandwich at all
+ if any(
+ float(depth) > SANDWICH_MAX_SQUISH_MM
+ for (_tensor, _points, depth) in partners.values()
+ ):
+ continue
+ # Partners on both sides of the part's center along the axis
+ center = float(axis @ ((unit.bbox_min + unit.bbox_max) / 2.0))
+ info = _SandwichInfo(axis=axis)
+ for other, (_tensor, points, _depth) in partners.items():
+ mean = float(
+ axis @ np.mean(np.asarray(points, dtype=np.float64), axis=0)
+ )
+ (info.side_a if mean < center else info.side_b).add(other)
+ if not info.side_a or not info.side_b:
+ continue
+ result[unit.node_id] = info
+ for other, (_tensor, _points, depth) in partners.items():
+ allowance = max(float(depth), 0.0)
+ partner = units_by_id[other]
+ for me, them in ((unit, other), (partner, unit.node_id)):
+ if allowance > me.seated_allowance.get(them, 0.0):
+ me.seated_allowance[them] = allowance
+ me.seated_allowance_axes[them] = axis
+ return result
+
+
+def _add_sandwich_edges(
+ sandwiches: dict[str, _SandwichInfo],
+ units_by_id: dict[str, _Component],
+ merged_into: dict[str, str],
+ edges: dict[str, set[str]],
+ warnings: list[str],
+) -> None:
+ """Hard edges for sandwiched parts: enclosure side, part, compressor.
+
+ Collision constraints cannot express these — a flagged or interference-
+ fit gasket derives no sweep edges at all, so without explicit edges the
+ topo sort may legally place it anywhere. The side with the larger total
+ material volume is the enclosure (assembles first); the lighter side is
+ the compressor (assembles after the part). A near-tie is ambiguous and
+ adds nothing rather than guessing.
+ """
+
+ def reaches(source: str, target: str) -> bool:
+ stack, seen = [source], set()
+ while stack:
+ node = stack.pop()
+ if node == target:
+ return True
+ if node in seen:
+ continue
+ seen.add(node)
+ stack.extend(edges.get(node, ()))
+ return False
+
+ def add_edge(before: str, after: str) -> None:
+ if after in edges[before]:
+ return
+ if reaches(after, before):
+ warnings.append(
+ f"sandwich preference between '{before}' and "
+ f"'{after}' conflicts with collision constraints; skipped"
+ )
+ return
+ edges[before].add(after)
+
+ for node_id, info in sandwiches.items():
+ if node_id not in edges:
+ continue
+
+ def resolve(side: set) -> set[str]:
+ return {
+ merged_into.get(other, other)
+ for other in side
+ if merged_into.get(other, other) in edges
+ } - {node_id}
+
+ side_a = resolve(info.side_a)
+ side_b = resolve(info.side_b)
+ if not side_a or not side_b:
+ continue
+
+ def side_volume(side: set[str]) -> float:
+ return sum(_part_volume(units_by_id[other]) for other in side)
+
+ volume_a = side_volume(side_a)
+ volume_b = side_volume(side_b)
+ if max(volume_a, volume_b) <= 0:
+ continue
+ if abs(volume_a - volume_b) < 0.05 * max(volume_a, volume_b):
+ warnings.append(
+ f"sandwiched part '{node_id}' has near-equal sides; "
+ "no ordering preference added"
+ )
+ continue
+ first, second = (
+ (side_a, side_b) if volume_a > volume_b else (side_b, side_a)
+ )
+ for other in sorted(first):
+ add_edge(other, node_id)
+ for other in sorted(second):
+ add_edge(node_id, other)
+
+
+def _add_support_edges(
+ parts: list[_Component],
+ pair_depths: dict[frozenset, tuple[float, list, list, np.ndarray, np.ndarray]],
+ fasteners: dict[str, _FastenerInfo],
+ merged_into: dict[str, str],
+ edges: dict[str, set[str]],
+ warnings: list[str],
+) -> None:
+ """A part assembles after the parts it rests on.
+
+ For every seated structure-structure contact whose mean normal is
+ mostly vertical, the upper part follows the lower one — gravity
+ stacking (a bracket after the carriages it sits on, a badge after its
+ housing). Fastener pairs are excluded: their order is governed by
+ joint edges (a nut hangs BELOW its plate but still installs last).
+ Skipped with a warning when an edge would contradict the DAG.
+ """
+ by_id = {part.node_id: part for part in parts}
+
+ def reaches(source: str, target: str) -> bool:
+ stack, seen = [source], set()
+ while stack:
+ node = stack.pop()
+ if node == target:
+ return True
+ if node in seen:
+ continue
+ seen.add(node)
+ stack.extend(edges.get(node, ()))
+ return False
+
+ for pair, (_depth, _points, normals, _tensor, _bounds) in pair_depths.items():
+ a, b = tuple(pair)
+ if a in fasteners or b in fasteners:
+ continue
+ unit_a = merged_into.get(a, a)
+ unit_b = merged_into.get(b, b)
+ if unit_a == unit_b or unit_a not in edges or unit_b not in edges:
+ continue
+ if not normals:
+ continue
+ # fcl normal signs follow triangle winding — align to one
+ # hemisphere before averaging or opposing windings cancel out
+ aligned = np.asarray(normals, dtype=np.float64)
+ flip = np.sign(aligned[:, 2:3])
+ flip[flip == 0] = 1.0
+ mean = np.mean(aligned * flip, axis=0)
+ length = float(np.linalg.norm(mean))
+ if length <= 1e-9 or abs(float(mean[2] / length)) < 0.5:
+ continue
+ part_a, part_b = by_id.get(a), by_id.get(b)
+ if part_a is None or part_b is None:
+ continue
+ center_a = float((part_a.bbox_min[2] + part_a.bbox_max[2]) / 2.0)
+ center_b = float((part_b.bbox_min[2] + part_b.bbox_max[2]) / 2.0)
+ if abs(center_a - center_b) < 1e-6:
+ continue
+ lower, upper = (
+ (unit_a, unit_b) if center_a < center_b else (unit_b, unit_a)
+ )
+ if upper in edges[lower]:
+ continue
+ if reaches(upper, lower):
+ warnings.append(
+ f"support-order preference between '{lower}' and "
+ f"'{upper}' conflicts with collision constraints; skipped"
+ )
+ continue
+ edges[lower].add(upper)
+
+
+def _ordering_adjacency(
+ parts: list[_Component],
+ pair_depths: dict[frozenset, tuple],
+ contact_mm: float = ORDERING_CONTACT_MM,
+) -> dict[str, set[str]]:
+ """Leaf-level "mates with" graph for ordering decisions.
+
+ Seeded from the colliding pairs (`pair_depths`), then augmented with
+ near-contact pairs: an inflated-AABB prefilter proposes candidates, an
+ exact FCL distance query confirms them within `contact_mm`. Real CAD
+ clearances (chip above its pads, boss in its pocket) become edges here
+ even though they never interpenetrate. Ordering-only — collision truth
+ is untouched.
+ """
+ import fcl
+
+ adjacency: dict[str, set[str]] = {part.node_id: set() for part in parts}
+ for pair in pair_depths:
+ if len(pair) != 2:
+ continue
+ a, b = tuple(pair)
+ if a in adjacency and b in adjacency:
+ adjacency[a].add(b)
+ adjacency[b].add(a)
+
+ count = len(parts)
+ if count < 2:
+ return adjacency
+ mins = np.array([part.bbox_min for part in parts]) - contact_mm
+ maxs = np.array([part.bbox_max for part in parts]) + contact_mm
+
+ candidates: list[tuple[int, int]] = []
+ for i in range(count - 1):
+ overlap = np.all(
+ (mins[i + 1 :] <= maxs[i]) & (maxs[i + 1 :] >= mins[i]), axis=1
+ )
+ for offset in np.nonzero(overlap)[0]:
+ j = i + 1 + int(offset)
+ if parts[j].node_id in adjacency[parts[i].node_id]:
+ continue
+ candidates.append((i, j))
+
+ # Past the budget, bbox proximity alone counts as adjacency — a degrade
+ # toward MORE edges, which only weakens the connectivity filter.
+ exact = len(candidates) <= MAX_ADJACENCY_DISTANCE_PAIRS
+ objects: dict[int, "fcl.CollisionObject"] = {}
+
+ def object_for(index: int):
+ obj = objects.get(index)
+ if obj is None:
+ obj = fcl.CollisionObject(
+ _mesh_bvh(parts[index].mesh), fcl.Transform()
+ )
+ objects[index] = obj
+ return obj
+
+ for i, j in candidates:
+ if exact:
+ request = fcl.DistanceRequest()
+ result = fcl.DistanceResult()
+ distance = fcl.distance(
+ object_for(i), object_for(j), request, result
+ )
+ if distance > contact_mm:
+ continue
+ adjacency[parts[i].node_id].add(parts[j].node_id)
+ adjacency[parts[j].node_id].add(parts[i].node_id)
+ return adjacency
+
+
+def _rollup_adjacency(
+ leaf_adjacency: dict[str, set[str]],
+ merged_into: dict[str, str],
+ group_units: dict[str, tuple[_Component, list[str]]],
+ units_by_id: dict[str, _Component],
+) -> dict[str, set[str]]:
+ """Leaf adjacency lifted to the FINAL planning units (rigid merges chased,
+ subassembly-group members folded into their representative)."""
+ member_to_rep: dict[str, str] = {}
+ for rep_id, (_combined, members) in group_units.items():
+ for member in members:
+ member_to_rep[member] = rep_id
+
+ def final_unit(leaf_id: str) -> str:
+ unit = merged_into.get(leaf_id, leaf_id)
+ return member_to_rep.get(unit, unit)
+
+ adjacency: dict[str, set[str]] = {
+ unit_id: set() for unit_id in units_by_id
+ }
+ for leaf_id, neighbors in leaf_adjacency.items():
+ unit_a = final_unit(leaf_id)
+ if unit_a not in adjacency:
+ continue
+ for neighbor in neighbors:
+ unit_b = final_unit(neighbor)
+ if unit_b == unit_a or unit_b not in adjacency:
+ continue
+ adjacency[unit_a].add(unit_b)
+ adjacency[unit_b].add(unit_a)
+ return adjacency
+
+
+def _reselect_base(
+ planned: list[PlannedComponent],
+ units_by_id: dict[str, _Component],
+ unit_adjacency: dict[str, set[str]],
+ fasteners: dict[str, _FastenerInfo],
+ warnings: list[str],
+) -> None:
+ """Re-anchor the assembly on the most-connected massive part.
+
+ The greedy loop's base is whatever it could not remove until last — on an
+ enclosure model that deadlocks (box pinned by its contents, seal pinned
+ between box and lid), the box gets FLAGGED and the compressed seal
+ "wins", inverting the whole sequence: the lid stack assembles hanging in
+ midair and the true anchor arrives late as an afterthought. From first
+ principles the base is the part everything mounts INTO: the structural
+ part with the highest mate degree and volume. When any structural part
+ beats the greedy base by a clear margin on BOTH axes, it becomes the
+ base (motion "none", placed first — a planned removal motion is
+ discarded; the anchor is placed, not inserted) and the ex-base fades in
+ at its ordered position like any other flagged part — for a compressed
+ seal that reads exactly right.
+ """
+ base_entry = next(
+ (entry for entry in planned if entry.tier == "base"), None
+ )
+ if base_entry is None:
+ return
+
+ def score(node_id: str) -> tuple[int, float]:
+ return (
+ len(unit_adjacency.get(node_id, ())),
+ _part_volume(units_by_id[node_id]),
+ )
+
+ candidates = [
+ entry
+ for entry in planned
+ if entry.tier != "base"
+ and entry.node_id in units_by_id
+ and entry.node_id not in fasteners
+ and not units_by_id[entry.node_id].is_proxy
+ ]
+ if not candidates:
+ return
+
+ winner = max(
+ candidates, key=lambda entry: (*score(entry.node_id), entry.node_id)
+ )
+ base_degree, base_volume = score(base_entry.node_id)
+ win_degree, win_volume = score(winner.node_id)
+ # Mate DEGREE is the anchor signal — the box everything screws into wins
+ # on degree even though its thin shell loses on mesh volume to a potted
+ # blob of components. The greedy base is an accident (the last removable
+ # part), so it earns no strong deference: a challenger that clearly
+ # dominates on connectivity (1.5x) with comparable mass takes over;
+ # near-ties keep the greedy base for stability.
+ if win_degree < 1.5 * max(base_degree, 1) or win_volume < 0.5 * base_volume:
+ return
+
+ winner_unit = units_by_id[winner.node_id]
+ base_unit = units_by_id[base_entry.node_id]
+ warnings.append(
+ f"base re-anchored to '{winner_unit.name or winner.node_id}' "
+ f"({win_degree} mates) — '{base_unit.name or base_entry.node_id}' "
+ "was the last removable part, not the part the assembly mounts into; "
+ "it fades in at its ordered position instead"
+ )
+ winner.tier = "base"
+ winner.motion = {"type": "none"}
+ winner.confidence = "high"
+ winner.removal_direction = None
+ winner.blocked_by = []
+ base_entry.tier = "flagged"
+ base_entry.motion = {"type": "none"}
+ base_entry.confidence = "low"
+ base_entry.removal_direction = None
+ base_entry.blocked_by = sorted(
+ unit_adjacency.get(base_entry.node_id, ())
+ )[:8]
+
+
+def _connectivity_repair(
+ order: list[str],
+ adjacency: dict[str, set[str]],
+) -> list[str]:
+ """Rebuild the order connectivity-first, preserving relative order
+ otherwise: a part that touches nothing placed is DEFERRED until
+ something it mates with has landed (a bracket emitted before the
+ support it hangs from waits those few steps). When neither the stream
+ nor the deferred pool offers a touching part, the earliest deferred
+ part anchors a detached island.
+
+ Reordering may violate a derived (collision-witness) edge: the deferred
+ part's insertion window may have closed. That is deliberate and SAFE —
+ forward verification replays every motion against the final order and
+ demotes a now-colliding insertion to a fade-in. A part fading in
+ attached to the assembly beats a part animating into empty space."""
+ result: list[str] = []
+ placed: set[str] = set()
+ deferred: list[str] = []
+ remaining = list(order)
+
+ def touches(node_id: str) -> bool:
+ return not placed or bool(adjacency.get(node_id, EMPTY_SET) & placed)
+
+ while remaining or deferred:
+ pick = None
+ for index, node_id in enumerate(deferred):
+ if touches(node_id):
+ pick = deferred.pop(index)
+ break
+ if pick is None:
+ while remaining:
+ node_id = remaining.pop(0)
+ if touches(node_id):
+ pick = node_id
+ break
+ deferred.append(node_id)
+ if pick is None:
+ # Nothing anywhere touches: a detached island starts here
+ pick = deferred.pop(0)
+ result.append(pick)
+ placed.add(pick)
+ return result
+
+
+def _preference_topo_sort(
+ planned: list[PlannedComponent],
+ units_by_id: dict[str, _Component],
+ edges: dict[str, set[str]],
+ fasteners: dict[str, _FastenerInfo],
+ joints: dict[str, dict[str, float]],
+ fallback_order: list[str],
+ warnings: list[str],
+ group_members: dict[str, list[str]] | None = None,
+ debug_trace: list | None = None,
+ fastened: set[str] | None = None,
+ contact_count: dict[str, int] | None = None,
+ adjacency: dict[str, set[str]] | None = None,
+ soft_edges: dict[str, set[str]] | None = None,
+) -> list[str]:
+ """Deterministic scored Kahn's sort over the precedence DAG.
+
+ Preferences, in order: the base first; keep runs of identical parts
+ together; SECURING fasteners (they pass through the parts they clamp)
+ install the moment their joint is complete; the DEPENDENCY SPINE —
+ parts that other parts are waiting on (outgoing precedence edges:
+ their insertion window closes, or later parts build on them) precede
+ terminal parts nothing depends on, regardless of size (sliders beat a
+ big badge subassembly); weakly-secured terminal parts (no fastener
+ engages them, nothing must follow them, one seated neighbor, verified
+ clean removal — snap clips, badges) go last of all; then
+ big-and-central structure before small/peripheral; then bottom-up;
+ nodeId breaks ties. Accessory fasteners — threaded mates only,
+ clamping nothing (knobs, set screws) — take no priority jump and
+ schedule like small structure.
+
+ When `adjacency` is given, growth is CONNECTED: each pick must mate with
+ something already placed. A genuinely detached island (fixture,
+ reference geometry — nothing pending touches the placed set) anchors on
+ its own most-connected massive part with a warning; parts never install
+ suspended in space next to nothing.
+ """
+ units = list(units_by_id.values())
+ centroid = _assembly_centroid(units)
+ assembly_min = np.min([unit.bbox_min for unit in units], axis=0)
+ assembly_max = np.max([unit.bbox_max for unit in units], axis=0)
+ diagonal = float(np.linalg.norm(assembly_max - assembly_min)) or 1.0
+
+ # Subassembly units act like fasteners when any member is one (a
+ # washer+screw pair is a fastener stack, not a corridor part)
+ group_members = group_members or {}
+ fastener_units = set(fasteners)
+ for rep_id, members in group_members.items():
+ if any(member in fasteners for member in members):
+ fastener_units.add(rep_id)
+
+ base_id = next(
+ (entry.node_id for entry in planned if entry.tier == "base"), None
+ )
+
+ def is_securing(node_id: str) -> bool:
+ # Securing = clamps a COMPONENT onto the structure (a through-part
+ # that is neither its threaded mate nor the base). Anchor bolts
+ # whose only through-part is the base itself don't jump the queue.
+ for candidate in (node_id, *group_members.get(node_id, ())):
+ info = fasteners.get(candidate)
+ if info is None:
+ continue
+ if any(
+ member not in info.mates and member != base_id
+ for member in joints.get(candidate, ())
+ ):
+ return True
+ return False
+
+ fastened = fastened or set()
+ contact_count = contact_count or {}
+
+ def is_weakly_secured(node_id: str) -> bool:
+ # Terminal snap-ons (clips, badges): no fastener engages them,
+ # nothing is constrained to follow them, they seat against exactly
+ # one structural neighbor, AND their removal is a verified clean
+ # slide (tier 1/2). They assemble as late as their constraints
+ # allow, REGARDLESS of size — a large slide-on cover is still a
+ # terminal attachment. The gates matter on real CAD: fastener
+ # detection is name-only and clearance fits hide contacts, so
+ # without removability evidence this proxy matches half a wire
+ # harness. Anything with an outgoing edge (a slider whose
+ # insertion path a later part closes, a gasket that must precede
+ # its lid) is load-bearing for the sequence and exempt; zero
+ # structural contacts means fastener-positioned; escape/flagged
+ # parts and bbox proxies are never demoted.
+ if node_id in fastener_units:
+ return False
+ entry = by_id[node_id]
+ if entry.tier not in ("linear", "L"):
+ return False
+ if units_by_id[node_id].is_proxy:
+ return False
+ if outgoing(node_id):
+ return False
+ members = (node_id, *group_members.get(node_id, ()))
+ if any(member in fastened for member in members):
+ return False
+ return max(
+ (contact_count.get(member, 0) for member in members), default=0
+ ) == 1
+
+ by_id = {entry.node_id: entry for entry in planned}
+ predecessors: dict[str, set[str]] = {node_id: set() for node_id in edges}
+ for before, afters in edges.items():
+ for after in afters:
+ predecessors[after].add(before)
+
+ soft_edges = soft_edges or {}
+ soft_predecessors: dict[str, set[str]] = {
+ node_id: set() for node_id in edges
+ }
+ for before, afters in soft_edges.items():
+ for after in afters:
+ if after in soft_predecessors:
+ soft_predecessors[after].add(before)
+
+ def outgoing(node_id: str) -> bool:
+ return bool(edges.get(node_id)) or bool(soft_edges.get(node_id))
+
+ placed: list[str] = []
+ placed_set: set[str] = set()
+ pending = set(edges.keys())
+ previous_identity: tuple | None = None
+
+ def identity(node_id: str) -> tuple:
+ entry = by_id[node_id]
+ unit = units_by_id[node_id]
+ motion = entry.motion
+ if motion.get("type") == "linear":
+ motion_key = (
+ "linear",
+ tuple(round(float(c), 3) for c in motion["direction"]),
+ )
+ elif motion.get("type") == "L":
+ motion_key = (
+ "L",
+ tuple(
+ tuple(round(float(c), 3) for c in segment["direction"])
+ for segment in motion["segments"]
+ ),
+ )
+ else:
+ motion_key = (str(motion.get("type")),)
+ return (unit.name, motion_key)
+
+ while pending:
+ available = [
+ node_id
+ for node_id in pending
+ if predecessors[node_id] <= placed_set
+ ]
+ if not available: # cycle — cannot happen for greedy-derived edges
+ warnings.append(
+ "precedence cycle detected; keeping the greedy order for "
+ "the remaining parts"
+ )
+ placed.extend(
+ node_id for node_id in fallback_order if node_id in pending
+ )
+ break
+
+ # Connected growth: prefer parts that mate with the placed set. When
+ # no AVAILABLE part touches but some edge-blocked pending part does,
+ # restrict this pick to that part's unplaced ANCESTORS (the work
+ # that unlocks it) — never wander off to an unrelated floating part.
+ # Only when NOTHING pending touches is the remainder a detached
+ # island: anchor it on its most-connected massive part.
+ if adjacency is not None and placed_set:
+ touching = [
+ node_id
+ for node_id in available
+ if adjacency.get(node_id, EMPTY_SET) & placed_set
+ ]
+ if touching:
+ available = touching
+ else:
+ pending_touchers = [
+ node_id
+ for node_id in pending
+ if adjacency.get(node_id, EMPTY_SET) & placed_set
+ ]
+ if pending_touchers:
+ need: set[str] = set()
+ stack = list(pending_touchers)
+ while stack:
+ node_id = stack.pop()
+ for before in predecessors.get(node_id, EMPTY_SET):
+ if before not in placed_set and before not in need:
+ need.add(before)
+ stack.append(before)
+ gated = [
+ node_id for node_id in available if node_id in need
+ ]
+ if gated:
+ available = gated
+ # else: the DAG forces work outside every toucher's
+ # ancestry before anything can connect — proceed unfiltered
+ else:
+ anchor = max(
+ available,
+ key=lambda node_id: (
+ len(adjacency.get(node_id, ())),
+ _part_volume(units_by_id[node_id]),
+ node_id,
+ ),
+ )
+ warnings.append(
+ f"'{units_by_id[anchor].name or anchor}' starts a "
+ "detached island — nothing already placed touches it"
+ )
+ available = [anchor]
+
+ def sort_key(node_id: str) -> tuple:
+ entry = by_id[node_id]
+ unit = units_by_id[node_id]
+ return (
+ 0 if entry.tier == "base" else 1,
+ 0
+ if previous_identity is not None
+ and identity(node_id) == previous_identity
+ else 1,
+ 0 if is_securing(node_id) else 1,
+ # A flagged structural part whose blockers are still pending
+ # fades in BEFORE they exist (a boxed-in PCB before the lid
+ # that traps it) — a preference, never a DAG edge, so it can
+ # never force a disconnected pick. Flagged fasteners follow
+ # their joints like everything else.
+ 0
+ if (
+ entry.tier == "flagged"
+ and node_id not in fastener_units
+ and any(
+ blocker in pending for blocker in entry.blocked_by
+ )
+ )
+ else 1,
+ # Soft ordering (support stacking, sandwich sides): prefer
+ # parts whose soft prerequisites are already placed — a
+ # PREFERENCE the connectivity filter can override, never a
+ # DAG constraint that forces a mid-air pick
+ 1
+ if soft_predecessors.get(node_id, EMPTY_SET) - placed_set
+ else 0,
+ 0 if outgoing(node_id) else 1,
+ 1 if is_weakly_secured(node_id) else 0,
+ _structural_key(unit, centroid, diagonal),
+ float(unit.bbox_min[2]),
+ node_id,
+ )
+
+ chosen = min(available, key=sort_key)
+ if debug_trace is not None:
+ ranked = sorted(available, key=sort_key)
+ debug_trace.append(
+ [(node_id, sort_key(node_id)) for node_id in ranked[:4]]
+ )
+ placed.append(chosen)
+ placed_set.add(chosen)
+ pending.remove(chosen)
+ previous_identity = identity(chosen)
+
+ if adjacency is not None:
+ placed = _connectivity_repair(placed, adjacency)
+ return placed
+
+
+def _verify_sequence(
+ sequence: list[str],
+ planned_by_id: dict[str, PlannedComponent],
+ units_by_id: dict[str, _Component],
+ trimesh_mod,
+ fasteners: dict[str, _FastenerInfo],
+ path_samples: int,
+ warnings: list[str],
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+) -> None:
+ """Forward replay: each unit's insertion is re-checked against exactly
+ the units already present in the final sequence. By construction this
+ passes; a failure (numerical edge) demotes the part to flagged rather
+ than ever shipping a colliding motion.
+ """
+ from trimesh.collision import CollisionManager
+
+ manager = CollisionManager()
+ samples_segment = max(12, path_samples // 3)
+ for node_id in sequence:
+ entry = planned_by_id[node_id]
+ part = units_by_id[node_id]
+ segments = _removal_segments(entry.motion)
+ if segments is None:
+ entry.verified = entry.tier == "base"
+ else:
+ blockers = _path_blockers(
+ part,
+ manager,
+ segments,
+ samples_segment,
+ fasteners,
+ tolerance=tolerance,
+ )
+ if blockers:
+ warnings.append(
+ f"'{part.name or node_id}' failed forward verification; "
+ "flagged for review — it fades in during playback"
+ )
+ entry.motion = {"type": "none"}
+ entry.tier = "flagged"
+ entry.confidence = "low"
+ entry.removal_direction = None
+ entry.blocked_by = sorted(blockers)[:8]
+ entry.verified = False
+ else:
+ entry.verified = True
+ manager.add_object(node_id, part.mesh)
+
+
+def _part_to_dict(entry: PlannedComponent) -> dict:
+ payload: dict = {"motion": entry.motion}
+ if entry.confidence is not None:
+ payload["confidence"] = entry.confidence
+ if entry.removal_direction is not None:
+ payload["removalDirection"] = entry.removal_direction
+ if entry.blocked_by:
+ payload["blockedBy"] = entry.blocked_by
+ if entry.tier is not None:
+ payload["tier"] = entry.tier
+ if entry.group_id is not None:
+ payload["groupId"] = entry.group_id
+ payload["verified"] = entry.verified
+ return payload
+
+
+def _collect_world_parts(root: AssemblyNode, trimesh_mod) -> list[_Component]:
+ parts: list[_Component] = []
+
+ def visit(node: AssemblyNode, parent_world: np.ndarray) -> None:
+ local = np.asarray(node.transform, dtype=np.float64).reshape(4, 4).T
+ world = parent_world @ local
+ if node.mesh is not None and len(node.mesh.positions) > 0:
+ positions = node.mesh.positions.astype(np.float64)
+ transformed = positions @ world[:3, :3].T + world[:3, 3]
+ mesh = trimesh_mod.Trimesh(
+ vertices=transformed,
+ faces=node.mesh.indices.astype(np.int64),
+ process=False,
+ )
+ parts.append(
+ _Component(
+ node_id=node.node_id,
+ name=node.name,
+ mesh=mesh,
+ bbox_min=transformed.min(axis=0),
+ bbox_max=transformed.max(axis=0),
+ is_proxy=node.mesh.is_proxy,
+ )
+ )
+ for child in node.children:
+ visit(child, world)
+
+ visit(root, np.eye(4))
+ return parts
+
+
+def _seated_pair_depths(
+ parts: list[_Component], trimesh_mod
+) -> dict[frozenset, tuple[float, list, list]]:
+ """Max depth + contact points + contact normals per touching pair.
+
+ One internal broadphase pass over the whole assembly. Feeds fastener
+ mate detection (threaded interference), rigid-group merging, the
+ contact-ring axis estimate for stubby fasteners, and the contact-normal
+ separation candidates (the mating surfaces say how a part comes apart).
+ """
+ from trimesh.collision import CollisionManager
+
+ manager = CollisionManager()
+ for part in parts:
+ manager.add_object(part.node_id, part.mesh)
+
+ pairs: dict[frozenset, tuple[float, list, list, np.ndarray, np.ndarray]] = {}
+ is_colliding, _names, contacts = manager.in_collision_internal(
+ return_names=True, return_data=True
+ )
+ if not is_colliding:
+ return pairs
+ for contact in contacts:
+ pair = frozenset(contact.names)
+ if len(pair) != 2:
+ continue
+ depth, points, normals, tensor, bounds = pairs.get(
+ pair,
+ (
+ 0.0,
+ [],
+ [],
+ np.zeros((3, 3)),
+ np.array([[np.inf] * 3, [-np.inf] * 3]),
+ ),
+ )
+ point = np.asarray(contact.point, dtype=np.float64)
+ bounds = np.array(
+ [np.minimum(bounds[0], point), np.maximum(bounds[1], point)]
+ )
+ if len(points) < 64:
+ points.append(np.asarray(contact.point, dtype=np.float64))
+ normals.append(np.asarray(contact.normal, dtype=np.float64))
+ # Uncapped structure tensor over ALL contact normals: the capped
+ # lists above fill from one contact region and go rank-deficient;
+ # n·nᵀ is also winding-sign invariant
+ normal = np.asarray(contact.normal, dtype=np.float64)
+ length = float(np.linalg.norm(normal))
+ if length > 1e-9:
+ unit = normal / length
+ tensor = tensor + np.outer(unit, unit)
+ pairs[pair] = (
+ max(depth, float(contact.depth)),
+ points,
+ normals,
+ tensor,
+ bounds,
+ )
+ return pairs
+
+
+def _classify_fasteners(
+ parts: list[_Component], pair_depths: dict[frozenset, tuple[float, list]]
+) -> dict[str, _FastenerInfo]:
+ """Symmetry axis + threaded mates for every part with a fastener name.
+
+ A mate is a part the fastener deeply interpenetrates while seated —
+ solid-cylinder thread models overlap their nut/tapped hole by roughly
+ the thread depth. Contacts with mates are exempt only while the
+ fastener travels along its own axis.
+
+ Axis detection is a three-step fallback: SVD symmetry (clean rods and
+ discs) → bbox shape (stubby screws) → the mate-contact ring (flange
+ heads and knobs whose overall shape hides the bore axis — the thread
+ contact points form a cylindrical band whose axis IS the bore).
+
+ Size sanity: hardware is SMALL relative to its assembly. A name-matched
+ part spanning more than MAX_FASTENER_DIAGONAL_FRACTION of the assembly
+ diagonal keeps its structural role — name-only detection otherwise
+ turns housings and rails with spec-suffixed names into "fasteners",
+ fronting them in removal priority and granting them bore exemptions.
+ """
+ assembly_min = np.min([part.bbox_min for part in parts], axis=0)
+ assembly_max = np.max([part.bbox_max for part in parts], axis=0)
+ assembly_diagonal = float(np.linalg.norm(assembly_max - assembly_min))
+ max_extent = max(
+ MAX_FASTENER_EXTENT_MM,
+ MAX_FASTENER_DIAGONAL_FRACTION * assembly_diagonal,
+ )
+
+ fasteners: dict[str, _FastenerInfo] = {}
+ for part in parts:
+ if not _is_fastener(part):
+ continue
+ if float(np.linalg.norm(part.bbox_max - part.bbox_min)) > max_extent:
+ continue
+
+ mates: dict[str, float] = {}
+ mate_points: list = []
+ all_points: list = []
+ for pair, (depth, points, _normals, _tensor, _bounds) in pair_depths.items():
+ if part.node_id not in pair:
+ continue
+ all_points.extend(points)
+ if depth > MATE_MIN_DEPTH_MM:
+ (other,) = pair - {part.node_id}
+ mates[other] = depth
+ mate_points.extend(points)
+
+ # Axis cascade, strongest evidence first: own shape (SVD, bbox),
+ # thread-mate contact band, the FULL seated contact cloud (a knob
+ # with clearance threads still seats on a coaxial boss), and
+ # finally the dominant contact normal.
+ axis_kind = _symmetry_axis_kind(part)
+ if axis_kind is None:
+ axis_kind = _bbox_axis_kind(part)
+ if axis_kind is not None:
+ axis, kind = axis_kind
+ else:
+ ring_axis = _axis_from_contacts(mate_points)
+ if ring_axis is None:
+ ring_axis = _axis_from_contacts(all_points)
+ if ring_axis is None:
+ clusters = _normal_clusters(part.contact_normals, top=1)
+ ring_axis = clusters[0] if clusters else None
+ if ring_axis is None:
+ continue
+ axis, kind = ring_axis, None
+
+ fasteners[part.node_id] = _FastenerInfo(
+ axis=axis,
+ mates=mates,
+ kind=kind,
+ shank_radius=_shank_radius(part, axis, mate_points),
+ )
+ return fasteners
+
+
+def _shank_radius(
+ part: _Component, axis: np.ndarray, mate_points: list
+) -> float | None:
+ """The fastener's shank radius around its axis.
+
+ Threaded-mate contact points sit ON the thread surface — their mean
+ radial distance IS the thread radius. Without mates, the 25th
+ percentile of the part's own radial vertex distances approximates the
+ thin band (the shank) below the head.
+ """
+ center = (part.bbox_min + part.bbox_max) / 2.0
+ if len(mate_points) >= 8:
+ points = np.asarray(mate_points, dtype=np.float64) - center
+ radial = points - np.outer(points @ axis, axis)
+ radius = float(np.linalg.norm(radial, axis=1).mean())
+ else:
+ vertices = np.asarray(part.mesh.vertices, dtype=np.float64)
+ if len(vertices) < 8:
+ return None
+ rel = vertices - center
+ radial = rel - np.outer(rel @ axis, axis)
+ radius = float(np.percentile(np.linalg.norm(radial, axis=1), 25))
+ if radius <= 0.2:
+ return None
+ return radius
+
+
+def _fastener_joints(
+ parts: list[_Component],
+ fasteners: dict[str, _FastenerInfo],
+) -> dict[str, dict[str, float]]:
+ """The parts each fastener joins → their position along its axis.
+
+ Members are threaded mates plus every part whose material radially
+ surrounds the shank (clearance through-holes), each mapped to the
+ projection (mm, along info.axis from the fastener center) of WHERE it
+ engages the shank — the physical stacking order of the joint.
+
+ Ring-containment test: 8 points on a circle of shankRadius × 1.3
+ around the fastener's axis, at three heights across the overlap of the
+ fastener's axis span with the candidate's span. A candidate that
+ surrounds ≥ 6/8 points at any height is part of the joint — it must be
+ installed before the fastener that passes through it.
+ """
+ by_id = {part.node_id: part for part in parts}
+ joints: dict[str, dict[str, float]] = {}
+
+ for fastener_id, info in fasteners.items():
+ part = by_id.get(fastener_id)
+ if part is None:
+ continue
+ center0 = (part.bbox_min + part.bbox_max) / 2.0
+ joint: dict[str, float] = {}
+ for mate in info.mates:
+ mate_part = by_id.get(mate)
+ if mate_part is None:
+ continue
+ mate_center = (mate_part.bbox_min + mate_part.bbox_max) / 2.0
+ joint[mate] = float((mate_center - center0) @ info.axis)
+ radius = info.shank_radius
+ if radius is not None:
+ axis = info.axis
+ center = (part.bbox_min + part.bbox_max) / 2.0
+ seed = (
+ WORLD_AXES[0]
+ if abs(float(axis @ WORLD_AXES[0])) < 0.9
+ else WORLD_AXES[2]
+ )
+ u = np.cross(axis, seed)
+ u = u / (float(np.linalg.norm(u)) or 1.0)
+ v = np.cross(axis, u)
+ # Two probe radii: just outside the shank, and past a generous
+ # clearance hole — surrounding at either radius counts
+ ring_radii = (radius * 1.2, radius * 1.2 + 2.0)
+ angles = np.linspace(0.0, 2.0 * np.pi, 8, endpoint=False)
+ ring_offsets = np.array(
+ [np.cos(a) * u + np.sin(a) * v for a in angles]
+ )
+ f_lo, f_hi = _axis_span(part, axis, center)
+
+ # Cap adaptive probes at a few head-widths: beyond that a "hole"
+ # is an opening, not a fastener bore
+ own = np.asarray(part.mesh.vertices) - center
+ own_radial = own - np.outer(own @ axis, axis)
+ max_radial = float(np.linalg.norm(own_radial, axis=1).max())
+ probe_cap = max_radial * 5.0 + 5.0
+
+ for other in parts:
+ if other.node_id == fastener_id or other.node_id in joint:
+ continue
+ inflate = probe_cap + 2.0
+ if not (
+ np.all(part.bbox_min - inflate <= other.bbox_max)
+ and np.all(other.bbox_min - inflate <= part.bbox_max)
+ ):
+ continue
+ o_lo, o_hi = _axis_span(other, axis, center)
+ lo, hi = max(f_lo, o_lo), min(f_hi, o_hi)
+ if hi - lo < 0.5:
+ continue
+
+ # Candidate-adaptive probe: just outside the candidate's own
+ # bore, so slip-fit clearances (an oversize washer) still read
+ # as "the fastener passes through me"
+ probe_radii = list(ring_radii)
+ probe_heights = [
+ lo + (hi - lo) * fraction
+ for fraction in (0.5, 0.25, 0.75)
+ ]
+ vertices = np.asarray(other.mesh.vertices)
+ projected = (vertices - center) @ axis
+ span_mask = (projected >= lo) & (projected <= hi)
+ in_span = vertices[span_mask]
+ if len(in_span) >= 3:
+ rel = in_span - center
+ radial = np.linalg.norm(
+ rel - np.outer(rel @ axis, axis), axis=1
+ )
+ adaptive = float(radial.min()) * 1.05 + 0.5
+ if adaptive <= probe_cap:
+ probe_radii.append(adaptive)
+ # The bore-rim vertex marks WHERE the candidate's
+ # material actually surrounds the shank (a wide
+ # bracket may only engage in one thin slice that
+ # fixed fractions miss)
+ rim_t = float(
+ projected[span_mask][int(np.argmin(radial))]
+ )
+ probe_heights.append(
+ min(max(rim_t, lo + 0.25), hi - 0.25)
+ )
+
+ surrounded = False
+ surround_t = 0.0
+ for t in probe_heights:
+ for ring_radius in probe_radii:
+ ring = (
+ center + axis * t + ring_offsets * ring_radius
+ )
+ try:
+ inside = other.mesh.contains(ring)
+ except Exception: # non-watertight candidate
+ inside = None
+ if (
+ inside is not None
+ and len(inside) > 0
+ and float(np.mean(inside)) >= 0.75
+ ):
+ surrounded = True
+ surround_t = t
+ break
+ if surrounded:
+ break
+ if surrounded:
+ joint[other.node_id] = float(surround_t)
+ joints[fastener_id] = joint
+ return joints
+
+
+def _axis_span(
+ part: _Component, axis: np.ndarray, origin: np.ndarray
+) -> tuple[float, float]:
+ """The part's bbox extent projected onto an axis line through origin."""
+ corners = np.array(
+ [
+ [
+ part.bbox_min[0] if x == 0 else part.bbox_max[0],
+ part.bbox_min[1] if y == 0 else part.bbox_max[1],
+ part.bbox_min[2] if z == 0 else part.bbox_max[2],
+ ]
+ for x in (0, 1)
+ for y in (0, 1)
+ for z in (0, 1)
+ ]
+ )
+ projected = (corners - origin) @ axis
+ return float(projected.min()), float(projected.max())
+
+
+def _axis_from_contacts(points: list) -> np.ndarray | None:
+ """Bore axis from threaded-mate contact points (a cylindrical band).
+
+ Tries the band's principal directions plus the world axes and keeps
+ the candidate whose perpendicular radii are most uniform — a cylinder
+ fit. Returns None when the points don't read as a cylinder.
+ """
+ if len(points) < 8:
+ return None
+ pts = np.asarray(points, dtype=np.float64)
+ centered = pts - pts.mean(axis=0)
+ try:
+ basis = np.linalg.svd(centered, full_matrices=False)[2]
+ except np.linalg.LinAlgError: # pragma: no cover - degenerate cloud
+ return None
+
+ candidates = [basis[0], basis[2], *WORLD_AXES]
+ best_axis: np.ndarray | None = None
+ best_spread = float("inf")
+ for candidate in candidates:
+ norm = float(np.linalg.norm(candidate))
+ if norm <= 1e-9:
+ continue
+ axis = candidate / norm
+ radial = centered - np.outer(centered @ axis, axis)
+ radii = np.linalg.norm(radial, axis=1)
+ mean_radius = float(radii.mean())
+ if mean_radius <= 1e-6:
+ continue
+ spread = float(radii.std())
+ if spread < best_spread:
+ best_spread = spread
+ best_axis = axis
+ if best_axis is None or best_spread > 0.5:
+ return None
+ for world in WORLD_AXES:
+ if float(np.dot(best_axis, world)) > 0.999:
+ return world.copy()
+ return best_axis
+
+
+def _bbox_axis_kind(part: _Component) -> tuple[np.ndarray, str] | None:
+ """Rod/disc axis from bbox extents when SVD is inconclusive.
+
+ Rod: clearly longest extent is the axis. Disc: clearly thinnest extent
+ is the normal. Near-cubic parts return None (no natural axis).
+ """
+ extents = np.abs(part.bbox_max - part.bbox_min)
+ order = np.argsort(extents) # ascending
+ smallest, mid, largest = (float(extents[i]) for i in order)
+ if mid <= 1e-9:
+ return None
+ axis = np.zeros(3)
+ if largest > 1.4 * mid:
+ axis[order[2]] = 1.0 # rod: along the longest extent
+ return axis, "rod"
+ if smallest < 0.6 * mid:
+ axis[order[0]] = 1.0 # disc: along the thinnest extent
+ return axis, "disc"
+ return None
+
+
+def _embedded_pairs(parts: list[_Component]) -> list[tuple[str, str]]:
+ """(inner, outer) pairs where one part sits fully inside another.
+
+ Fully-embedded solids (logo/text bodies inside their parent) produce
+ NO surface contacts — FCL's mesh collision only sees intersecting
+ surfaces — so containment is tested directly: bbox containment first,
+ then ray-cast `contains` on a sample of the inner part's vertices.
+ """
+ pairs: list[tuple[str, str]] = []
+ epsilon = 0.01
+ for inner in parts:
+ for outer in parts:
+ if inner.node_id == outer.node_id:
+ continue
+ if not (
+ np.all(inner.bbox_min >= outer.bbox_min - epsilon)
+ and np.all(inner.bbox_max <= outer.bbox_max + epsilon)
+ ):
+ continue
+ vertices = np.asarray(inner.mesh.vertices)
+ if len(vertices) == 0:
+ continue
+ sample = vertices[:: max(1, len(vertices) // 24)][:24]
+ try:
+ inside = outer.mesh.contains(sample)
+ except Exception: # non-watertight outer mesh — skip
+ continue
+ if len(inside) > 0 and float(np.mean(inside)) > 0.8:
+ pairs.append((inner.node_id, outer.node_id))
+ return pairs
+
+
+def _merge_rigid_groups(
+ parts: list[_Component],
+ pair_depths: dict[frozenset, tuple[float, list, list, np.ndarray, np.ndarray]],
+ fasteners: dict[str, _FastenerInfo],
+ trimesh_mod,
+ warnings: list[str],
+) -> tuple[list[_Component], dict[str, str]]:
+ """Union-find over rigidly bound pairs.
+
+ Two ways a pair can never separate by a rigid motion: deep seated
+ surface interpenetration (press fits) and full containment (embedded
+ logo/text solids). Each cluster plans as one unit — the combined mesh
+ under the largest member's nodeId. Returns the reduced part list plus
+ member nodeId → representative nodeId.
+ """
+ parent: dict[str, str] = {part.node_id: part.node_id for part in parts}
+
+ def find(node_id: str) -> str:
+ while parent[node_id] != node_id:
+ parent[node_id] = parent[parent[node_id]]
+ node_id = parent[node_id]
+ return node_id
+
+ def union(a: str, b: str) -> None:
+ root_a, root_b = find(a), find(b)
+ if root_a != root_b:
+ parent[root_b] = root_a
+
+ for inner, outer in _embedded_pairs(parts):
+ union(inner, outer)
+
+ clusters: dict[str, list[_Component]] = {}
+ for part in parts:
+ clusters.setdefault(find(part.node_id), []).append(part)
+
+ def bbox_volume(part: _Component) -> float:
+ extents = part.bbox_max - part.bbox_min
+ return float(abs(extents[0] * extents[1] * extents[2]))
+
+ units: list[_Component] = []
+ merged_into: dict[str, str] = {}
+ for members in clusters.values():
+ if len(members) == 1:
+ units.append(members[0])
+ continue
+ # A fastener member becomes the representative so the unit keeps
+ # its bore axis and mate exemptions (a knob merged with its
+ # coincident variant must still unscrew)
+ rep = max(
+ members,
+ key=lambda member: (
+ 1 if member.node_id in fasteners else 0,
+ bbox_volume(member),
+ ),
+ )
+ combined = trimesh_mod.util.concatenate(
+ [member.mesh for member in members]
+ )
+ # Concatenated soups are not watertight — carry the honest volume
+ combined._carbon_volume = sum(
+ _part_volume(member) for member in members
+ )
+ units.append(
+ _Component(
+ node_id=rep.node_id,
+ name=rep.name,
+ mesh=combined,
+ bbox_min=np.min([m.bbox_min for m in members], axis=0),
+ bbox_max=np.max([m.bbox_max for m in members], axis=0),
+ is_proxy=any(m.is_proxy for m in members),
+ )
+ )
+ for member in members:
+ if member.node_id != rep.node_id:
+ merged_into[member.node_id] = rep.node_id
+ names = ", ".join(
+ f"'{member.name or member.node_id}'" for member in members
+ )
+ warnings.append(
+ f"{names} interpenetrate when seated; planned as one rigid unit"
+ )
+ return units, merged_into
+
+
+def _symmetry_axis_kind(part: _Component) -> tuple[np.ndarray, str] | None:
+ """The natural insertion axis of a fastener-like part, with its kind.
+
+ Rod-like parts (bolts, pins, screws: one dominant extent) insert along
+ their long axis; disc-like parts (washers, nuts: two equal dominant
+ extents) insert along their normal. Returns None for parts without a
+ clear axis.
+ """
+ vertices = np.asarray(part.mesh.vertices)
+ if len(vertices) < 3:
+ return None
+ centered = vertices - vertices.mean(axis=0)
+ try:
+ singular, basis = np.linalg.svd(centered, full_matrices=False)[1:]
+ except np.linalg.LinAlgError: # pragma: no cover - degenerate mesh
+ return None
+ s1, s2, s3 = (float(s) for s in singular[:3])
+ if s2 <= 1e-9:
+ return None
+ if s1 > 1.4 * s2:
+ axis, kind = basis[0], "rod" # rod: dominant extent is the axis
+ elif s3 > 1e-9 and s2 > 1.4 * s3 and s1 < 1.25 * s2:
+ axis, kind = basis[2], "disc" # disc: the normal is the smallest extent
+ else:
+ return None
+ norm = np.linalg.norm(axis)
+ if norm <= 1e-9:
+ return None
+ axis = axis / norm
+ # Snap near-axis-aligned directions to clean world axes (stable plan
+ # output, and identical fasteners group on exact direction matches)
+ for world in WORLD_AXES:
+ if float(np.dot(axis, world)) > 0.999:
+ return world.copy(), kind
+ return axis, kind
+
+
+def _symmetry_axis(part: _Component) -> np.ndarray | None:
+ result = _symmetry_axis_kind(part)
+ return result[0] if result is not None else None
+
+
+def _normal_clusters(normals: list, top: int = 3) -> list[np.ndarray]:
+ """Dominant contact-normal directions (greedy clustering by support)."""
+ clusters: list[tuple[np.ndarray, int]] = []
+ for normal in normals:
+ length = float(np.linalg.norm(normal))
+ if length <= 1e-9:
+ continue
+ unit = np.asarray(normal, dtype=np.float64) / length
+ for index, (center, count) in enumerate(clusters):
+ if abs(float(center @ unit)) > 0.95:
+ clusters[index] = (center, count + 1)
+ break
+ else:
+ clusters.append((unit, 1))
+ clusters.sort(key=lambda entry: -entry[1])
+ results: list[np.ndarray] = []
+ for center, _count in clusters[:top]:
+ snapped = center
+ for world in WORLD_AXES:
+ if abs(float(center @ world)) > 0.999:
+ snapped = world.copy() if float(center @ world) > 0 else -world
+ break
+ results.append(snapped)
+ return results
+
+
+def _candidate_directions(part: _Component) -> list[np.ndarray]:
+ """Removal directions to try, most natural first.
+
+ A part's own symmetry axis comes first, then the dominant seated
+ CONTACT NORMALS (the mating surfaces say how the part separates — a
+ plate on a tilted plane offers the tilted lift no world axis can),
+ then the world axes. Deduplication is sign-sensitive: +X and -X are
+ different removal directions (a part boxed in on one side exits the
+ other), so only same-direction duplicates are dropped.
+ """
+ candidates: list[np.ndarray] = []
+ axis = _symmetry_axis(part)
+ if axis is not None:
+ candidates.extend([axis, -axis])
+
+ for normal in _normal_clusters(part.contact_normals):
+ for candidate in (normal, -normal):
+ if all(float(np.dot(candidate, c)) < 0.999 for c in candidates):
+ candidates.append(candidate)
+
+ for world in WORLD_AXES:
+ if all(float(np.dot(world, c)) < 0.999 for c in candidates):
+ candidates.append(world)
+ return candidates
+
+
+def _greedy_disassembly(
+ parts: list[_Component],
+ trimesh_mod,
+ clearance: float,
+ path_samples: int,
+ warnings: list[str] | None = None,
+ fasteners: dict[str, _FastenerInfo] | None = None,
+ group_units: dict[str, tuple[_Component, list[str]]] | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ late_merges: dict[str, str] | None = None,
+ deep_bitten: set[str] | None = None,
+ sandwiched: set[str] | None = None,
+ protected: set[str] | None = None,
+) -> tuple[list[PlannedComponent], list[str], dict]:
+ from trimesh.collision import CollisionManager
+
+ if warnings is None:
+ warnings = []
+ if fasteners is None:
+ fasteners = {}
+ if sandwiched is None:
+ sandwiched = set()
+
+ by_id = {part.node_id: part for part in parts}
+ remaining: dict[str, _Component] = dict(by_id)
+
+ manager = CollisionManager()
+ full_manager = CollisionManager()
+ for part in parts:
+ manager.add_object(part.node_id, part.mesh)
+ full_manager.add_object(part.node_id, part.mesh)
+
+ removal_order: list[PlannedComponent] = []
+ group_mesh_cache: dict = {}
+ stuck_blockers_cache: dict[str, list[str]] = {}
+ # "forced" and "unplanned" stay at 0 for stats compatibility: the
+ # planner no longer fabricates motions — unsolvable parts are "flagged".
+ # "group" counts subassembly units (each covering 2+ parts).
+ tiers = {
+ "linear": 0,
+ "l": 0,
+ "escape": 0,
+ "group": 0,
+ "flagged": 0,
+ "forced": 0,
+ "unplanned": 0,
+ }
+
+ centroid = _assembly_centroid(parts)
+ _amin = np.min([p.bbox_min for p in parts], axis=0)
+ _amax = np.max([p.bbox_max for p in parts], axis=0)
+ assembly_diagonal = float(np.linalg.norm(_amax - _amin)) or 1.0
+
+ def removal_priority(pool: dict[str, _Component]) -> list[_Component]:
+ # Fasteners come off first (so they assemble last, after the parts
+ # they secure), then small/peripheral structure — the biggest, most
+ # central part survives to become the base; nodeId keeps ties
+ # stable. Deliberately NOT sensitive to the weakly-secured signal:
+ # this ranking schedules expensive removal attempts and picks
+ # flag/merge victims, and fronting hard-to-remove one-contact
+ # parts (cables, interlocked clips) multiplies failed sweeps.
+ # "Terminal parts last" is a display preference — the topo sort
+ # owns it.
+ return sorted(
+ pool.values(),
+ key=lambda p: (
+ 0 if p.node_id in fasteners else 1,
+ tuple(
+ -component
+ for component in _structural_key(
+ p, centroid, assembly_diagonal
+ )
+ ),
+ p.node_id,
+ ),
+ )
+
+ progressed = True
+ while remaining and progressed:
+ progressed = False
+ for part in removal_priority(remaining):
+ if len(remaining) == 1:
+ # The last part is the base: it "assembles" by being placed
+ remaining.pop(part.node_id)
+ removal_order.append(
+ PlannedComponent(
+ node_id=part.node_id,
+ motion={"type": "none"},
+ confidence="high",
+ removal_direction=None,
+ tier="base",
+ )
+ )
+ progressed = True
+ break
+
+ # Pull the part out of the broadphase for its own tests —
+ # re-registering the same CollisionObject avoids the BVH
+ # rebuild that trimesh's remove/add cycle would pay, and the
+ # sweep stops enumerating self-contacts at every sample
+ with (
+ _unregistered(manager, [part.node_id]),
+ _unregistered(full_manager, [part.node_id]),
+ ):
+ planned = _plan_removal(
+ part,
+ remaining,
+ manager,
+ clearance,
+ path_samples,
+ fasteners,
+ tolerance,
+ full_manager=full_manager,
+ )
+
+ if planned is not None:
+ manager.remove_object(part.node_id)
+ tiers["linear" if planned.tier == "linear" else "l"] += 1
+ removal_order.append(planned)
+ remaining.pop(part.node_id)
+ progressed = True
+ # Restart the scan: every removal changes what the priority
+ # order should try next (a freed fastener, a newly exposed
+ # peripheral part) — continuing down the stale list lets the
+ # wrong part slip out first
+ break
+
+ if not progressed and len(remaining) > 1:
+ # Tier 3: adaptive multi-segment escape for interlocked parts
+ for part in removal_priority(remaining):
+ with _unregistered(manager, [part.node_id]):
+ planned = _plan_escape(
+ part,
+ remaining,
+ manager,
+ path_samples,
+ fasteners,
+ tolerance,
+ )
+
+ if planned is not None:
+ manager.remove_object(part.node_id)
+ tiers["escape"] += 1
+ removal_order.append(planned)
+ remaining.pop(part.node_id)
+ progressed = True
+ # Resume the cheap greedy scan: freeing one part often
+ # unlocks straight-line removals for its neighbors
+ break
+
+ if not progressed and len(remaining) > 1:
+ # Removability-evidence merge: a stuck part whose bbox overlaps
+ # exactly ONE remaining neighbor can never separate from it (a
+ # captive SEMS washer on its screw, coincident CAD variants of
+ # one knob) — they are one rigid unit, by definition. The pair
+ # continues as the neighbor.
+ merged_here = False
+ for part in removal_priority(remaining)[:8]:
+ if part.node_id in sandwiched:
+ # A compliant part pressed into its flange is NOT a
+ # rigid unit with it — never merge a gasket into a lid
+ continue
+ if protected and part.node_id in protected:
+ # A caller-authored unit (a populated PCB) never loses
+ # its identity by riding another part's step — a stuck
+ # unit flags and fades in as its own step instead
+ continue
+ cached = stuck_blockers_cache.get(part.node_id)
+ if cached is not None and all(
+ blocker in remaining for blocker in cached
+ ):
+ blockers = cached
+ else:
+ blockers = _escape_blockers(
+ part,
+ remaining,
+ manager,
+ fasteners,
+ tolerance,
+ path_samples,
+ )
+ stuck_blockers_cache[part.node_id] = blockers
+ if len(blockers) != 1:
+ continue
+ host_id = blockers[0]
+ host = remaining.get(host_id)
+ if host is None or host_id in sandwiched:
+ continue
+ if protected and host_id in protected:
+ # Caller-authored units are a FIXED grouping — parts never
+ # join them either (an enclosure "captive" around a
+ # populated PCB is a separate step, not a rider)
+ continue
+ combined_mesh = trimesh_mod.util.concatenate(
+ [host.mesh, part.mesh]
+ )
+ combined_mesh._carbon_volume = _part_volume(
+ host
+ ) + _part_volume(part)
+ merged_allowance = {**part.seated_allowance, **host.seated_allowance}
+ merged_axes = {
+ **part.seated_allowance_axes,
+ **host.seated_allowance_axes,
+ }
+ for stale in (host.node_id, part.node_id):
+ merged_allowance.pop(stale, None)
+ merged_axes.pop(stale, None)
+ combined = _Component(
+ node_id=host.node_id,
+ name=host.name,
+ mesh=combined_mesh,
+ bbox_min=np.minimum(host.bbox_min, part.bbox_min),
+ bbox_max=np.maximum(host.bbox_max, part.bbox_max),
+ is_proxy=host.is_proxy or part.is_proxy,
+ seated_allowance=merged_allowance,
+ seated_allowance_axes=merged_axes,
+ )
+ warnings.append(
+ f"'{part.name or part.node_id}' cannot separate from "
+ f"'{host.name or host_id}'; planned as one rigid unit"
+ )
+ manager.remove_object(part.node_id)
+ manager.remove_object(host_id)
+ manager.add_object(host_id, combined.mesh)
+ remaining.pop(part.node_id)
+ remaining[host_id] = combined
+ if late_merges is not None:
+ late_merges[part.node_id] = host_id
+ progressed = True
+ merged_here = True
+ break
+ if merged_here:
+ continue
+
+ if not progressed and len(remaining) > 2:
+ # Subassembly extraction: mutually interlocked parts (a keyed
+ # hub, a slider with its captive lock) often remove cleanly as
+ # one unit. Members animate together as a single step.
+ group = _plan_group_removal(
+ remaining,
+ manager,
+ path_samples,
+ fasteners,
+ trimesh_mod,
+ combined_cache=group_mesh_cache,
+ tolerance=tolerance,
+ deep_bitten=deep_bitten,
+ )
+ if (
+ group is not None
+ and protected
+ and any(member in protected for member in group[0])
+ ):
+ # Caller-authored units keep their own step — never absorb
+ # one into an extracted interlock group
+ group = None
+ if group is not None:
+ members, combined, entry = group
+ for member_id in members:
+ manager.remove_object(member_id)
+ remaining.pop(member_id)
+ removal_order.append(entry)
+ if group_units is not None:
+ group_units[entry.node_id] = (combined, members)
+ tiers["group"] = tiers.get("group", 0) + 1
+ progressed = True
+ continue
+
+ if not progressed and len(remaining) > 1:
+ # No collision-free escape exists. Flag the part — motion "none",
+ # blockers recorded, the viewer fades it in. Never fabricate a
+ # motion through geometry. Removing it from the working set gives
+ # its neighbors another chance at a clean removal.
+ part = removal_priority(remaining)[0]
+ manager.remove_object(part.node_id)
+ warnings.append(
+ f"'{part.name or part.node_id}' has no collision-free escape; "
+ "flagged for review — it fades in during playback"
+ )
+ removal_order.append(
+ PlannedComponent(
+ node_id=part.node_id,
+ motion={"type": "none"},
+ confidence="low",
+ removal_direction=None,
+ blocked_by=_escape_blockers(
+ part,
+ remaining,
+ manager,
+ fasteners,
+ tolerance,
+ path_samples,
+ )
+ or _blockers(part, remaining, trimesh_mod),
+ tier="flagged",
+ )
+ )
+ tiers["flagged"] += 1
+ remaining.pop(part.node_id)
+ progressed = True
+
+ # Assembly order = removal order reversed (base out last -> placed first)
+ sequence = [entry.node_id for entry in reversed(removal_order)]
+ return removal_order, sequence, tiers
+
+
+def _mesh_bvh(mesh):
+ """FCL BVH for a mesh, built once and cached on the mesh object.
+
+ trimesh's `in_collision_single` rebuilds the BVH on every call, which
+ dominated planning time (hours on real assemblies); caching turns each
+ path sample into a pure narrowphase query.
+ """
+ bvh = getattr(mesh, "_carbon_bvh", None)
+ if bvh is None:
+ from trimesh.collision import mesh_to_BVH
+
+ bvh = mesh_to_BVH(mesh)
+ mesh._carbon_bvh = bvh
+ return bvh
+
+
+@contextmanager
+def _unregistered(manager, node_ids):
+ """Temporarily pull parts out of the broadphase during their own sweep.
+
+ A moving part left registered collides with its own seated copy at
+ EVERY sample — thousands of triangle-pair contacts enumerated in C,
+ wrapped into Python objects, then discarded by name-filtering (the
+ self exemption). Profiled at ~86% of total planning time on the seat
+ rail (53M contact constructions). Unregistering re-registers the SAME
+ CollisionObject afterward, so the historical BVH-rebuild cost of
+ trimesh's remove/add cycle never happens — the BVH lives on the
+ geometry, not the registration. Name-based self exemptions stay in
+ place as belt-and-suspenders for callers that can't unregister.
+ """
+ entries = []
+ if manager is not None:
+ objs = getattr(manager, "_objs", {})
+ entries = [objs[n]["obj"] for n in node_ids if n in objs]
+ for obj in entries:
+ manager._manager.unregisterObject(obj)
+ if entries:
+ manager._manager.update()
+ try:
+ yield
+ finally:
+ for obj in entries:
+ manager._manager.registerObject(obj)
+ if entries:
+ manager._manager.update()
+
+
+def _contacts_at(
+ manager, part: _Component, translation: np.ndarray
+) -> list[tuple[str | None, float]]:
+ """(otherName, depth) contacts of `part` translated by `translation`
+ against the manager's objects.
+
+ The moving part may still be registered in the manager — callers
+ exempt it by name (its own geometry reports name None here).
+ """
+ import fcl
+
+ bvh = _mesh_bvh(part.mesh)
+ obj = fcl.CollisionObject(bvh, fcl.Transform(np.eye(3), translation))
+ cdata = fcl.CollisionData(
+ request=fcl.CollisionRequest(
+ num_max_contacts=100000, enable_contact=True
+ )
+ )
+ manager._manager.collide(obj, cdata, fcl.defaultCollisionCallback)
+ if not cdata.result.is_collision:
+ return []
+ contacts: list[tuple[str | None, float]] = []
+ for contact in cdata.result.contacts:
+ geometry = contact.o1 if contact.o1 != bvh else contact.o2
+ contacts.append(
+ (
+ manager._names.get(id(geometry)),
+ float(contact.penetration_depth),
+ )
+ )
+ return contacts
+
+
+def _self_exempt(
+ exempt: dict[str, float] | None, self_ids
+) -> dict[str, float]:
+ """Merge an infinite allowance for the moving part(s) into `exempt`.
+
+ The moving part stays registered in the manager (removing and
+ re-adding it rebuilds its BVH), so its contacts against its own seated
+ copy are filtered here by name instead.
+ """
+ merged = dict(exempt) if exempt else {}
+ ids = [self_ids] if isinstance(self_ids, str) else self_ids
+ for node_id in ids:
+ merged[node_id] = float("inf")
+ return merged
+
+
+def _head_direction(
+ part: _Component,
+ info: _FastenerInfo,
+ units_by_id: dict[str, _Component] | None = None,
+) -> np.ndarray:
+ """Tip → head sense of a fastener's axis.
+
+ The head end is the fastener's widest end (flange, hex, button) — an
+ intrinsic property immune to mate misclassification (a snug
+ counterbore can read as thread-deep interference). Symmetric parts
+ (studs, pins) fall back to pointing away from their mates.
+ """
+ axis = info.axis
+ vertices = np.asarray(part.mesh.vertices, dtype=np.float64)
+ if len(vertices) >= 8:
+ center = (part.bbox_min + part.bbox_max) / 2.0
+ rel = vertices - center
+ proj = rel @ axis
+ radial = np.linalg.norm(rel - np.outer(proj, axis), axis=1)
+ span = float(proj.max() - proj.min())
+ if span > 1e-6:
+ head_side = proj > span * 0.25
+ tip_side = proj < -span * 0.25
+ hi = float(radial[head_side].max()) if np.any(head_side) else 0.0
+ lo = float(radial[tip_side].max()) if np.any(tip_side) else 0.0
+ if abs(hi - lo) > 0.2:
+ return axis if hi > lo else -axis
+
+ if units_by_id and info.mates:
+ mate_centers = [
+ (units_by_id[m].bbox_min + units_by_id[m].bbox_max) / 2.0
+ for m in info.mates
+ if m in units_by_id
+ ]
+ if mate_centers:
+ f_center = (part.bbox_min + part.bbox_max) / 2.0
+ away = f_center - np.mean(mate_centers, axis=0)
+ if float(away @ axis) < 0:
+ return -axis
+ return axis
+
+
+def _mate_exempt(
+ part: _Component,
+ direction: np.ndarray,
+ fasteners: dict[str, _FastenerInfo],
+) -> dict[str, float] | None:
+ """Bore-engagement allowances for this part along this direction.
+
+ Only a fastener travelling along its own axis unscrews through its
+ mate and slides through its joint's holes/counterbores; any other
+ part/direction is judged strictly against everything.
+ """
+ info = fasteners.get(part.node_id)
+ if info is None or (not info.mates and not info.sliding):
+ return None
+ if abs(float(np.dot(direction, info.axis))) > 0.99:
+ return {**info.sliding, **info.mates}
+ return None
+
+
+def _seated_exempt(
+ part: _Component, direction: np.ndarray
+) -> dict[str, float] | None:
+ """Sandwich-squish allowances valid along this direction.
+
+ Like `_mate_exempt`, axis-gated: a compliant part separates from its
+ flange along the sandwich axis (and the flange lifts off along the
+ same axis); motion in any other direction is judged strictly, so a
+ misclassified part can never slide laterally through real geometry.
+ """
+ if not part.seated_allowance:
+ return None
+ allowed = {
+ partner: depth
+ for partner, depth in part.seated_allowance.items()
+ if abs(
+ float(np.dot(direction, part.seated_allowance_axes[partner]))
+ )
+ > 0.99
+ }
+ return allowed or None
+
+
+def _plan_removal(
+ part: _Component,
+ remaining: dict[str, _Component],
+ manager,
+ clearance: float,
+ path_samples: int,
+ fasteners: dict[str, _FastenerInfo],
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ full_manager=None,
+) -> PlannedComponent | None:
+ others = [p for p in remaining.values() if p.node_id != part.node_id]
+ if not others:
+ return None
+
+ static_min = np.min([p.bbox_min for p in others], axis=0)
+ static_max = np.max([p.bbox_max for p in others], axis=0)
+
+ # Named fasteners only ever exit through their bore: their axis, both
+ # senses — the sense pointing AWAY from their threaded mates first, so
+ # a screw backs out of its hole instead of tunneling deeper through the
+ # threads. Everything else tries its symmetry axis then the world axes.
+ info = fasteners.get(part.node_id)
+ if _is_fastener(part) and info is not None:
+ head = _head_direction(part, info, remaining)
+ directions = [head, -head]
+ else:
+ directions = _candidate_directions(part)
+
+ # Tier 1: straight line. Collect EVERY clear direction, then pick the
+ # least entangling one: the sweep with the fewest blockers against the
+ # FULL seated assembly (parts already removed in disassembly assemble
+ # later — a sweep through their seats manufactures precedence edges
+ # that drag this part early in the sequence for no reason).
+ clear: list[tuple[int, np.ndarray, float]] = []
+ for index, direction in enumerate(directions):
+ travel = _exit_travel(part, static_min, static_max, direction)
+ if travel <= 0:
+ continue
+ separation = _separation_distance(
+ part.bbox_min, part.bbox_max, static_min, static_max, direction
+ )
+ last_touch = _path_is_clear(
+ part,
+ manager,
+ direction,
+ 0.0,
+ travel,
+ path_samples,
+ tolerance,
+ exempt=_self_exempt(
+ _mate_exempt(part, direction, fasteners), part.node_id
+ ),
+ check_until=separation + 2 * MAX_SAMPLE_SPACING_MM,
+ )
+ if last_touch is not None:
+ clear.append(
+ (
+ index,
+ direction,
+ _recorded_travel(part, direction, travel, last_touch),
+ )
+ )
+
+ if clear:
+ if len(clear) == 1 or full_manager is None:
+ _index, direction, recorded = clear[0]
+ else:
+ samples_segment = max(12, path_samples // 3)
+
+ def entanglement(candidate: tuple[int, np.ndarray, float]) -> tuple:
+ index, direction, recorded = candidate
+ blockers = _path_blockers(
+ part,
+ full_manager,
+ [(direction, recorded)],
+ samples_segment,
+ fasteners,
+ extra_exempt={part.node_id: float("inf")},
+ tolerance=tolerance,
+ )
+ # Tie-break by candidate order, NOT travel: the direction
+ # list already ranks natural exits first (own axis /
+ # away-from-mate before world axes)
+ return (len(blockers), index)
+
+ _index, direction, recorded = min(clear, key=entanglement)
+ confidence = "low" if part.is_proxy else "high"
+ return PlannedComponent(
+ node_id=part.node_id,
+ motion={
+ "type": "linear",
+ "direction": [-float(c) for c in direction],
+ "distance": recorded,
+ },
+ confidence=confidence,
+ removal_direction=[float(c) for c in direction],
+ tier="linear",
+ )
+
+ # Tier 2: lift then slide ("L"). First segment is a short escape hop,
+ # the second exits the assembly.
+ part_size = part.bbox_max - part.bbox_min
+ hop = float(np.linalg.norm(part_size)) or 1.0
+ samples_segment = max(12, path_samples // 3)
+ for first in WORLD_AXES:
+ if (
+ _path_is_clear(
+ part,
+ manager,
+ first,
+ 0.0,
+ hop,
+ samples_segment,
+ tolerance,
+ exempt=_self_exempt(
+ _mate_exempt(part, first, fasteners), part.node_id
+ ),
+ )
+ is None
+ ):
+ continue
+ offset = first * hop
+ for second in WORLD_AXES:
+ if abs(float(np.dot(first, second))) > 0.99:
+ continue
+ travel = _exit_travel(part, static_min, static_max, second, offset)
+ if travel <= 0:
+ continue
+ separation = _separation_distance(
+ part.bbox_min + offset,
+ part.bbox_max + offset,
+ static_min,
+ static_max,
+ second,
+ )
+ second_touch = _path_is_clear(
+ part,
+ manager,
+ second,
+ 0.0,
+ travel,
+ samples_segment,
+ tolerance,
+ base_offset=offset,
+ exempt=_self_exempt(
+ _mate_exempt(part, second, fasteners), part.node_id
+ ),
+ check_until=separation + 2 * MAX_SAMPLE_SPACING_MM,
+ )
+ if second_touch is not None:
+ # Insertion motion reverses the removal: slide in, then drop
+ return PlannedComponent(
+ node_id=part.node_id,
+ motion={
+ "type": "L",
+ "segments": [
+ {
+ "direction": [-float(c) for c in second],
+ "distance": _recorded_travel(
+ part, second, travel, second_touch
+ ),
+ },
+ {
+ "direction": [-float(c) for c in first],
+ "distance": round(hop, 3),
+ },
+ ],
+ },
+ confidence="low",
+ removal_direction=[float(c) for c in first],
+ tier="L",
+ )
+
+ return None
+
+
+def _plan_escape(
+ part: _Component,
+ remaining: dict[str, _Component],
+ manager,
+ path_samples: int,
+ fasteners: dict[str, _FastenerInfo],
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+) -> PlannedComponent | None:
+ """Tier 3: BFS over axis-aligned hops until the part clears the assembly.
+
+ Unlike tier 2's fixed lift-then-slide, each hop travels as far as the
+ free space allows (a blind slot needs "slide to the end, lift, slide
+ out" — hop lengths the fixed search cannot guess). The removal segments
+ reverse into a multi-segment "L" insertion motion, which the viewer
+ already interpolates for any segment count.
+ """
+ from collections import deque
+
+ others = [p for p in remaining.values() if p.node_id != part.node_id]
+ if not others:
+ return None
+
+ static_min = np.min([p.bbox_min for p in others], axis=0)
+ static_max = np.max([p.bbox_max for p in others], axis=0)
+
+ part_diagonal = float(np.linalg.norm(part.bbox_max - part.bbox_min)) or 1.0
+ min_hop = max(part_diagonal * MIN_HOP_FRACTION, 2.0)
+ hop_cap = part_diagonal * 1.5
+ samples_segment = max(12, path_samples // 3)
+ directions = _candidate_directions(part)
+
+ queue: deque[tuple[np.ndarray, list[tuple[np.ndarray, float]]]] = deque(
+ [(np.zeros(3), [])]
+ )
+ visited = {(0, 0, 0)}
+ expansions = 0
+
+ while queue and expansions < MAX_ESCAPE_EXPANSIONS:
+ offset, segments = queue.popleft()
+ expansions += 1
+ for direction in directions:
+ # Never double back along the previous hop
+ if segments and abs(float(np.dot(direction, segments[-1][0]))) > 0.99:
+ continue
+ exempt = _self_exempt(
+ _mate_exempt(part, direction, fasteners), part.node_id
+ )
+
+ # Can the part exit straight from here?
+ travel = _exit_travel(
+ part, static_min, static_max, direction, base_offset=offset
+ )
+ separation = _separation_distance(
+ part.bbox_min + offset,
+ part.bbox_max + offset,
+ static_min,
+ static_max,
+ direction,
+ )
+ if travel > 0:
+ exit_touch = _path_is_clear(
+ part,
+ manager,
+ direction,
+ 0.0,
+ travel,
+ samples_segment,
+ tolerance,
+ base_offset=offset,
+ exempt=exempt,
+ check_until=separation + 2 * MAX_SAMPLE_SPACING_MM,
+ )
+ if exit_touch is not None:
+ removal = segments + [
+ (
+ direction,
+ _recorded_travel(part, direction, travel, exit_touch),
+ )
+ ]
+ return _removal_segments_to_planned(part, removal)
+
+ if len(segments) + 1 >= MAX_ESCAPE_SEGMENTS:
+ continue
+
+ # Otherwise hop as far as the free space allows and search on
+ free = _free_travel(
+ part,
+ manager,
+ direction,
+ offset,
+ hop_cap,
+ samples_segment,
+ exempt=exempt,
+ tolerance=tolerance,
+ )
+ if free < min_hop:
+ continue
+ new_offset = offset + direction * free
+ key = tuple(int(round(float(c) / min_hop)) for c in new_offset)
+ if key in visited:
+ continue
+ visited.add(key)
+ queue.append((new_offset, segments + [(direction, float(free))]))
+
+ return None
+
+
+def _group_exempt(
+ members: list[_Component],
+ direction: np.ndarray,
+ fasteners: dict[str, _FastenerInfo],
+ member_ids: set[str],
+) -> dict[str, float] | None:
+ """Merged threaded-mate allowances for a group moving along `direction`.
+
+ A member fastener aligned with the travel keeps its mate allowance
+ (the group can unscrew off an external mate); mates inside the group
+ are irrelevant — members are absent from the manager during the test.
+ """
+ merged: dict[str, float] = {}
+ for member in members:
+ exempt = _mate_exempt(member, direction, fasteners)
+ if exempt:
+ # Mates AND sliding joints: a knob pair leaving through the
+ # opening of the bracket it threads through keeps its sliding
+ # engagement
+ for mate, depth in exempt.items():
+ if mate in member_ids:
+ continue
+ if depth > merged.get(mate, 0.0):
+ merged[mate] = depth
+ # A member's compliant squish against an external sandwich partner
+ # travels with the group (a lid leaving with its gasket attached),
+ # axis-gated like everything else
+ seated = _seated_exempt(member, direction)
+ if seated:
+ for partner, depth in seated.items():
+ if partner in member_ids:
+ continue
+ if depth > merged.get(partner, 0.0):
+ merged[partner] = depth
+ return merged or None
+
+
+def _plan_group_removal(
+ remaining: dict[str, _Component],
+ manager,
+ path_samples: int,
+ fasteners: dict[str, _FastenerInfo],
+ trimesh_mod,
+ combined_cache: dict | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ deep_bitten: set[str] | None = None,
+) -> tuple[list[str], _Component, PlannedComponent] | None:
+ """Find a connected subassembly that removes as one unit.
+
+ Candidate groups grow from a seed part through a proximity graph
+ (bboxes inflated by GROUP_PROXIMITY_MM — clearance fits produce no
+ surface contacts), adding the smallest neighbor first (attachments —
+ keys, locks, knobs — are small). Members translate together; the
+ combined unit is registered under the largest member's nodeId.
+ """
+ parts = list(remaining.values())
+ if len(parts) <= 2:
+ return None
+
+ adjacency: dict[str, set[str]] = {part.node_id: set() for part in parts}
+ for index, a in enumerate(parts):
+ for b in parts[index + 1 :]:
+ if np.all(
+ a.bbox_min - GROUP_PROXIMITY_MM <= b.bbox_max
+ ) and np.all(b.bbox_min - GROUP_PROXIMITY_MM <= a.bbox_max):
+ adjacency[a.node_id].add(b.node_id)
+ adjacency[b.node_id].add(a.node_id)
+
+ def diagonal(part: _Component) -> float:
+ return float(np.linalg.norm(part.bbox_max - part.bbox_min))
+
+ samples_segment = max(12, path_samples // 3)
+ tests = 0
+ seeds = sorted(parts, key=lambda p: (-float(p.bbox_max[2]), p.node_id))
+ for seed in seeds:
+ if tests >= MAX_GROUP_TESTS:
+ break
+ members = [seed]
+ member_ids = {seed.node_id}
+ bitten = deep_bitten or set()
+ while len(members) < MAX_GROUP_SIZE and tests < MAX_GROUP_TESTS:
+ neighbors = sorted(
+ (
+ remaining[node_id]
+ for member in members
+ for node_id in adjacency.get(member.node_id, ())
+ if node_id not in member_ids and node_id in remaining
+ ),
+ key=lambda p: (
+ 1 if p.node_id in bitten else 0,
+ diagonal(p),
+ p.node_id,
+ ),
+ )
+ if not neighbors:
+ break
+ members.append(neighbors[0])
+ member_ids.add(neighbors[0].node_id)
+ # The whole remaining set is not a removal
+ if len(members) >= len(remaining):
+ break
+
+ others = [
+ part for part in parts if part.node_id not in member_ids
+ ]
+ static_min = np.min([p.bbox_min for p in others], axis=0)
+ static_max = np.max([p.bbox_max for p in others], axis=0)
+
+ # Concatenating big meshes and building their BVH is expensive;
+ # the same candidate sets recur across stuck rounds
+ cache_key = frozenset(member_ids)
+ combined = (
+ combined_cache.get(cache_key)
+ if combined_cache is not None
+ else None
+ )
+ if combined is None:
+ combined_mesh = trimesh_mod.util.concatenate(
+ [member.mesh for member in members]
+ )
+ combined_mesh._carbon_volume = sum(
+ _part_volume(member) for member in members
+ )
+ combined = _Component(
+ node_id=max(
+ members,
+ key=lambda p: float(
+ abs(np.prod(p.bbox_max - p.bbox_min))
+ ),
+ ).node_id,
+ name=" + ".join(member.name for member in members),
+ mesh=combined_mesh,
+ bbox_min=np.min([m.bbox_min for m in members], axis=0),
+ bbox_max=np.max([m.bbox_max for m in members], axis=0),
+ is_proxy=any(m.is_proxy for m in members),
+ )
+ if combined_cache is not None:
+ combined_cache[cache_key] = combined
+
+ directions: list[np.ndarray] = []
+ for member in members:
+ member_info = fasteners.get(member.node_id)
+ axes = []
+ if member_info is not None:
+ axes.append(member_info.axis)
+ axis = _symmetry_axis(member)
+ if axis is not None:
+ axes.append(axis)
+ for base_axis in axes:
+ for candidate in (base_axis, -base_axis):
+ if all(
+ float(np.dot(candidate, d)) < 0.999
+ for d in directions
+ ):
+ directions.append(candidate)
+ for world in WORLD_AXES:
+ if all(float(np.dot(world, d)) < 0.999 for d in directions):
+ directions.append(world)
+
+ # Members leave the broadphase for the group's own tests —
+ # every member registered would flood the combined mesh with
+ # its full self-overlap contact set at every sample. The name
+ # exemption below stays as belt-and-suspenders.
+ with _unregistered(manager, list(member_ids)):
+ group_touch = None
+ for direction in directions:
+ tests += 1
+ travel = _exit_travel(
+ combined, static_min, static_max, direction
+ )
+ if travel <= 0:
+ continue
+ separation = _separation_distance(
+ combined.bbox_min,
+ combined.bbox_max,
+ static_min,
+ static_max,
+ direction,
+ )
+ group_touch = _path_is_clear(
+ combined,
+ manager,
+ direction,
+ 0.0,
+ travel,
+ samples_segment,
+ tolerance,
+ exempt=_self_exempt(
+ _group_exempt(
+ members, direction, fasteners, member_ids
+ ),
+ list(member_ids),
+ ),
+ check_until=separation + 2 * MAX_SAMPLE_SPACING_MM,
+ )
+ if group_touch is not None:
+ break
+ if tests >= MAX_GROUP_TESTS:
+ break
+ if group_touch is not None:
+ entry = PlannedComponent(
+ node_id=combined.node_id,
+ motion={
+ "type": "linear",
+ "direction": [-float(c) for c in direction],
+ "distance": _recorded_travel(
+ combined, direction, travel, group_touch
+ ),
+ },
+ confidence="low",
+ removal_direction=[float(c) for c in direction],
+ tier="group",
+ )
+ ordered = [member.node_id for member in members]
+ return ordered, combined, entry
+
+ return None
+
+
+def _removal_segments_to_planned(
+ part: _Component, removal: list[tuple[np.ndarray, float]]
+) -> PlannedComponent:
+ """Reverse a removal segment chain into an insertion motion."""
+ first_direction = removal[0][0]
+ if len(removal) == 1:
+ direction, distance = removal[0]
+ motion = {
+ "type": "linear",
+ "direction": [-float(c) for c in direction],
+ "distance": round(float(distance), 3),
+ }
+ else:
+ motion = {
+ "type": "L",
+ "segments": [
+ {
+ "direction": [-float(c) for c in direction],
+ "distance": round(float(distance), 3),
+ }
+ for direction, distance in reversed(removal)
+ ],
+ }
+ return PlannedComponent(
+ node_id=part.node_id,
+ motion=motion,
+ confidence="low",
+ removal_direction=[float(c) for c in first_direction],
+ tier="escape",
+ )
+
+
+def _blocking_depth(
+ contacts: list[tuple[str | None, float]],
+ exempt: dict[str, float] | None,
+) -> float:
+ """Max blocking penetration depth over a sample's contacts.
+
+ Contacts with an exempt partner (a fastener's threaded mate, or the
+ moving part's own registered copy) are allowed up to that allowance
+ plus a margin — the steady thread interference — and count as blocking
+ beyond it.
+ """
+ depth = 0.0
+ for other, contact_depth in contacts:
+ if other is not None and exempt is not None and other in exempt:
+ if contact_depth <= exempt[other] + MATE_DEPTH_MARGIN_MM:
+ continue
+ if contact_depth > depth:
+ depth = contact_depth
+ return depth
+
+
+def _free_travel(
+ part: _Component,
+ manager,
+ direction: np.ndarray,
+ base_offset: np.ndarray,
+ cap: float,
+ samples: int,
+ exempt: dict[str, float] | None = None,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+) -> float:
+ """Furthest clear translation along `direction` from `base_offset`.
+
+ Samples forward like `_path_is_clear` but returns the last clear
+ distance before the first blocking contact instead of a boolean.
+ """
+ if cap <= 0:
+ return 0.0
+ samples = min(
+ max(samples, int(cap / MAX_SAMPLE_SPACING_MM) + 1),
+ MAX_PATH_SAMPLES,
+ )
+ offsets = np.linspace(0.0, cap, samples, endpoint=True)[1:]
+ clear = 0.0
+ for s in offsets:
+ translation = direction * float(s) + base_offset
+ contacts = _contacts_at(manager, part, translation)
+ if contacts:
+ depth = _blocking_depth(contacts, exempt)
+ if depth > tolerance:
+ return clear
+ clear = float(s)
+ return clear
+
+
+def _recorded_travel(
+ part: _Component,
+ direction: np.ndarray,
+ full_travel: float,
+ last_touch: float,
+) -> float:
+ """The travel to record for the animation: reach free space, then one
+ own-extent of clearance so the exit reads visually — never more than
+ the full AABB-exit travel (whose tail was verified clear)."""
+ extent = float(np.abs(direction) @ (part.bbox_max - part.bbox_min))
+ return round(min(float(full_travel), last_touch + extent + EXIT_MARGIN_MM), 3)
+
+
+def _separation_distance(
+ bbox_min: np.ndarray,
+ bbox_max: np.ndarray,
+ static_min: np.ndarray,
+ static_max: np.ndarray,
+ direction: np.ndarray,
+) -> float:
+ """Translation along `direction` until the AABBs separate.
+
+ AABB overlap ends as soon as the boxes separate on ANY axis, so this
+ is the cheapest separating axis (taking the max instead explodes for
+ directions with tiny components). Beyond this distance the moving box
+ is disjoint from the whole static set — no collision checks needed.
+ """
+ travel = float("inf")
+ for axis in range(3):
+ d = float(direction[axis])
+ if d > 1e-6:
+ needed = float(static_max[axis] - bbox_min[axis])
+ travel = min(travel, max(needed / d, 0.0))
+ elif d < -1e-6:
+ needed = float(bbox_max[axis] - static_min[axis])
+ travel = min(travel, max(needed / -d, 0.0))
+ return 0.0 if travel == float("inf") else travel
+
+
+def _exit_travel(
+ part: _Component,
+ static_min: np.ndarray,
+ static_max: np.ndarray,
+ direction: np.ndarray,
+ base_offset: np.ndarray | None = None,
+) -> float:
+ """Distance along `direction` until the part's AABB clears the assembly.
+
+ Capped at the assembly diagonal and never zero: a part already outside
+ still gets an animation travel of its own extent plus margin so the
+ insertion reads clearly.
+ """
+ bbox_min = part.bbox_min + (base_offset if base_offset is not None else 0.0)
+ bbox_max = part.bbox_max + (base_offset if base_offset is not None else 0.0)
+
+ travel = _separation_distance(
+ bbox_min, bbox_max, static_min, static_max, direction
+ )
+
+ diagonal = float(np.linalg.norm(static_max - static_min))
+ travel = min(travel, diagonal * 1.5)
+
+ extent = float(np.abs(direction) @ (bbox_max - bbox_min))
+ return max(travel, extent) + EXIT_MARGIN_MM
+
+
+def _path_is_clear(
+ part: _Component,
+ manager,
+ direction: np.ndarray,
+ start: float,
+ end: float,
+ samples: int,
+ tolerance: float = PENETRATION_TOLERANCE_MM,
+ base_offset: np.ndarray | None = None,
+ exempt: dict[str, float] | None = None,
+ check_until: float | None = None,
+) -> float | None:
+ """Densely sample translations of the part and check for collisions.
+
+ Returns None when the path is blocked; otherwise the LAST distance at
+ which the part was still touching something (0.0 for a free flight) —
+ the "reach free space" point that callers record as the motion travel
+ instead of the AABB-exit distance (a screw backs out of its hole in
+ ~20mm; it does not fly to the assembly boundary).
+
+ Surface contact up to `tolerance` is allowed so sliding fits (pins in
+ bores, rails in channels) remain removable. Contacts with `exempt`
+ partners (a fastener's threaded mate along its own axis, the moving
+ part's own registered copy) are allowed up to their recorded
+ interference — infinite allowances (self, group members) do not count
+ as touching. When a sample presses past half the tolerance, the
+ neighborhood is re-checked at half spacing so thin blockers cannot
+ slip between samples. Samples beyond `check_until` (the AABB
+ separation distance from everything static) are provably clear and
+ skipped.
+ """
+ if end <= start:
+ return None
+ seated = _seated_exempt(part, direction)
+ if seated:
+ # Compliant squish along the sandwich axis never blocks; explicit
+ # exemptions (self, mates) keep precedence when larger
+ merged_exempt = dict(seated)
+ for partner, depth in (exempt or {}).items():
+ merged_exempt[partner] = max(merged_exempt.get(partner, 0.0), depth)
+ exempt = merged_exempt
+ samples = min(
+ max(samples, int((end - start) / MAX_SAMPLE_SPACING_MM) + 1),
+ MAX_PATH_SAMPLES,
+ )
+ offsets = np.linspace(start, end, samples, endpoint=True)[1:]
+ spacing = (end - start) / max(samples - 1, 1)
+
+ def blocked_at(distance: float) -> tuple[bool, bool, bool]:
+ """(blocked, near, touching) at a distance along the path."""
+ translation = direction * float(distance)
+ if base_offset is not None:
+ translation = translation + base_offset
+ contacts = _contacts_at(manager, part, translation)
+ if not contacts:
+ return False, False, False
+ depth = _blocking_depth(contacts, exempt)
+ touching = any(
+ other is not None
+ and not (
+ exempt is not None
+ and exempt.get(other, 0.0) == float("inf")
+ )
+ for other, _depth in contacts
+ )
+ return depth > tolerance, depth > tolerance * 0.5, touching
+
+ last_touch = 0.0
+ for s in offsets:
+ if check_until is not None and float(s) > check_until:
+ break
+ blocked, near, touching = blocked_at(float(s))
+ if blocked:
+ return None
+ if touching:
+ last_touch = float(s)
+ if near:
+ # Refine around near-tolerance contact: a thin flange's blocking
+ # window can be narrower than the sample spacing
+ half = spacing / 2.0
+ for probe in (float(s) - half, float(s) + half):
+ if probe <= start or probe >= end:
+ continue
+ probe_blocked, _near, _touching = blocked_at(probe)
+ if probe_blocked:
+ return None
+ return last_touch
+
+
+def _escape_blockers(
+ part: _Component,
+ remaining: dict[str, _Component],
+ manager,
+ fasteners: dict[str, _FastenerInfo],
+ tolerance: float,
+ path_samples: int,
+) -> list[str]:
+ """The parts that ACTUALLY block every escape: union of sweep blockers
+ over the part's candidate directions. Bbox proximity over-counts —
+ neighbors that never intersect any escape path are not blockers, and
+ the single-blocker rigid-merge decision depends on the difference.
+ """
+ others = [p for p in remaining.values() if p.node_id != part.node_id]
+ if not others:
+ return []
+ static_min = np.min([p.bbox_min for p in others], axis=0)
+ static_max = np.max([p.bbox_max for p in others], axis=0)
+ samples_segment = max(12, path_samples // 3)
+
+ info = fasteners.get(part.node_id)
+ if _is_fastener(part) and info is not None:
+ head = _head_direction(part, info, remaining)
+ directions = [head, -head]
+ else:
+ directions = _candidate_directions(part)
+
+ blockers: set[str] = set()
+ with _unregistered(manager, [part.node_id]):
+ for direction in directions:
+ travel = _exit_travel(part, static_min, static_max, direction)
+ if travel <= 0:
+ continue
+ blockers |= _path_blockers(
+ part,
+ manager,
+ [(direction, float(travel))],
+ samples_segment,
+ fasteners,
+ extra_exempt={part.node_id: float("inf")},
+ tolerance=tolerance,
+ )
+ blockers.discard(part.node_id)
+ return sorted(blockers)[:8]
+
+
+def _blockers(part: _Component, remaining: dict[str, _Component], trimesh_mod) -> list[str]:
+ """Parts whose bounding boxes overlap this part's (rough blocking set)."""
+ blockers: list[str] = []
+ for other in remaining.values():
+ if other.node_id == part.node_id:
+ continue
+ overlaps = bool(
+ np.all(part.bbox_min <= other.bbox_max)
+ and np.all(other.bbox_min <= part.bbox_max)
+ )
+ if overlaps:
+ blockers.append(other.node_id)
+ return blockers[:8]
diff --git a/services/geometry/app/schemas.py b/services/geometry/app/schemas.py
new file mode 100644
index 0000000000..459b9159b8
--- /dev/null
+++ b/services/geometry/app/schemas.py
@@ -0,0 +1,145 @@
+"""Pydantic models for the /convert contract.
+
+Field names are camelCase on purpose: they must match the wire format in
+docs/specs/animated-work-instructions-contracts.md exactly.
+"""
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, field_validator
+
+
+class SourceSpec(BaseModel):
+ url: str
+ format: Literal["step"] = "step"
+
+
+class OutputTarget(BaseModel):
+ url: str
+
+
+class OutputSpec(BaseModel):
+ glb: OutputTarget
+ graph: OutputTarget
+
+
+class ConvertOptions(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+
+ linearDeflection: float = 0.1
+ angularDeflection: float = 0.5
+ compress: bool = True
+
+
+class ConvertRequest(BaseModel):
+ jobId: str
+ source: SourceSpec
+ outputs: OutputSpec
+ options: ConvertOptions = ConvertOptions()
+
+
+class ConvertStats(BaseModel):
+ convertMs: int
+ meshTriangles: int
+ warnings: list[str] = []
+
+
+class ConvertResponse(BaseModel):
+ ok: Literal[True] = True
+ componentCount: int
+ unit: str
+ stats: ConvertStats
+
+
+class PlanOutputSpec(BaseModel):
+ plan: OutputTarget
+
+
+class PlanUnit(BaseModel):
+ """A set of leaf nodeIds the planner should treat as one rigid body."""
+
+ id: str
+ name: str | None = None
+ nodeIds: list[str]
+
+
+class PlanOptions(BaseModel):
+ model_config = ConfigDict(extra="ignore")
+
+ linearDeflection: float = 0.1
+ angularDeflection: float = 0.5
+ clearance: float = 0.5
+ pathSamples: int = 60
+ # Pre-grouped units (e.g. a purchased PCB) merged into one body for planning.
+ units: list[PlanUnit] | None = None
+ # Caller-fixed assembly order + grouping: an ordered list of groups, each a
+ # set of leaf nodeIds installed together as one rigid body at step i, after
+ # every earlier group. When set, the planner uses this order as-is (no
+ # reordering) and only computes each group's forward-collision insertion
+ # motion against the parts of previous groups.
+ sequence: list[list[str]] | None = None
+
+ @field_validator("sequence")
+ @classmethod
+ def _validate_sequence(
+ cls, value: list[list[str]] | None
+ ) -> list[list[str]] | None:
+ if value is None:
+ return value
+ for index, group in enumerate(value):
+ if not group:
+ raise ValueError(f"sequence group {index} must be non-empty")
+ if not all(isinstance(node_id, str) for node_id in group):
+ raise ValueError(
+ f"sequence group {index} entries must be strings"
+ )
+ return value
+
+
+class PlanRequest(BaseModel):
+ jobId: str
+ source: SourceSpec
+ # Optional: the caller now persists the plan from the response body (see
+ # PlanResponse.plan). A pre-signed upload URL would expire during the
+ # multi-minute planner run, so uploading here is best-effort/backward-compat
+ # only.
+ outputs: PlanOutputSpec | None = None
+ options: PlanOptions = PlanOptions()
+
+
+class PlanStats(BaseModel):
+ planMs: int
+ tiers: dict[str, int]
+ warnings: list[str] = []
+ # Parts whose insertion passed forward verification against the parts
+ # present at their point in the final sequence
+ verifiedCount: int | None = None
+
+
+# Planning a large assembly runs for 10+ minutes — longer than any single HTTP
+# request survives across the app/tunnel/undici stack. So POST /plan starts the
+# work in the background and returns immediately; the caller polls
+# GET /plan/{jobId} until it reports "done" and then persists the inline plan.
+
+
+class PlanStartResponse(BaseModel):
+ ok: Literal[True] = True
+ jobId: str
+ status: str # "pending" | "running"
+
+
+class PlanStatusResponse(BaseModel):
+ ok: Literal[True] = True
+ status: str # "pending" | "running" | "done" | "error"
+ # Present only when status == "done":
+ plan: dict | None = None
+ componentCount: int | None = None
+ plannedCount: int | None = None
+ stats: PlanStats | None = None
+ # Present only when status == "error":
+ error: str | None = None
+
+
+class HealthResponse(BaseModel):
+ ok: Literal[True] = True
+ version: str
diff --git a/services/geometry/pyproject.toml b/services/geometry/pyproject.toml
new file mode 100644
index 0000000000..f60227a64e
--- /dev/null
+++ b/services/geometry/pyproject.toml
@@ -0,0 +1,31 @@
+[project]
+name = "carbon-geometry"
+version = "0.1.0"
+description = "Carbon geometry service: STEP -> GLB + graph.json conversion (OCCT/XCAF)"
+requires-python = ">=3.11"
+dependencies = [
+ "fastapi==0.136.3",
+ "uvicorn[standard]==0.49.0",
+ "httpx==0.28.1",
+ "cadquery-ocp==7.9.3.1.1",
+ "numpy==2.4.6",
+ "pygltflib==1.16.5",
+ "trimesh==4.5.3",
+ "python-fcl>=0.7.0.6",
+ "scipy>=1.14",
+ # ray-cast containment (fastener joints, embedded-solid merging)
+ "rtree>=1.2",
+]
+
+[project.optional-dependencies]
+dev = ["pytest==9.0.3", "manifold3d>=3.0"]
+
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools]
+packages = ["app"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
diff --git a/services/geometry/tests/conftest.py b/services/geometry/tests/conftest.py
new file mode 100644
index 0000000000..21ba64944e
--- /dev/null
+++ b/services/geometry/tests/conftest.py
@@ -0,0 +1,54 @@
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Iterator
+
+import pytest
+
+
[email protected](scope="session")
+def step_fixtures(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
+ """Generate the STEP fixtures once per session (requires OCP)."""
+ pytest.importorskip("OCP")
+ from fixtures.make_fixtures import build_all
+
+ return build_all(tmp_path_factory.mktemp("step-fixtures"))
+
+
+class StorageStub:
+ def __init__(self, source_bytes: bytes) -> None:
+ self.source_bytes = source_bytes
+ self.puts: dict[str, bytes] = {}
+
+
+class _StorageHandler(BaseHTTPRequestHandler):
+ storage: StorageStub
+
+ def do_GET(self) -> None:
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(self.storage.source_bytes)))
+ self.end_headers()
+ self.wfile.write(self.storage.source_bytes)
+
+ def do_PUT(self) -> None:
+ length = int(self.headers["Content-Length"])
+ self.storage.puts[self.path] = self.rfile.read(length)
+ self.send_response(200)
+ self.end_headers()
+
+ def log_message(self, *args: object) -> None: # silence test output
+ pass
+
+
+def storage_server(step_fixtures: dict[str, Path]) -> Iterator[tuple[str, StorageStub]]:
+ """Local HTTP server playing the signed-URL storage role."""
+ storage = StorageStub(step_fixtures["plates"].read_bytes())
+ handler = type("Handler", (_StorageHandler,), {"storage": storage})
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_address[1]}", storage
+ finally:
+ server.shutdown()
diff --git a/scripts/stripe-configs.ts b/services/geometry/tests/fixtures/__init__.py
similarity index 100%
rename from scripts/stripe-configs.ts
rename to services/geometry/tests/fixtures/__init__.py
diff --git a/services/geometry/tests/fixtures/make_fixtures.py b/services/geometry/tests/fixtures/make_fixtures.py
new file mode 100644
index 0000000000..703f2e24b7
--- /dev/null
+++ b/services/geometry/tests/fixtures/make_fixtures.py
@@ -0,0 +1,133 @@
+"""Generate the STEP test fixtures programmatically with OCP.
+
+Three fixtures:
+- box.step: single-part box (no assembly structure)
+- plates.step: 5-part assembly: 1 plate + 4 identical "M5-SHCS" cylinders
+- nested.step: assembly containing a 2-part subassembly plus a direct part
+
+Run directly to write them somewhere: python tests/fixtures/make_fixtures.py <dir>
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder
+from OCP.gp import gp_Trsf, gp_Vec
+from OCP.IFSelect import IFSelect_ReturnStatus
+from OCP.Quantity import Quantity_Color, Quantity_ColorRGBA, Quantity_TypeOfColor
+from OCP.STEPCAFControl import STEPCAFControl_Writer
+from OCP.STEPControl import STEPControl_StepModelType
+from OCP.TCollection import TCollection_ExtendedString
+from OCP.TDataStd import TDataStd_Name
+from OCP.TDF import TDF_Label
+from OCP.TDocStd import TDocStd_Document
+from OCP.TopLoc import TopLoc_Location
+from OCP.TopoDS import TopoDS_Shape
+from OCP.XCAFDoc import XCAFDoc_ColorType, XCAFDoc_DocumentTool
+
+
+def _new_doc() -> TDocStd_Document:
+ return TDocStd_Document(TCollection_ExtendedString("BinXCAF"))
+
+
+def _set_name(label: TDF_Label, name: str) -> None:
+ TDataStd_Name.Set_s(label, TCollection_ExtendedString(name))
+
+
+def _translation(x: float, y: float, z: float) -> TopLoc_Location:
+ trsf = gp_Trsf()
+ trsf.SetTranslation(gp_Vec(x, y, z))
+ return TopLoc_Location(trsf)
+
+
+def _rgba(r: float, g: float, b: float, a: float = 1.0) -> Quantity_ColorRGBA:
+ return Quantity_ColorRGBA(
+ Quantity_Color(r, g, b, Quantity_TypeOfColor.Quantity_TOC_RGB), a
+ )
+
+
+def _write_step(doc: TDocStd_Document, path: Path) -> None:
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+ shape_tool.UpdateAssemblies()
+ writer = STEPCAFControl_Writer()
+ writer.SetColorMode(True)
+ writer.SetNameMode(True)
+ if not writer.Transfer(doc, STEPControl_StepModelType.STEPControl_AsIs):
+ raise RuntimeError(f"STEP transfer failed for {path}")
+ if writer.Write(str(path)) != IFSelect_ReturnStatus.IFSelect_RetDone:
+ raise RuntimeError(f"STEP write failed for {path}")
+
+
+def _add_part(doc: TDocStd_Document, shape: TopoDS_Shape, name: str) -> TDF_Label:
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+ label = shape_tool.AddShape(shape, False)
+ _set_name(label, name)
+ return label
+
+
+def build_box_step(path: Path) -> None:
+ doc = _new_doc()
+ box = BRepPrimAPI_MakeBox(40.0, 30.0, 20.0).Shape()
+ _add_part(doc, box, "BLOCK")
+ _write_step(doc, path)
+
+
+def build_plates_step(path: Path) -> None:
+ doc = _new_doc()
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+ color_tool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
+
+ plate_label = _add_part(doc, BRepPrimAPI_MakeBox(100.0, 60.0, 10.0).Shape(), "PLATE")
+ color_tool.SetColor(plate_label, _rgba(0.2, 0.4, 0.8), XCAFDoc_ColorType.XCAFDoc_ColorSurf)
+ screw_label = _add_part(
+ doc, BRepPrimAPI_MakeCylinder(2.5, 30.0).Shape(), "M5-SHCS"
+ )
+ color_tool.SetColor(screw_label, _rgba(0.7, 0.7, 0.75), XCAFDoc_ColorType.XCAFDoc_ColorSurf)
+
+ assembly = shape_tool.NewShape()
+ _set_name(assembly, "STACK-ASSY")
+ shape_tool.AddComponent(assembly, plate_label, TopLoc_Location())
+ for x, y in [(10.0, 10.0), (90.0, 10.0), (90.0, 50.0), (10.0, 50.0)]:
+ shape_tool.AddComponent(assembly, screw_label, _translation(x, y, 10.0))
+ _write_step(doc, path)
+
+
+def build_nested_step(path: Path) -> None:
+ doc = _new_doc()
+ shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
+
+ base_label = _add_part(doc, BRepPrimAPI_MakeBox(50.0, 50.0, 8.0).Shape(), "BASE")
+ pin_label = _add_part(doc, BRepPrimAPI_MakeCylinder(4.0, 25.0).Shape(), "PIN")
+ cover_label = _add_part(doc, BRepPrimAPI_MakeBox(50.0, 50.0, 3.0).Shape(), "COVER")
+
+ sub_assembly = shape_tool.NewShape()
+ _set_name(sub_assembly, "SUB-ASSY")
+ shape_tool.AddComponent(sub_assembly, base_label, TopLoc_Location())
+ shape_tool.AddComponent(sub_assembly, pin_label, _translation(25.0, 25.0, 8.0))
+
+ top_assembly = shape_tool.NewShape()
+ _set_name(top_assembly, "TOP-ASSY")
+ shape_tool.AddComponent(top_assembly, sub_assembly, TopLoc_Location())
+ shape_tool.AddComponent(top_assembly, cover_label, _translation(0.0, 0.0, 40.0))
+ _write_step(doc, path)
+
+
+def build_all(directory: Path) -> dict[str, Path]:
+ directory.mkdir(parents=True, exist_ok=True)
+ fixtures = {
+ "box": directory / "box.step",
+ "plates": directory / "plates.step",
+ "nested": directory / "nested.step",
+ }
+ build_box_step(fixtures["box"])
+ build_plates_step(fixtures["plates"])
+ build_nested_step(fixtures["nested"])
+ return fixtures
+
+
+if __name__ == "__main__":
+ out = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()
+ for name, fixture_path in build_all(out).items():
+ print(f"{name}: {fixture_path}")
diff --git a/services/geometry/tests/test_api.py b/services/geometry/tests/test_api.py
new file mode 100644
index 0000000000..d905a0a228
--- /dev/null
+++ b/services/geometry/tests/test_api.py
@@ -0,0 +1,65 @@
+"""Auth and /health tests. These run without the OCCT wheel installed."""
+
+import pytest
+from fastapi.testclient import TestClient
+
+from app import __version__
+from app.main import app
+
+
+def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.delenv("GEOMETRY_SERVICE_API_KEY", raising=False)
+ monkeypatch.delenv("GEOMETRY_DEV_MODE", raising=False)
+ return TestClient(app)
+
+
+def test_health(client: TestClient) -> None:
+ response = client.get("/health")
+ assert response.status_code == 200
+ assert response.json() == {"ok": True, "version": __version__}
+
+
+def test_convert_requires_auth(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ assert client.post("/convert", json={}).status_code == 401
+
+
+def test_convert_rejects_wrong_token(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ response = client.post(
+ "/convert", json={}, headers={"Authorization": "Bearer wrong"}
+ )
+ assert response.status_code == 401
+
+
+def test_convert_rejects_all_when_key_unset_and_not_dev(client: TestClient) -> None:
+ response = client.post(
+ "/convert", json={}, headers={"Authorization": "Bearer anything"}
+ )
+ assert response.status_code == 401
+
+
+def test_dev_mode_allows_unauthenticated(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("GEOMETRY_DEV_MODE", "true")
+ response = client.post("/convert", json={})
+ # Auth passed; the empty body fails validation per the error contract.
+ assert response.status_code == 400
+ body = response.json()
+ assert body["ok"] is False
+ assert body["code"] == "INVALID_INPUT"
+
+
+def test_valid_token_reaches_validation(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ response = client.post(
+ "/convert", json={"jobId": "x"}, headers={"Authorization": "Bearer secret"}
+ )
+ assert response.status_code == 400
+ assert response.json()["code"] == "INVALID_INPUT"
diff --git a/services/geometry/tests/test_convert.py b/services/geometry/tests/test_convert.py
new file mode 100644
index 0000000000..c6a84f0bfd
--- /dev/null
+++ b/services/geometry/tests/test_convert.py
@@ -0,0 +1,159 @@
+"""Conversion tests over generated STEP fixtures. Skipped if OCP is missing."""
+
+import math
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("OCP")
+
+from pygltflib import GLTF2
+
+from app.convert import ConversionResult, convert_step
+
+
+def _convert(step_path: Path, tmp_path: Path, name: str) -> tuple[ConversionResult, Path]:
+ glb_path = tmp_path / f"{name}.glb"
+ result = convert_step(step_path, glb_path)
+ return result, glb_path
+
+
+def _leaves(node: dict) -> list[dict]:
+ if not node["isAssembly"]:
+ return [node]
+ return [leaf for child in node["children"] for leaf in _leaves(child)]
+
+
+def _all_nodes(node: dict) -> list[dict]:
+ return [node] + [n for child in node["children"] for n in _all_nodes(child)]
+
+
+def _glb_node_ids(glb_path: Path) -> set[str]:
+ gltf = GLTF2().load(str(glb_path))
+ return {
+ node.extras["nodeId"]
+ for node in gltf.nodes
+ if node.extras and "nodeId" in node.extras
+ }
+
+
+def test_single_part_box(step_fixtures: dict[str, Path], tmp_path: Path) -> None:
+ result, glb_path = _convert(step_fixtures["box"], tmp_path, "box")
+ assert glb_path.exists() and glb_path.stat().st_size > 0
+ assert glb_path.read_bytes()[:4] == b"glTF"
+
+ graph = result.graph
+ assert graph["version"] == 1
+ assert graph["unit"] == "mm"
+ assert graph["sourceUnit"] == "mm"
+ assert graph["componentCount"] == 1
+
+ root = graph["root"]
+ assert root["isAssembly"] is False
+ assert root["geometryHash"]
+ assert len(root["nodeId"]) == 16
+ assert math.isclose(root["volume"], 40 * 30 * 20, rel_tol=0.01)
+ bbox = root["bbox"]
+ assert bbox["min"] == pytest.approx([0, 0, 0], abs=0.5)
+ assert bbox["max"] == pytest.approx([40, 30, 20], abs=0.5)
+
+
+def test_plates_assembly_counts_and_duplicates(
+ step_fixtures: dict[str, Path], tmp_path: Path
+) -> None:
+ result, _ = _convert(step_fixtures["plates"], tmp_path, "plates")
+ graph = result.graph
+ assert graph["componentCount"] == 5
+
+ root = graph["root"]
+ assert root["isAssembly"] is True
+ assert root["geometryHash"] is None
+ assert root["volume"] is None
+
+ leaves = _leaves(root)
+ assert len(leaves) == 5
+ screws = [leaf for leaf in leaves if leaf["name"].startswith("M5-SHCS")]
+ assert len(screws) == 4
+ # Identical geometry, one shared hash...
+ assert len({s["geometryHash"] for s in screws}) == 1
+ # ...but four distinct stable nodeIds.
+ assert len({s["nodeId"] for s in screws}) == 4
+
+ for leaf in leaves:
+ assert leaf["volume"] is not None and leaf["volume"] > 0
+ bbox = leaf["bbox"]
+ assert all(lo <= hi for lo, hi in zip(bbox["min"], bbox["max"]))
+ assert all(math.isfinite(v) for v in bbox["min"] + bbox["max"])
+
+ # Plate color round-trips from XCAF.
+ plate = next(leaf for leaf in leaves if leaf["name"].startswith("PLATE"))
+ assert plate["color"] == pytest.approx([0.2, 0.4, 0.8, 1.0], abs=0.02)
+
+ # World bbox reflects instance transforms: plate 100x60x10 at the origin,
+ # 30mm screws standing on top of it (z = 10..40).
+ root_bbox = root["bbox"]
+ assert root_bbox["min"] == pytest.approx([0, 0, 0], abs=0.5)
+ assert root_bbox["max"] == pytest.approx([100, 60, 40], abs=0.5)
+ screw = next(s for s in screws if s["bbox"]["min"][0] < 50)
+ assert screw["bbox"]["min"][2] == pytest.approx(10, abs=0.5)
+ assert screw["bbox"]["max"][2] == pytest.approx(40, abs=0.5)
+
+
+def test_source_unit_detection(tmp_path: Path) -> None:
+ from app.convert import _detect_source_unit
+
+ inch = tmp_path / "inch.step"
+ inch.write_text(
+ "DATA;\n#41=( CONVERSION_BASED_UNIT('INCH',#38) LENGTH_UNIT() NAMED_UNIT(#40) );\nENDSEC;"
+ )
+ assert _detect_source_unit(inch) == "inch"
+
+ metre = tmp_path / "metre.step"
+ metre.write_text("DATA;\n#41=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT($,.METRE.) );\nENDSEC;")
+ assert _detect_source_unit(metre) == "m"
+
+ unknown = tmp_path / "unknown.step"
+ unknown.write_text("DATA;\nENDSEC;")
+ assert _detect_source_unit(unknown) == "mm"
+
+
+def test_node_ids_stable_across_runs(
+ step_fixtures: dict[str, Path], tmp_path: Path
+) -> None:
+ first, _ = _convert(step_fixtures["plates"], tmp_path, "run1")
+ second, _ = _convert(step_fixtures["plates"], tmp_path, "run2")
+
+ first_ids = [n["nodeId"] for n in _all_nodes(first.graph["root"])]
+ second_ids = [n["nodeId"] for n in _all_nodes(second.graph["root"])]
+ assert first_ids == second_ids
+ assert first.graph == second.graph
+
+
+def test_nested_assembly_structure(
+ step_fixtures: dict[str, Path], tmp_path: Path
+) -> None:
+ result, _ = _convert(step_fixtures["nested"], tmp_path, "nested")
+ graph = result.graph
+ assert graph["componentCount"] == 3
+
+ root = graph["root"]
+ assert root["isAssembly"] is True
+ sub_assemblies = [c for c in root["children"] if c["isAssembly"]]
+ assert len(sub_assemblies) == 1
+ assert len(_leaves(sub_assemblies[0])) == 2
+ direct_parts = [c for c in root["children"] if not c["isAssembly"]]
+ assert len(direct_parts) == 1
+
+ node_ids = [n["nodeId"] for n in _all_nodes(root)]
+ assert len(node_ids) == len(set(node_ids))
+
+
+def test_glb_extras_match_graph(step_fixtures: dict[str, Path], tmp_path: Path) -> None:
+ for name in ("box", "plates", "nested"):
+ result, glb_path = _convert(step_fixtures[name], tmp_path, f"extras-{name}")
+ glb_ids = _glb_node_ids(glb_path)
+ for leaf in _leaves(result.graph["root"]):
+ assert leaf["nodeId"] in glb_ids
+ # Assemblies (incl. root) are stamped too.
+ for node in _all_nodes(result.graph["root"]):
+ assert node["nodeId"] in glb_ids
diff --git a/services/geometry/tests/test_endpoint.py b/services/geometry/tests/test_endpoint.py
new file mode 100644
index 0000000000..1083a991f6
--- /dev/null
+++ b/services/geometry/tests/test_endpoint.py
@@ -0,0 +1,141 @@
+"""End-to-end /convert against a local HTTP server playing the storage role."""
+
+import json
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("OCP")
+
+from fastapi.testclient import TestClient
+
+import app.main as main
+import app.plan as plan_mod
+from app.main import app
+
+
+
+def test_convert_endpoint_round_trip(
+ storage_server: tuple[str, "object"], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ base_url, storage = storage_server
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ monkeypatch.setenv("GEOMETRY_DEV_MODE", "true")
+
+ client = TestClient(app)
+ response = client.post(
+ "/convert",
+ json={
+ "jobId": "test-job",
+ "source": {"url": f"{base_url}/source.step", "format": "step"},
+ "outputs": {
+ "glb": {"url": f"{base_url}/out/model.glb"},
+ "graph": {"url": f"{base_url}/out/graph.json"},
+ },
+ "options": {"linearDeflection": 0.1, "angularDeflection": 0.5},
+ },
+ headers={"Authorization": "Bearer secret"},
+ )
+ assert response.status_code == 200, response.text
+
+ body = response.json()
+ assert body["ok"] is True
+ assert body["componentCount"] == 5
+ assert body["unit"] == "mm"
+ assert body["stats"]["convertMs"] >= 0
+ assert body["stats"]["meshTriangles"] > 0
+
+ glb = storage.puts["/out/model.glb"]
+ assert glb[:4] == b"glTF"
+ graph = json.loads(storage.puts["/out/graph.json"])
+ assert graph["componentCount"] == 5
+ assert graph["root"]["isAssembly"] is True
+
+
+def test_convert_endpoint_read_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ monkeypatch.setenv("GEOMETRY_DEV_MODE", "true")
+ client = TestClient(app)
+ response = client.post(
+ "/convert",
+ json={
+ "jobId": "bad-job",
+ "source": {"url": "http://127.0.0.1:1/missing.step", "format": "step"},
+ "outputs": {
+ "glb": {"url": "http://127.0.0.1:1/a"},
+ "graph": {"url": "http://127.0.0.1:1/b"},
+ },
+ },
+ headers={"Authorization": "Bearer secret"},
+ )
+ assert response.status_code == 422
+ body = response.json()
+ assert body["ok"] is False
+ assert body["code"] == "READ_FAILED"
+
+
+def test_plan_async_submit_poll_result(monkeypatch: pytest.MonkeyPatch) -> None:
+ """POST /plan starts a background job; GET /plan/{id} polls to the result."""
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+
+ # Stub the planner + download so the async orchestration is what's exercised,
+ # not OCCT tessellation.
+ monkeypatch.setattr(main, "_download", lambda url, dest: Path(dest).write_text("x"))
+
+ def fake_plan_step(_path: object, **_kwargs: object) -> SimpleNamespace:
+ return SimpleNamespace(
+ plan={
+ "version": 3,
+ "unit": "mm",
+ "sequence": ["n1"],
+ "components": {"n1": {"motion": {"type": "none"}}},
+ },
+ component_count=1,
+ planned_count=1,
+ tiers={"linear": 1},
+ warnings=[],
+ verified_count=1,
+ )
+
+ monkeypatch.setattr(plan_mod, "plan_step", fake_plan_step)
+
+ client = TestClient(app)
+ headers = {"Authorization": "Bearer secret"}
+
+ start = client.post(
+ "/plan",
+ json={"jobId": "async-job", "source": {"url": "https://x/y.step"}},
+ headers=headers,
+ )
+ assert start.status_code == 202, start.text
+ assert start.json()["jobId"] == "async-job"
+ assert start.json()["status"] in ("pending", "running")
+
+ for _ in range(100):
+ poll = client.get("/plan/async-job", headers=headers)
+ assert poll.status_code == 200, poll.text
+ body = poll.json()
+ if body["status"] == "done":
+ assert body["plan"]["version"] == 3
+ assert body["componentCount"] == 1
+ assert body["plannedCount"] == 1
+ break
+ if body["status"] == "error":
+ raise AssertionError(body.get("error"))
+ time.sleep(0.02)
+ else:
+ raise AssertionError("plan job never completed")
+
+ # Unknown job id reports 404 via the error contract.
+ missing = client.get("/plan/does-not-exist", headers=headers)
+ assert missing.status_code == 404
+ assert missing.json()["ok"] is False
+
+
+def test_plan_requires_auth(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ client = TestClient(app)
+ assert client.post("/plan", json={}).status_code == 401
+ assert client.get("/plan/whatever").status_code == 401
diff --git a/services/geometry/tests/test_limits.py b/services/geometry/tests/test_limits.py
new file mode 100644
index 0000000000..4d9c6eb29c
--- /dev/null
+++ b/services/geometry/tests/test_limits.py
@@ -0,0 +1,90 @@
+"""Operational limit enforcement: URL policy, size cap, part cap, concurrency."""
+
+import pytest
+from fastapi.testclient import TestClient
+
+from app.main import _conversion_slots, app
+
+
+def _payload(base_url: str) -> dict:
+ return {
+ "jobId": "limit-job",
+ "source": {"url": f"{base_url}/source.step", "format": "step"},
+ "outputs": {
+ "glb": {"url": f"{base_url}/out/model.glb"},
+ "graph": {"url": f"{base_url}/out/graph.json"},
+ },
+ }
+
+
+AUTH = {"Authorization": "Bearer secret"}
+
+
+def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ monkeypatch.setenv("GEOMETRY_DEV_MODE", "true")
+ return TestClient(app)
+
+
+def test_https_required_outside_dev_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("GEOMETRY_SERVICE_API_KEY", "secret")
+ monkeypatch.delenv("GEOMETRY_DEV_MODE", raising=False)
+ client = TestClient(app)
+ response = client.post(
+ "/convert", json=_payload("http://example.com"), headers=AUTH
+ )
+ assert response.status_code == 400
+ assert response.json()["code"] == "INVALID_INPUT"
+
+
+def test_host_allowlist(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("GEOMETRY_ALLOWED_URL_HOSTS", "storage.internal")
+ response = client.post(
+ "/convert", json=_payload("http://example.com"), headers=AUTH
+ )
+ assert response.status_code == 400
+ assert response.json()["code"] == "INVALID_INPUT"
+
+
+def test_source_size_cap(
+ storage_server: tuple[str, object],
+ client: TestClient,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ base_url, _ = storage_server
+ monkeypatch.setenv("GEOMETRY_MAX_SOURCE_MB", "0")
+ response = client.post("/convert", json=_payload(base_url), headers=AUTH)
+ assert response.status_code == 413
+ assert response.json()["code"] == "LIMIT_EXCEEDED"
+
+
+def test_part_count_cap(
+ storage_server: tuple[str, object],
+ client: TestClient,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ base_url, _ = storage_server
+ monkeypatch.setenv("GEOMETRY_MAX_PARTS", "1")
+ response = client.post("/convert", json=_payload(base_url), headers=AUTH)
+ assert response.status_code == 413
+ assert response.json()["code"] == "LIMIT_EXCEEDED"
+
+
+def test_busy_when_no_slots(client: TestClient) -> None:
+ acquired = []
+ while _conversion_slots.acquire(blocking=False):
+ acquired.append(True)
+ try:
+ response = client.post(
+ "/convert", json=_payload("http://127.0.0.1:1"), headers=AUTH
+ )
+ assert response.status_code == 429
+ assert response.json()["code"] == "BUSY"
+ finally:
+ for _ in acquired:
+ _conversion_slots.release()
diff --git a/services/geometry/tests/test_optimize.py b/services/geometry/tests/test_optimize.py
new file mode 100644
index 0000000000..1eb1ff1ae5
--- /dev/null
+++ b/services/geometry/tests/test_optimize.py
@@ -0,0 +1,48 @@
+"""Meshopt compression pass. Skipped without OCP or the gltf-transform CLI."""
+
+import shutil
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("OCP")
+pytestmark = pytest.mark.skipif(
+ shutil.which("gltf-transform") is None, reason="gltf-transform CLI not installed"
+)
+
+from pygltflib import GLTF2
+
+from app.convert import convert_step
+from app.optimize import compress_glb
+
+
+def test_compression_preserves_extras_and_shrinks(
+ step_fixtures: dict[str, Path], tmp_path: Path
+) -> None:
+ glb_path = tmp_path / "plates.glb"
+ result = convert_step(step_fixtures["plates"], glb_path)
+
+ compressed = tmp_path / "plates.meshopt.glb"
+ assert compress_glb(glb_path, compressed) is True
+ assert compressed.stat().st_size < glb_path.stat().st_size
+
+ gltf = GLTF2().load(str(compressed))
+ assert "EXT_meshopt_compression" in (gltf.extensionsUsed or [])
+ compressed_ids = {
+ node.extras["nodeId"]
+ for node in gltf.nodes
+ if node.extras and "nodeId" in node.extras
+ }
+ original_ids = {
+ n.extras["nodeId"]
+ for n in GLTF2().load(str(glb_path)).nodes
+ if n.extras and "nodeId" in n.extras
+ }
+ assert compressed_ids == original_ids
+
+
+def test_missing_cli_falls_back(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("PATH", str(tmp_path)) # nothing on PATH
+ source = tmp_path / "in.glb"
+ source.write_bytes(b"glTF")
+ assert compress_glb(source, tmp_path / "out.glb") is False
diff --git a/services/geometry/tests/test_plan.py b/services/geometry/tests/test_plan.py
new file mode 100644
index 0000000000..d5d09d7e19
--- /dev/null
+++ b/services/geometry/tests/test_plan.py
@@ -0,0 +1,1505 @@
+"""Planner core tests over synthetic geometry (no STEP/OCCT required)."""
+
+import numpy as np
+import pytest
+
+trimesh = pytest.importorskip("trimesh")
+pytest.importorskip("fcl")
+
+from app.plan import _greedy_disassembly, _Component, _plan_parts # noqa: E402
+
+
+def _box_part(node_id: str, extents, center, name: str | None = None) -> _Component:
+ mesh = trimesh.creation.box(extents=extents)
+ mesh.apply_translation(center)
+ bounds = mesh.bounds
+ return _Component(
+ node_id=node_id,
+ name=name or node_id,
+ mesh=mesh,
+ bbox_min=np.array(bounds[0]),
+ bbox_max=np.array(bounds[1]),
+ is_proxy=False,
+ )
+
+
+def _mesh_part(node_id: str, mesh, name: str | None = None) -> _Component:
+ bounds = mesh.bounds
+ return _Component(
+ node_id=node_id,
+ name=name or node_id,
+ mesh=mesh,
+ bbox_min=np.array(bounds[0]),
+ bbox_max=np.array(bounds[1]),
+ is_proxy=False,
+ )
+
+
+def _plan(parts):
+ return _greedy_disassembly(parts, trimesh, clearance=0.5, path_samples=40)
+
+
+def _plan_full(parts):
+ """Full pipeline: classification + rigid merge + greedy disassembly."""
+ warnings: list[str] = []
+ outcome = _plan_parts(
+ parts, trimesh, clearance=0.5, path_samples=40, warnings=warnings
+ )
+ return outcome, warnings
+
+
+def test_stacked_boxes_disassemble_top_down():
+ base = _box_part("base", (100, 100, 10), (0, 0, 5))
+ top = _box_part("top", (40, 40, 10), (0, 0, 15.05))
+
+ planned, sequence, tiers = _plan([base, top])
+
+ by_id = {entry.node_id: entry for entry in planned}
+ # The top box lifts straight up; the base is placed (no motion)
+ assert by_id["top"].motion["type"] == "linear"
+ assert by_id["top"].removal_direction == [0.0, 0.0, 1.0]
+ # Insertion direction is the reverse of removal
+ assert by_id["top"].motion["direction"] == [-0.0, -0.0, -1.0]
+ assert by_id["top"].motion["distance"] > 0
+ assert by_id["base"].motion["type"] == "none"
+
+ # Assembly order: base first, then the top box
+ assert sequence == ["base", "top"]
+ assert tiers["unplanned"] == 0
+
+
+def test_pin_in_bore_slides_out_along_axis():
+ # A plate with a clearance hole and a pin through it: the pin's only
+ # straight-line escape is +/-Z along the bore.
+ plate = trimesh.creation.box(extents=(60, 60, 20))
+ cylinder = trimesh.creation.cylinder(radius=5.2, height=30)
+ plate = plate.difference(cylinder)
+ bounds = plate.bounds
+ plate_part = _Component(
+ node_id="plate",
+ name="plate",
+ mesh=plate,
+ bbox_min=np.array(bounds[0]),
+ bbox_max=np.array(bounds[1]),
+ is_proxy=False,
+ )
+
+ pin = trimesh.creation.cylinder(radius=5.0, height=40)
+ pin_bounds = pin.bounds
+ pin_part = _Component(
+ node_id="pin",
+ name="pin",
+ mesh=pin,
+ bbox_min=np.array(pin_bounds[0]),
+ bbox_max=np.array(pin_bounds[1]),
+ is_proxy=False,
+ )
+
+ planned, sequence, _tiers = _plan([plate_part, pin_part])
+ by_id = {entry.node_id: entry for entry in planned}
+
+ assert by_id["pin"].motion["type"] == "linear"
+ direction = by_id["pin"].removal_direction
+ assert abs(direction[2]) == 1.0 and direction[0] == 0.0 and direction[1] == 0.0
+ assert sequence[0] == "plate"
+
+
+def test_captive_parts_merge_or_flag_never_forced():
+ # A box captive inside a shell can never separate from it: with exactly
+ # one blocker, the pair is one rigid unit by definition — merged, not
+ # flagged, never given a fabricated motion. With MULTIPLE blockers
+ # (nested shells), the captive part is flagged and fades in.
+ def hollow(outer_extent, cavity_extent, name):
+ outer = trimesh.creation.box(
+ extents=(outer_extent, outer_extent, outer_extent)
+ )
+ cavity = trimesh.creation.box(
+ extents=(cavity_extent, cavity_extent, cavity_extent)
+ )
+ return _mesh_part(name, outer.difference(cavity))
+
+ # Single blocker: inner merges into its shell
+ outcome, warnings = _plan_full(
+ [hollow(50, 40, "shell"), _box_part("inner", (30, 30, 30), (0, 0, 0))]
+ )
+ assert outcome.tiers["forced"] == 0
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.merged_into.get("inner") == "shell"
+ assert outcome.sequence == ["shell"]
+ assert any("rigid unit" in warning for warning in warnings)
+
+ # Multiple blockers: the innermost part flags (fades in), and the
+ # inner shell — left with a single blocker — merges into the outer
+ outcome, warnings = _plan_full(
+ [
+ hollow(70, 60, "outer-shell"),
+ hollow(50, 40, "inner-shell"),
+ _box_part("core", (30, 30, 30), (0, 0, 0)),
+ ]
+ )
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+ assert outcome.tiers["forced"] == 0
+ assert by_id["core"].tier == "flagged"
+ assert by_id["core"].motion["type"] == "none"
+ # blocked_by is recomputed against the FULL seated assembly, where the
+ # inner shell has rigid-merged into the outer — one pinning body
+ assert by_id["core"].blocked_by == ["outer-shell"]
+ assert outcome.merged_into.get("inner-shell") == "outer-shell"
+
+
+def test_rod_prefers_its_own_axis():
+ # A rod lying diagonally on a plate can exit +Z too, but its natural
+ # removal is along its own axis — fasteners must leave through their bores
+ base = _box_part("base", (200, 200, 10), (0, 0, 5))
+ rod = trimesh.creation.cylinder(radius=4, height=80)
+ # lay the rod along +X, floating just above the plate
+ rotate = trimesh.transformations.rotation_matrix(np.pi / 2, (0, 1, 0))
+ rod.apply_transform(rotate)
+ rod.apply_translation((0, 0, 14.2))
+ bounds = rod.bounds
+ rod_part = _Component(
+ node_id="rod",
+ name="rod",
+ mesh=rod,
+ bbox_min=np.array(bounds[0]),
+ bbox_max=np.array(bounds[1]),
+ is_proxy=False,
+ )
+
+ planned, _sequence, _tiers = _plan([base, rod_part])
+ by_id = {entry.node_id: entry for entry in planned}
+
+ direction = by_id["rod"].removal_direction
+ assert direction is not None
+ # Axis-first: the rod leaves along ±X (its own axis), not +Z
+ assert abs(direction[0]) == 1.0
+ assert direction[1] == 0.0 and direction[2] == 0.0
+
+
+def test_blind_pocket_escapes_with_multi_segment_motion():
+ # A part in a walled pocket, seated under an interior lip: it must first
+ # slide sideways out from under the lip, then lift through the open top.
+ # Tier 2's fixed lift-then-slide cannot solve this (its hop length is the
+ # part diagonal, which overshoots into the pocket wall) — the tier-3
+ # adaptive escape must find the slide-then-lift and emit a multi-segment
+ # "L" motion.
+ floor = trimesh.creation.box(extents=(60, 60, 5))
+ floor.apply_translation((0, 0, 2.5))
+ wall_px = trimesh.creation.box(extents=(10, 60, 40))
+ wall_px.apply_translation((25, 0, 20))
+ wall_nx = trimesh.creation.box(extents=(10, 60, 40))
+ wall_nx.apply_translation((-25, 0, 20))
+ wall_py = trimesh.creation.box(extents=(60, 10, 40))
+ wall_py.apply_translation((0, 25, 20))
+ wall_ny = trimesh.creation.box(extents=(60, 10, 40))
+ wall_ny.apply_translation((0, -25, 20))
+ lip = trimesh.creation.box(extents=(20, 40, 5))
+ lip.apply_translation((10, 0, 37.5))
+ container = trimesh.util.concatenate(
+ [floor, wall_px, wall_nx, wall_py, wall_ny, lip]
+ )
+ container_part = _Component(
+ node_id="container",
+ name="container",
+ mesh=container,
+ bbox_min=np.array(container.bounds[0]),
+ bbox_max=np.array(container.bounds[1]),
+ is_proxy=False,
+ )
+
+ part = _box_part("part", (18, 18, 10), (8, 0, 10))
+
+ planned, sequence, tiers = _plan([container_part, part])
+ by_id = {entry.node_id: entry for entry in planned}
+
+ assert tiers["escape"] >= 1
+ assert tiers["unplanned"] == 0
+ assert sequence[0] == "container"
+ assert by_id["container"].motion["type"] == "none"
+
+ motion = by_id["part"].motion
+ assert motion["type"] == "L"
+ assert len(motion["segments"]) >= 2
+ assert by_id["part"].confidence == "low"
+ # Insertion reverses the removal: drop in through the open top, then
+ # slide +X under the lip into the seated pose
+ first, last = motion["segments"][0], motion["segments"][-1]
+ assert first["direction"][2] < -0.9
+ assert last["direction"][0] > 0.9
+
+
+def test_captive_washer_assembles_before_its_bolt():
+ # Washer captive between a bolt head and the plate: disassembly must pull
+ # the bolt first, so assembly order is plate -> washer -> bolt.
+ plate = trimesh.creation.box(extents=(60, 60, 20))
+ plate.apply_translation((0, 0, 10))
+ hole = trimesh.creation.cylinder(radius=5.2, height=30)
+ hole.apply_translation((0, 0, 10))
+ plate = plate.difference(hole)
+ plate_part = _Component(
+ node_id="plate",
+ name="plate",
+ mesh=plate,
+ bbox_min=np.array(plate.bounds[0]),
+ bbox_max=np.array(plate.bounds[1]),
+ is_proxy=False,
+ )
+
+ washer = trimesh.creation.annulus(r_min=4.4, r_max=9.0, height=1.5)
+ washer.apply_translation((0, 0, 20.85))
+ washer_part = _Component(
+ node_id="washer",
+ name="washer",
+ mesh=washer,
+ bbox_min=np.array(washer.bounds[0]),
+ bbox_max=np.array(washer.bounds[1]),
+ is_proxy=False,
+ )
+
+ shaft = trimesh.creation.cylinder(radius=4.0, height=22)
+ shaft.apply_translation((0, 0, 11))
+ head = trimesh.creation.cylinder(radius=8.0, height=5)
+ head.apply_translation((0, 0, 24.2))
+ bolt = shaft.union(head)
+ bolt_part = _Component(
+ node_id="bolt",
+ name="bolt",
+ mesh=bolt,
+ bbox_min=np.array(bolt.bounds[0]),
+ bbox_max=np.array(bolt.bounds[1]),
+ is_proxy=False,
+ )
+
+ planned, sequence, _tiers = _plan([plate_part, washer_part, bolt_part])
+ by_id = {entry.node_id: entry for entry in planned}
+
+ # The bolt leaves along its axis; the washer follows once the bolt is out
+ assert by_id["bolt"].motion["type"] == "linear"
+ assert sequence.index("washer") < sequence.index("bolt")
+ assert sequence.index("plate") < sequence.index("washer")
+
+
+def test_screw_unscrews_through_its_threaded_mate():
+ # Solid thread model: screw shaft r5.0 in a plate bore r4.6 — a real
+ # 0.4mm interference. The plate is detected as the screw's threaded
+ # mate, so travel along the screw's own axis tolerates that steady
+ # interference and the screw exits through its bore instead of being
+ # flagged. No blanket allowance exists for any other contact.
+ plate = trimesh.creation.box(extents=(40, 40, 10))
+ plate.apply_translation((0, 0, 5))
+ bore = trimesh.creation.cylinder(radius=4.6, height=20)
+ bore.apply_translation((0, 0, 5))
+ plate = plate.difference(bore)
+ plate_part = _mesh_part("plate", plate)
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=24)
+ shaft.apply_translation((0, 0, 4))
+ head = trimesh.creation.cylinder(radius=8.0, height=4)
+ head.apply_translation((0, 0, 18))
+ screw = shaft.union(head)
+ screw_part = _mesh_part("screw", screw, name="Screw M5x30")
+
+ outcome, _warnings = _plan_full([plate_part, screw_part])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.tiers["flagged"] == 0
+ assert by_id["screw"].motion["type"] == "linear"
+ direction = by_id["screw"].removal_direction
+ assert direction is not None
+ # Out through the bore: the head side (+Z); -Z is blocked because the
+ # head cannot pass through its own mate beyond the thread interference
+ assert direction[2] > 0.9
+ assert outcome.sequence == ["plate", "screw"]
+
+
+def test_fastener_never_tunnels_a_thin_unmated_cover():
+ # A 1mm cover floats just above the screw head. It is NOT a mate, so
+ # the strict tolerance applies: the old blanket thread allowance
+ # (1.5mm) let the screw tunnel straight up through it whenever its
+ # axis was tried head-first. Now the screw must exit the open way
+ # (down, -Z) — never through the cover.
+ shaft = trimesh.creation.cylinder(radius=5.0, height=30)
+ shaft.apply_translation((0, 0, 15))
+ head = trimesh.creation.cylinder(radius=8.0, height=4)
+ head.apply_translation((0, 0, 32))
+ screw = shaft.union(head)
+ screw_part = _mesh_part("screw", screw, name="Screw M5x40")
+
+ cover = trimesh.creation.box(extents=(40, 40, 1))
+ cover.apply_translation((0, 0, 35.2))
+ cover_part = _mesh_part("cover", cover)
+
+ outcome, _warnings = _plan_full([screw_part, cover_part])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.tiers["flagged"] == 0
+ screw_direction = by_id["screw"].removal_direction
+ assert screw_direction is not None
+ assert screw_direction[2] < -0.9
+
+
+def test_embedded_logo_merges_into_its_host():
+ # A logo/text solid fully inside its host produces no surface contacts
+ # at all — containment testing must catch it and plan the pair as one
+ # rigid unit under the host's nodeId.
+ base = _box_part("base", (80, 80, 10), (0, 0, 5))
+ host = _box_part("host", (40, 40, 20), (0, 0, 20.05))
+ logo = _box_part("logo", (10, 10, 2), (0, 0, 20.05), name="3D LOGO")
+
+ outcome, warnings = _plan_full([base, host, logo])
+
+ assert outcome.merged_into == {"logo": "host"}
+ assert "logo" not in outcome.sequence
+ assert set(outcome.sequence) == {"base", "host"}
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+ assert by_id["host"].motion["type"] == "linear"
+ assert outcome.tiers["flagged"] == 0
+ assert any("rigid unit" in warning for warning in warnings)
+
+
+def test_captive_washer_ordering_with_real_fastener_names():
+ # Same captive-washer fixture as the legacy test, but through the full
+ # pipeline with realistic catalog names — classification (axis-only
+ # candidates for both fasteners) must preserve plate -> washer -> bolt.
+ plate = trimesh.creation.box(extents=(60, 60, 20))
+ plate.apply_translation((0, 0, 10))
+ hole = trimesh.creation.cylinder(radius=5.2, height=30)
+ hole.apply_translation((0, 0, 10))
+ plate = plate.difference(hole)
+ plate_part = _mesh_part("plate", plate)
+
+ washer = trimesh.creation.annulus(r_min=4.4, r_max=9.0, height=1.5)
+ washer.apply_translation((0, 0, 20.85))
+ washer_part = _mesh_part("washer", washer, name="Washer DIN 125")
+
+ shaft = trimesh.creation.cylinder(radius=4.0, height=22)
+ shaft.apply_translation((0, 0, 11))
+ head = trimesh.creation.cylinder(radius=8.0, height=5)
+ head.apply_translation((0, 0, 24.2))
+ bolt = shaft.union(head)
+ bolt_part = _mesh_part("bolt", bolt, name="Hex Bolt M8")
+
+ outcome, _warnings = _plan_full([plate_part, washer_part, bolt_part])
+
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.sequence.index("plate") < outcome.sequence.index("washer")
+ assert outcome.sequence.index("washer") < outcome.sequence.index("bolt")
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+ assert by_id["bolt"].motion["type"] == "linear"
+ direction = by_id["bolt"].removal_direction
+ assert direction is not None
+ assert abs(direction[2]) > 0.9
+
+
+def test_sequence_orders_fasteners_right_after_their_stack():
+ # Structure assembles bottom-up and a fastener installs as soon as the
+ # parts it secures are present — not scattered to the end. The screw's
+ # clearance hole through the bracket derives no constraint, but the
+ # bracket's own insertion sweep collides with the seated screw head,
+ # which forces bracket-before-screw; the tapped plate precedes the
+ # screw via the stack preference.
+ plate = trimesh.creation.box(extents=(80, 80, 10))
+ plate.apply_translation((0, 0, 5))
+ tapped = trimesh.creation.cylinder(radius=4.6, height=20)
+ tapped.apply_translation((0, 0, 5))
+ plate = plate.difference(tapped)
+ plate_part = _mesh_part("plate", plate)
+
+ bracket = trimesh.creation.box(extents=(30, 30, 8))
+ bracket.apply_translation((0, 0, 14))
+ clearance = trimesh.creation.cylinder(radius=5.4, height=20)
+ clearance.apply_translation((0, 0, 14))
+ bracket = bracket.difference(clearance)
+ bracket_part = _mesh_part("bracket", bracket)
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=18)
+ shaft.apply_translation((0, 0, 11))
+ head = trimesh.creation.cylinder(radius=8.0, height=4)
+ head.apply_translation((0, 0, 22))
+ screw = shaft.union(head)
+ screw_part = _mesh_part("screw", screw, name="Screw M6x20")
+
+ block = _box_part("block", (20, 20, 20), (30, 0, 22))
+
+ outcome, _warnings = _plan_full(
+ [plate_part, bracket_part, screw_part, block]
+ )
+
+ assert outcome.sequence[0] == "plate"
+ assert outcome.sequence.index("bracket") < outcome.sequence.index("screw")
+ # Securing fastener fires the moment its joint completes
+ assert (
+ outcome.sequence.index("screw")
+ == outcome.sequence.index("bracket") + 1
+ )
+ assert outcome.tiers["flagged"] == 0
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_bolt_precedes_nut_in_assembly():
+ # The threaded pair is contact-exempt during planning, so no collision
+ # edge derives between bolt and nut — the explicit stack preference
+ # must order the bolt (rod) before its nut (disc), never a nut
+ # floating in air waiting for its bolt.
+ plate = trimesh.creation.box(extents=(60, 60, 10))
+ plate.apply_translation((0, 0, 5))
+ bore = trimesh.creation.cylinder(radius=5.4, height=20)
+ bore.apply_translation((0, 0, 5))
+ plate = plate.difference(bore)
+ plate_part = _mesh_part("plate", plate)
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=22)
+ shaft.apply_translation((0, 0, 3))
+ head = trimesh.creation.cylinder(radius=9.0, height=4)
+ head.apply_translation((0, 0, 16))
+ bolt = shaft.union(head)
+ bolt_part = _mesh_part("bolt", bolt, name="Hex Bolt M10")
+
+ nut = trimesh.creation.annulus(r_min=4.6, r_max=9.0, height=5)
+ nut.apply_translation((0, 0, -4.5))
+ nut_part = _mesh_part("nut", nut, name="Hex Nut M10")
+
+ outcome, _warnings = _plan_full([plate_part, bolt_part, nut_part])
+
+ assert outcome.sequence.index("plate") < outcome.sequence.index("bolt")
+ assert outcome.sequence.index("bolt") < outcome.sequence.index("nut")
+ assert outcome.tiers["flagged"] == 0
+ assert all(entry.verified for entry in outcome.planned)
+ assert outcome.verified_count == 3
+
+
+def test_plan_is_deterministic():
+ # Same input, same plan — twice through the full pipeline.
+ def build():
+ base = _box_part("base", (100, 100, 10), (0, 0, 5))
+ left = _box_part("left", (20, 20, 20), (-30, 0, 20.05))
+ right = _box_part("right", (20, 20, 20), (30, 0, 20.05))
+ return [base, left, right]
+
+ first, _ = _plan_full(build())
+ second, _ = _plan_full(build())
+
+ assert first.sequence == second.sequence
+ assert [entry.motion for entry in first.planned] == [
+ entry.motion for entry in second.planned
+ ]
+ assert [entry.verified for entry in first.planned] == [
+ entry.verified for entry in second.planned
+ ]
+
+
+def _keyed_hub_parts():
+ """Hub keyed to a shaft: the key is captive in the hub's blind pocket
+ and proud into the shaft's full-length slot. Hub and key cannot move
+ alone (they drag each other), but hub+key slide off the shaft end as
+ one unit."""
+ shaft = trimesh.creation.cylinder(radius=10, height=120)
+ shaft.apply_transform(
+ trimesh.transformations.rotation_matrix(np.pi / 2, (0, 1, 0))
+ )
+ slot = trimesh.creation.box(extents=(124, 4.4, 6))
+ slot.apply_translation((0, 0, 8.5))
+ shaft = shaft.difference(slot)
+ shaft_part = _mesh_part("shaft", shaft)
+
+ key = trimesh.creation.box(extents=(20, 4, 5))
+ key.apply_translation((0, 0, 8.2))
+ key_part = _mesh_part("key", key)
+
+ hub = trimesh.creation.cylinder(radius=18, height=30)
+ hub.apply_transform(
+ trimesh.transformations.rotation_matrix(np.pi / 2, (0, 1, 0))
+ )
+ bore = trimesh.creation.cylinder(radius=10.2, height=40)
+ bore.apply_transform(
+ trimesh.transformations.rotation_matrix(np.pi / 2, (0, 1, 0))
+ )
+ pocket = trimesh.creation.box(extents=(24, 4.8, 2.2))
+ pocket.apply_translation((0, 0, 10.0))
+ hub = hub.difference(bore).difference(pocket)
+ hub_part = _mesh_part("hub", hub)
+
+ return shaft_part, key_part, hub_part
+
+
+def test_group_search_finds_the_keyed_hub_unit():
+ # Direct unit test of the subassembly search on a stuck state: neither
+ # hub nor key moves alone, but the pair slides off the shaft end.
+ from trimesh.collision import CollisionManager
+
+ from app.plan import _plan_group_removal
+
+ shaft_part, key_part, hub_part = _keyed_hub_parts()
+ remaining = {
+ part.node_id: part for part in (shaft_part, key_part, hub_part)
+ }
+ manager = CollisionManager()
+ for part in remaining.values():
+ manager.add_object(part.node_id, part.mesh)
+
+ group = _plan_group_removal(remaining, manager, 40, {}, trimesh)
+
+ assert group is not None
+ members, combined, entry = group
+ assert set(members) == {"hub", "key"}
+ assert combined.node_id == "hub" # largest member is the representative
+ assert entry.tier == "group"
+ assert entry.motion["type"] == "linear"
+ assert entry.removal_direction is not None
+ assert abs(entry.removal_direction[0]) > 0.9 # off the shaft end
+
+
+def test_group_unit_flows_through_sequence_and_payload(monkeypatch):
+ # Plumbing test for subassembly units: with single-part removals stubbed
+ # out (a pure translational fixture always lets the complement slide
+ # instead — greedy rightly prefers that), the stuck state must fall
+ # through to group extraction, and the unit must flow into the
+ # sequence, the groups payload, and per-member entries.
+ import app.plan as plan_module
+
+ monkeypatch.setattr(
+ plan_module, "_plan_removal", lambda *args, **kwargs: None
+ )
+ monkeypatch.setattr(
+ plan_module, "_plan_escape", lambda *args, **kwargs: None
+ )
+
+ shaft_part, key_part, hub_part = _keyed_hub_parts()
+ outcome, _warnings = _plan_full([shaft_part, key_part, hub_part])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.tiers["group"] == 1
+ assert len(outcome.groups) == 1
+ group = next(iter(outcome.groups.values()))
+ assert set(group["componentNodeIds"]) == {"hub", "key"}
+ assert group["motion"]["type"] == "linear"
+ # Both members carry the shared motion and groupId
+ assert by_id["hub"].group_id == by_id["key"].group_id
+ assert by_id["hub"].group_id is not None
+ assert by_id["hub"].motion == by_id["key"].motion
+ assert by_id["hub"].tier == "group"
+ assert by_id["key"].tier == "group"
+ # Forward verification runs against the real geometry
+ assert by_id["hub"].verified and by_id["key"].verified
+ # The unit's members sit adjacently in the sequence, after the shaft
+ assert outcome.sequence[0] == "shaft"
+ hub_index = outcome.sequence.index("hub")
+ key_index = outcome.sequence.index("key")
+ assert abs(hub_index - key_index) == 1
+
+
+def test_stud_installs_after_everything_it_clamps():
+ # A headless stud through a bracket into a tapped plate: no head means
+ # no collision constraint ever derives between bracket and stud — only
+ # the joint edge (the bracket's material surrounds the stud's shank)
+ # forces the clamped bracket to precede its fastener.
+ plate = trimesh.creation.box(extents=(80, 80, 10))
+ plate.apply_translation((0, 0, 5))
+ tapped = trimesh.creation.cylinder(radius=4.6, height=20)
+ tapped.apply_translation((0, 0, 5))
+ plate = plate.difference(tapped)
+ plate_part = _mesh_part("plate", plate)
+
+ bracket = trimesh.creation.box(extents=(30, 30, 8))
+ bracket.apply_translation((0, 0, 14))
+ clearance = trimesh.creation.cylinder(radius=5.6, height=20)
+ clearance.apply_translation((0, 0, 14))
+ bracket = bracket.difference(clearance)
+ bracket_part = _mesh_part("bracket", bracket)
+
+ stud = trimesh.creation.cylinder(radius=5.0, height=26)
+ stud.apply_translation((0, 0, 15))
+ stud_part = _mesh_part("stud", stud, name="Threaded Stud M10")
+
+ outcome, _warnings = _plan_full([plate_part, bracket_part, stud_part])
+
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.sequence.index("plate") < outcome.sequence.index("bracket")
+ assert outcome.sequence.index("bracket") < outcome.sequence.index("stud")
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_slip_fit_washer_still_precedes_its_bolt():
+ # A slip-over washer whose bore is WIDER than the bolt head: no
+ # collision constraint exists in either direction — only the joint
+ # edge (the bolt's shank passes through the washer) orders it before
+ # the bolt.
+ plate = trimesh.creation.box(extents=(60, 60, 12))
+ plate.apply_translation((0, 0, 6))
+ tapped = trimesh.creation.cylinder(radius=4.6, height=30)
+ tapped.apply_translation((0, 0, 6))
+ plate = plate.difference(tapped)
+ plate_part = _mesh_part("plate", plate)
+
+ washer = trimesh.creation.annulus(r_min=8.6, r_max=14.0, height=2)
+ washer.apply_translation((0, 0, 13.1))
+ washer_part = _mesh_part("washer", washer, name="Washer oversize")
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=18)
+ shaft.apply_translation((0, 0, 5))
+ head = trimesh.creation.cylinder(radius=8.0, height=4)
+ head.apply_translation((0, 0, 16))
+ bolt = shaft.union(head)
+ bolt_part = _mesh_part("bolt", bolt, name="Hex Bolt M10")
+
+ outcome, _warnings = _plan_full([plate_part, washer_part, bolt_part])
+
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.sequence.index("washer") < outcome.sequence.index("bolt")
+ assert outcome.sequence.index("plate") < outcome.sequence.index("washer")
+
+
+def test_big_central_parts_assemble_first():
+ # Free choice everywhere (everything lifts straight out): the sequence
+ # must open with the big central block, not the small outboard ones.
+ slab = _box_part("slab", (200, 200, 10), (0, 0, 5))
+ center = _box_part("center", (60, 60, 60), (0, 0, 40.05))
+ left = _box_part("left", (15, 15, 15), (-70, 0, 17.55))
+ right = _box_part("right", (15, 15, 15), (70, 0, 17.55))
+
+ outcome, _warnings = _plan_full([slab, center, left, right])
+
+ assert outcome.sequence[0] == "slab"
+ assert outcome.sequence[1] == "center"
+ assert set(outcome.sequence[2:]) == {"left", "right"}
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_snug_counterbore_bolt_slides_through_its_joint():
+ # The bolt's flange head drags through the bracket's counterbore with
+ # 0.3mm of interference (a snug fit — on tessellated CAD this is what
+ # tight clearances read as). The bracket is in the bolt's JOINT, and
+ # along its bore axis a fastener is allowed sliding engagement with
+ # its joint members — so the bolt exits through the hole instead of
+ # being flagged.
+ plate = trimesh.creation.box(extents=(60, 60, 10))
+ plate.apply_translation((0, 0, 5))
+ tapped = trimesh.creation.cylinder(radius=4.6, height=20)
+ tapped.apply_translation((0, 0, 5))
+ plate = plate.difference(tapped)
+ plate_part = _mesh_part("plate", plate)
+
+ bracket = trimesh.creation.box(extents=(40, 40, 12))
+ bracket.apply_translation((0, 0, 16))
+ through = trimesh.creation.cylinder(radius=5.6, height=30)
+ through.apply_translation((0, 0, 16))
+ counterbore = trimesh.creation.cylinder(radius=7.7, height=6)
+ counterbore.apply_translation((0, 0, 19.2))
+ bracket = bracket.difference(through).difference(counterbore)
+ bracket_part = _mesh_part("bracket", bracket)
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=22)
+ shaft.apply_translation((0, 0, 8))
+ head = trimesh.creation.cylinder(radius=8.0, height=3.5)
+ head.apply_translation((0, 0, 20.75))
+ bolt = shaft.union(head)
+ bolt_part = _mesh_part("bolt", bolt, name="Bolt M10 Flange")
+
+ outcome, _warnings = _plan_full([plate_part, bracket_part, bolt_part])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.tiers["flagged"] == 0
+ assert by_id["bolt"].motion["type"] == "linear"
+ direction = by_id["bolt"].removal_direction
+ assert direction is not None
+ assert direction[2] > 0.9 # out through the counterbore, head side
+ assert outcome.sequence.index("plate") < outcome.sequence.index("bracket")
+ assert outcome.sequence.index("bracket") < outcome.sequence.index("bolt")
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_part_escapes_along_tilted_contact_normal():
+ # A block seated flush in a tilted pocket: every world axis digs into a
+ # pocket wall, and the block has no rod/disc symmetry. The seated
+ # contact normals ARE the pocket's tilt — the planner must offer them
+ # as candidate directions and lift the block out along the tilt.
+ tilt = trimesh.transformations.rotation_matrix(np.pi / 6, (0, 1, 0))
+ normal = np.array(
+ [float(np.sin(np.pi / 6)), 0.0, float(np.cos(np.pi / 6))]
+ )
+
+ base = trimesh.creation.box(extents=(120, 80, 60))
+ base.apply_translation((0, 0, 30))
+ pocket_cut = trimesh.creation.box(extents=(40, 40, 40))
+ pocket_cut.apply_transform(tilt)
+ pocket_cut.apply_translation((0, 0, 58))
+ base = base.difference(pocket_cut)
+ base_part = _mesh_part("base", base)
+
+ # Seat the block flush on the pocket floor, 0.05mm into it so seated
+ # contacts (and their normals) exist:
+ # center = cut_center + R·(0, 0, -(20 - 6)) - 0.05·normal
+ block = trimesh.creation.box(extents=(39.5, 39.5, 12))
+ block.apply_transform(tilt)
+ block.apply_translation((-7.025, 0, 45.831))
+ block_part = _mesh_part("block", block)
+
+ outcome, _warnings = _plan_full([base_part, block_part])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.tiers["flagged"] == 0
+ assert by_id["block"].motion["type"] == "linear"
+ direction = by_id["block"].removal_direction
+ assert direction is not None
+ assert abs(float(np.dot(np.asarray(direction), normal))) > 0.98
+ assert by_id["block"].verified
+
+
+def test_merge_units_collapses_members_into_one_body():
+ from app.plan import _merge_units
+
+ a = _box_part("a", (10, 10, 10), (0, 0, 0))
+ b = _box_part("b", (10, 10, 10), (20, 0, 0))
+ c = _box_part("c", (10, 10, 10), (40, 0, 0))
+
+ parts, expansion = _merge_units(
+ [a, b, c],
+ [
+ {"id": "u1", "name": "PCB Assembly", "nodeIds": ["a", "b"]},
+ {"id": "u2", "name": "Solo", "nodeIds": ["c"]}, # single member: skipped
+ ],
+ trimesh,
+ )
+
+ by_id = {p.node_id: p for p in parts}
+ # a+b merged into one body "u1"; c stays; the single-member unit is a no-op.
+ assert set(by_id) == {"u1", "c"}
+ assert expansion == {"u1": {"members": ["a", "b"], "name": "PCB Assembly"}}
+ # The merged body spans both boxes' bounds.
+ assert by_id["u1"].mesh.vertices.shape[0] == a.mesh.vertices.shape[0] * 2
+ assert by_id["u1"].bbox_min[0] == pytest.approx(-5.0)
+ assert by_id["u1"].bbox_max[0] == pytest.approx(25.0)
+
+
+def test_merge_units_body_plans_as_a_single_step():
+ from app.plan import _merge_units
+
+ # A base with a two-solid "module" stacked on top; the module is one unit.
+ base = _box_part("base", (100, 100, 10), (0, 0, 5))
+ mod_a = _box_part("mod_a", (40, 40, 10), (0, 0, 15.05))
+ mod_b = _box_part("mod_b", (20, 20, 10), (0, 0, 25.10))
+
+ parts, expansion = _merge_units(
+ [base, mod_a, mod_b],
+ [{"id": "module", "name": "Module", "nodeIds": ["mod_a", "mod_b"]}],
+ trimesh,
+ )
+ assert {p.node_id for p in parts} == {"base", "module"}
+
+ outcome, _ = _plan_full(parts)
+ # The whole module is one planned body that lifts off the base.
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+ assert "module" in by_id
+ assert by_id["module"].motion["type"] == "linear"
+ assert expansion["module"]["members"] == ["mod_a", "mod_b"]
+
+
+def test_large_snap_on_clip_assembles_last():
+ # A slide-on clip that nothing clamps and that seats against only the
+ # base is a terminal attachment: it assembles LAST even though it is
+ # much bigger than the screwed-down bracket. Volume alone must not
+ # drag it early — "least secured goes last" is the principle.
+ plate = trimesh.creation.box(extents=(100, 100, 10))
+ plate.apply_translation((0, 0, 5))
+ tapped = trimesh.creation.cylinder(radius=4.6, height=20)
+ tapped.apply_translation((0, 0, 5))
+ plate = plate.difference(tapped)
+ plate_part = _mesh_part("plate", plate)
+
+ bracket = trimesh.creation.box(extents=(30, 30, 8))
+ bracket.apply_translation((0, 0, 14))
+ clearance = trimesh.creation.cylinder(radius=5.4, height=20)
+ clearance.apply_translation((0, 0, 14))
+ bracket = bracket.difference(clearance)
+ bracket_part = _mesh_part("bracket", bracket)
+
+ shaft = trimesh.creation.cylinder(radius=5.0, height=18)
+ shaft.apply_translation((0, 0, 11))
+ head = trimesh.creation.cylinder(radius=8.0, height=4)
+ head.apply_translation((0, 0, 22))
+ screw = shaft.union(head)
+ screw_part = _mesh_part("screw", screw, name="Screw M6x20")
+
+ # Bigger than the bracket, seated 0.1mm into the plate, unfastened,
+ # clear of the bracket and screw head in X
+ clip = _box_part("clip", (30, 40, 24), (33, 0, 21.9))
+ assert clip.mesh.volume > bracket_part.mesh.volume
+
+ outcome, _warnings = _plan_full(
+ [plate_part, bracket_part, screw_part, clip]
+ )
+
+ assert outcome.sequence[0] == "plate"
+ assert outcome.sequence[-1] == "clip"
+ # The securing screw still fires right after its joint completes
+ assert (
+ outcome.sequence.index("screw")
+ == outcome.sequence.index("bracket") + 1
+ )
+ assert outcome.tiers["flagged"] == 0
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_part_with_blocked_insertion_is_not_demoted():
+ # A slider in a blind channel also has exactly one seated neighbor and
+ # no fastener — but its only insertion path is closed by the end stop,
+ # so it carries an outgoing precedence edge and must NOT be demoted to
+ # the terminal tier (the seat-rail slider case).
+ rail = trimesh.creation.box(extents=(100, 40, 25))
+ rail.apply_translation((0, 0, 12.5))
+ # Blind tunnel: open at +X only, a 5mm plug remains at the -X end
+ tunnel = trimesh.creation.box(extents=(95, 20, 10))
+ tunnel.apply_translation((2.5, 0, 14))
+ # Subdivide like a real tessellation: giant coplanar box triangles
+ # report phantom penetration depths spanning the whole sliding face
+ rail = rail.difference(tunnel).subdivide_to_size(5.0)
+ rail_part = _mesh_part("rail", rail)
+
+ # Seated 0.05mm against the blind-end plug (x=-45), clearance to the
+ # tunnel floor and walls so the slide out is a clean fit
+ slider_mesh = trimesh.creation.box(extents=(80, 19.6, 9.6))
+ slider_mesh.apply_translation((-5.05, 0, 14))
+ slider = _mesh_part("slider", slider_mesh.subdivide_to_size(5.0))
+
+ # End stop seated 0.05mm against the rail's +X face, covering the
+ # tunnel opening
+ stop_mesh = trimesh.creation.box(extents=(10, 30, 20))
+ stop_mesh.apply_translation((54.95, 0, 10))
+ stop = _mesh_part("stop", stop_mesh.subdivide_to_size(5.0))
+
+ outcome, _warnings = _plan_full([rail_part, slider, stop])
+
+ assert outcome.sequence[0] == "rail"
+ # The slider's escape sweeps through the seated end stop: that edge
+ # keeps it early despite one contact and no fastener
+ assert "stop" in outcome.edges.get("slider", set())
+ assert outcome.sequence == ["rail", "slider", "stop"]
+ assert outcome.tiers["flagged"] == 0
+
+
+def _enclosure_with_gasket(gasket_bite: float, lid_bite: float):
+ """Open-top box, thin gasket frame on the rim, flat lid on the gasket.
+
+ The gasket ring (58x58 outer, 52x52 hole, 2mm thick) sits strictly
+ within the 5mm rim so its contacts with box and lid are purely
+ horizontal faces. `gasket_bite`/`lid_bite` control the seated
+ interpenetration at each interface.
+ """
+ box = trimesh.creation.box(extents=(60, 60, 30))
+ box.apply_translation((0, 0, 15))
+ cavity = trimesh.creation.box(extents=(50, 50, 30))
+ cavity.apply_translation((0, 0, 17))
+ # Subdivide like a real tessellation: giant coplanar box triangles
+ # report phantom penetration far beyond the geometric bite
+ box = box.difference(cavity).subdivide_to_size(5.0)
+ box_part = _mesh_part("box", box)
+
+ gasket = trimesh.creation.box(extents=(58, 58, 2))
+ hole = trimesh.creation.box(extents=(52, 52, 4))
+ gasket = gasket.difference(hole).subdivide_to_size(5.0)
+ # Box rim top is z=30; seat the gasket biting into it
+ gasket.apply_translation((0, 0, 31 - gasket_bite))
+ gasket_part = _mesh_part("gasket", gasket)
+
+ gasket_top = 32 - gasket_bite
+ lid_mesh = trimesh.creation.box(extents=(60, 60, 4))
+ lid_mesh.apply_translation((0, 0, gasket_top + 2 - lid_bite))
+ lid = _mesh_part("lid", lid_mesh.subdivide_to_size(5.0))
+ return box_part, gasket_part, lid
+
+
+def test_sandwiched_gasket_orders_between_flanges():
+ # A thin part with seated contact on BOTH sides along one axis is
+ # sandwiched: the enclosure side assembles first, then the part, then
+ # the compressor — even though the gasket is the smallest body and
+ # nothing else constrains it.
+ box_part, gasket_part, lid = _enclosure_with_gasket(0.05, 0.05)
+
+ outcome, _warnings = _plan_full([box_part, gasket_part, lid])
+
+ assert outcome.sequence == ["box", "gasket", "lid"]
+ assert outcome.tiers["flagged"] == 0
+ assert "gasket" not in outcome.merged_into
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def test_interfering_gasket_still_plans():
+ # A compressed gasket modeled with real interference (0.4mm into both
+ # flanges, past the 0.15mm tolerance) must still plan: the seated
+ # squish is granted as a compliant allowance, the lid's sweep is not
+ # spuriously blocked, and the gasket is never rigid-merged into a
+ # flange or flagged.
+ box_part, gasket_part, lid = _enclosure_with_gasket(0.4, 0.4)
+
+ outcome, warnings = _plan_full([box_part, gasket_part, lid])
+
+ assert outcome.sequence == ["box", "gasket", "lid"]
+ assert outcome.tiers["flagged"] == 0
+ assert outcome.merged_into == {}
+ assert not any("rigid unit" in warning for warning in warnings)
+ assert all(entry.verified for entry in outcome.planned)
+
+
+def _detect_sandwiches(parts):
+ from app.plan import (
+ _classify_fasteners,
+ _sandwiched_parts,
+ _seated_pair_depths,
+ )
+
+ pair_depths = _seated_pair_depths(parts, trimesh)
+ fasteners = _classify_fasteners(parts, pair_depths)
+ return _sandwiched_parts(parts, pair_depths, fasteners, {})
+
+
+def test_thick_stack_is_not_a_sandwich():
+ # A 15mm plate seated between two bodies passes the proportional
+ # thinness ratio (15 <= 0.3 * 60) but is NOT a gasket: the absolute
+ # thickness cap rejects it, so no allowance corrupts its collisions.
+ bottom = _box_part("bottom", (60, 60, 10), (0, 0, 5))
+ middle = _box_part("middle", (60, 60, 15), (0, 0, 17.45)) # bites 0.05
+ top = _box_part("top", (60, 60, 10), (0, 0, 29.9)) # bites 0.05
+
+ assert _detect_sandwiches([bottom, middle, top]) == {}
+ assert middle.seated_allowance == {}
+
+
+def test_deep_bite_is_not_a_sandwich():
+ # A thin ring with 1.5mm reported interference is a press fit or
+ # broken CAD, not compliant squish — granting an allowance would
+ # tunnel real geometry, so the part is not classified at all. The
+ # gate is pure logic on the reported depth, so feed it fabricated
+ # pair data (synthetic meshes report parallel-face penetration
+ # unreliably in both directions).
+ from app.plan import _sandwiched_parts
+
+ box = _box_part("box", (60, 60, 30), (0, 0, 14))
+ gasket = _box_part("gasket", (58, 58, 2), (0, 0, 30))
+ lid = _box_part("lid", (60, 60, 4), (0, 0, 33))
+ tensor = np.diag([0.0, 0.0, 8.0])
+
+ def pairs(depth):
+ def pair(z):
+ return (depth, [np.array([0.0, 0.0, z])] * 4, [], tensor, None)
+
+ return {
+ frozenset(("box", "gasket")): pair(29.2),
+ frozenset(("gasket", "lid")): pair(30.8),
+ }
+
+ parts = [box, gasket, lid]
+ assert _sandwiched_parts(parts, pairs(1.5), {}, {}) == {}
+ assert gasket.seated_allowance == {}
+ # The identical geometry with squish-scale interference IS a sandwich
+ assert "gasket" in _sandwiched_parts(parts, pairs(0.3), {}, {})
+ assert gasket.seated_allowance == {"box": 0.3, "lid": 0.3}
+
+
+def test_sandwich_allowance_is_axis_gated():
+ # A genuine gasket's squish allowance applies only along the sandwich
+ # axis (like a thread mate along its bore): lateral motion is judged
+ # strictly, so a misclassified part can never slide sideways through
+ # real geometry.
+ from app.plan import _seated_exempt
+
+ box_part, gasket_part, lid = _enclosure_with_gasket(0.4, 0.4)
+ sandwiches = _detect_sandwiches([box_part, gasket_part, lid])
+
+ assert "gasket" in sandwiches
+ along_axis = _seated_exempt(gasket_part, np.array([0.0, 0.0, 1.0]))
+ assert along_axis is not None and "lid" in along_axis
+ assert _seated_exempt(gasket_part, np.array([1.0, 0.0, 0.0])) is None
+ # The flange side gets the mirrored, equally axis-gated allowance
+ lid_along = _seated_exempt(lid, np.array([0.0, 0.0, -1.0]))
+ assert lid_along is not None and "gasket" in lid_along
+ assert _seated_exempt(lid, np.array([0.0, 1.0, 0.0])) is None
+
+
+def test_parts_with_dependents_precede_terminal_accessories():
+ # The dependency spine: a small slider that a later part waits on
+ # (its insertion path is closed by the end stop) assembles before a
+ # BIGGER terminal bridge nothing depends on. Volume must not drag the
+ # terminal accessory early — the assembly proceeds along the spine.
+ rail = trimesh.creation.box(extents=(100, 40, 25))
+ rail.apply_translation((0, 0, 12.5))
+ tunnel = trimesh.creation.box(extents=(95, 20, 10))
+ tunnel.apply_translation((2.5, 0, 14))
+ rail = rail.difference(tunnel).subdivide_to_size(5.0)
+ rail_part = _mesh_part("rail", rail)
+
+ slider_mesh = trimesh.creation.box(extents=(80, 19.6, 9.6))
+ slider_mesh.apply_translation((-5.05, 0, 14))
+ slider = _mesh_part("slider", slider_mesh.subdivide_to_size(5.0))
+
+ stop_mesh = trimesh.creation.box(extents=(10, 30, 20))
+ stop_mesh.apply_translation((54.95, 0, 10))
+ stop = _mesh_part("stop", stop_mesh.subdivide_to_size(5.0))
+
+ # Two risers on the rail top carrying a large terminal bridge: the
+ # bridge has TWO structural contacts (so the weakly-secured gate does
+ # not apply) and nothing depends on it
+ riser_a = _box_part("riser_a", (10, 10, 10), (0, 12, 29.95))
+ riser_b = _box_part("riser_b", (10, 10, 10), (30, 12, 29.95))
+ bridge = _box_part("bridge", (50, 30, 20), (15, 12, 44.9))
+ assert bridge.mesh.volume > slider.mesh.volume
+
+ outcome, _warnings = _plan_full(
+ [rail_part, slider, stop, riser_a, riser_b, bridge]
+ )
+
+ assert outcome.sequence[0] == "rail"
+ assert outcome.sequence.index("slider") < outcome.sequence.index("bridge")
+ # Risers carry the bridge (support edges) — they are spine parts too
+ assert outcome.sequence.index("riser_a") < outcome.sequence.index("bridge")
+ assert outcome.tiers["flagged"] == 0
+
+
+def test_outside_fastener_ejects_unit_member():
+ # Unit hygiene: an external screw clamping a unit member means that
+ # member is assembled at THIS level, so it leaves the unit and plans
+ # as its own body. The hub (most internally-connected member — the
+ # board the others mount on) is never ejected, even though the same
+ # screws secure it too. Exercises the ejection path end to end.
+ from app.plan import _eject_fastened_unit_members
+
+ board = _box_part("board", (60, 60, 4), (0, 0, 2))
+ left = _box_part("left", (12, 12, 10), (-18, 0, 7.95))
+ right = _box_part("right", (12, 12, 10), (18, 0, 7.95))
+ # A screw biting into `right` from above (a threaded mate → joint),
+ # clearing the board so it doesn't mate the hub
+ shaft = trimesh.creation.cylinder(radius=2.5, height=16)
+ shaft.apply_translation((18, 0, 13))
+ screw = _mesh_part("screw", shaft, name="M5 Screw")
+
+ units = [{"id": "u", "name": "Board", "nodeIds": ["board", "left", "right"]}]
+ warnings: list[str] = []
+ cleaned = _eject_fastened_unit_members(
+ [board, left, right, screw], units, trimesh, warnings
+ )
+
+ remaining = set(cleaned[0]["nodeIds"])
+ assert "right" not in remaining # clamped by the external screw
+ assert {"board", "left"} <= remaining # hub + unclamped member stay
+ assert any("ejected" in warning for warning in warnings)
+
+
+def test_eject_is_a_noop_without_outside_fasteners():
+ # A self-contained unit (no external fastener touches its members)
+ # passes through unchanged — and never raises.
+ from app.plan import _eject_fastened_unit_members
+
+ a = _box_part("a", (20, 20, 10), (0, 0, 5))
+ b = _box_part("b", (20, 20, 10), (0, 0, 15.05))
+ units = [{"id": "u", "name": "Stack", "nodeIds": ["a", "b"]}]
+ warnings: list[str] = []
+ cleaned = _eject_fastened_unit_members([a, b], units, trimesh, warnings)
+ assert set(cleaned[0]["nodeIds"]) == {"a", "b"}
+ assert warnings == []
+
+
+# --- Fixed-sequence mode ------------------------------------------------
+# The caller supplies the assembly ORDER and GROUPING; the planner uses it
+# as-is and only computes each group's forward-collision insertion motion.
+
+
+def _plan_fixed(parts, groups):
+ from app.plan import _plan_fixed_sequence
+
+ warnings: list[str] = []
+ outcome = _plan_fixed_sequence(
+ parts,
+ groups,
+ trimesh,
+ clearance=0.5,
+ path_samples=40,
+ warnings=warnings,
+ tolerance=0.15,
+ )
+ return outcome, warnings
+
+
+def _blind_channel_blocks():
+ """A rail with a horizontal blind pocket open only at +X, holding two
+ blocks that slide in along -X and stack: `deep` seats at the closed -X
+ end, `near` behind it toward the opening. The correct install order is
+ deep-first — `near` placed first boxes `deep` in against the plug."""
+ rail = trimesh.creation.box(extents=(100, 40, 30))
+ rail.apply_translation((0, 0, 15))
+ # Pocket spans x[-40, 50] (open at the +X rail face, a plug remains at -X)
+ pocket = trimesh.creation.box(extents=(90, 22, 12))
+ pocket.apply_translation((5, 0, 15))
+ rail = rail.difference(pocket).subdivide_to_size(5.0)
+ rail_part = _mesh_part("rail", rail)
+
+ deep_mesh = trimesh.creation.box(extents=(40, 20, 10))
+ deep_mesh.apply_translation((-20, 0, 15)) # x[-40, 0], against the plug
+ deep = _mesh_part("deep", deep_mesh.subdivide_to_size(5.0))
+
+ near_mesh = trimesh.creation.box(extents=(40, 20, 10))
+ near_mesh.apply_translation((20.2, 0, 15)) # x[0.2, 40.2], toward the opening
+ near = _mesh_part("near", near_mesh.subdivide_to_size(5.0))
+ return rail_part, deep, near
+
+
+def test_fixed_sequence_stacked_boxes_all_clear():
+ # (a) Given the correct bottom -> top order, every group gets a non-"none"
+ # forward-collision-clear motion (except the placed base) and verifies.
+ bottom = _box_part("bottom", (100, 100, 10), (0, 0, 5))
+ middle = _box_part("middle", (60, 60, 10), (0, 0, 15.05))
+ top = _box_part("top", (40, 40, 10), (0, 0, 25.10))
+
+ outcome, _warnings = _plan_fixed(
+ [bottom, middle, top], [["bottom"], ["middle"], ["top"]]
+ )
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ # Order is used as given
+ assert outcome.sequence == ["bottom", "middle", "top"]
+ # Base is placed (no insertion); the rest drop straight down onto it
+ assert by_id["bottom"].motion["type"] == "none"
+ assert by_id["bottom"].tier == "base"
+ assert by_id["middle"].motion["type"] != "none"
+ assert by_id["top"].motion["type"] != "none"
+ # Forward-collision clear against the parts present at their step
+ assert all(entry.verified for entry in outcome.planned)
+ # Every member carries a groupId so a step can be matched by its group
+ assert all(entry.group_id is not None for entry in outcome.planned)
+ assert len(outcome.groups) == 3
+
+
+def test_fixed_sequence_bad_order_flags_boxed_in_group():
+ # (b) An order that forces a collision: placing `near` first boxes `deep`
+ # in against the plug, so `deep` cannot be inserted and is flagged.
+ rail, deep, near = _blind_channel_blocks()
+
+ outcome, _warnings = _plan_fixed([rail, deep, near], [["rail"], ["near"], ["deep"]])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.sequence == ["rail", "near", "deep"]
+ assert by_id["deep"].tier == "flagged"
+ assert by_id["deep"].motion["type"] == "none"
+ assert by_id["deep"].blocked_by # non-empty: the plug rail + the blocking near
+ assert not by_id["deep"].verified
+ # `near` (installed toward the opening first) still slides in cleanly
+ assert by_id["near"].motion["type"] != "none"
+ assert by_id["near"].verified
+
+
+def test_fixed_sequence_respects_order_not_re_derives_it():
+ # (c) The SAME parts planned with the correct order flag nothing; reversing
+ # the two blocks moves the flag onto `deep` — proving the given order is
+ # respected, not re-derived (a re-deriving planner would pick the good order
+ # either way).
+ rail, deep, near = _blind_channel_blocks()
+ good, _ = _plan_fixed([rail, deep, near], [["rail"], ["deep"], ["near"]])
+
+ rail, deep, near = _blind_channel_blocks()
+ reversed_, _ = _plan_fixed([rail, deep, near], [["rail"], ["near"], ["deep"]])
+
+ good_flagged = {e.node_id for e in good.planned if e.tier == "flagged"}
+ reversed_flagged = {e.node_id for e in reversed_.planned if e.tier == "flagged"}
+
+ assert good_flagged == set()
+ assert reversed_flagged == {"deep"}
+ assert good_flagged != reversed_flagged
+ assert all(entry.verified for entry in good.planned)
+
+
+def test_fixed_sequence_single_group_is_the_base():
+ # (d) A single group spanning the whole model is the placed base: it keeps
+ # motion "none" and every member shares that one step.
+ a = _box_part("a", (40, 40, 10), (0, 0, 5))
+ b = _box_part("b", (40, 40, 10), (0, 0, 15.05))
+
+ outcome, _warnings = _plan_fixed([a, b], [["a", "b"]])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert set(outcome.sequence) == {"a", "b"}
+ assert by_id["a"].motion["type"] == "none"
+ assert by_id["b"].motion["type"] == "none"
+ assert by_id["a"].verified and by_id["b"].verified
+ assert by_id["a"].group_id == by_id["b"].group_id
+ assert len(outcome.groups) == 1
+ group = next(iter(outcome.groups.values()))
+ assert set(group["componentNodeIds"]) == {"a", "b"}
+ assert group["motion"]["type"] == "none"
+
+
+def test_fixed_sequence_drops_unknown_nodeids():
+ # (e) NodeIds absent from the model are dropped from their group; a group
+ # left all-unknown is skipped with a warning.
+ base = _box_part("base", (100, 100, 10), (0, 0, 5))
+ top = _box_part("top", (40, 40, 10), (0, 0, 15.05))
+
+ outcome, warnings = _plan_fixed(
+ [base, top],
+ [["base", "ghost"], ["nope1", "nope2"], ["top"]],
+ )
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ # The unknown ids never appear; the all-unknown middle group is skipped
+ assert outcome.sequence == ["base", "top"]
+ assert "ghost" not in by_id and "nope1" not in by_id
+ assert by_id["base"].motion["type"] == "none"
+ assert by_id["top"].motion["type"] != "none"
+ assert any("ghost" in warning for warning in warnings)
+ assert any("skipped" in warning.lower() for warning in warnings)
+
+
+def test_fixed_sequence_ignores_parts_outside_the_sequence():
+ # (f) The planning world is the sequence: a model part assigned to NO
+ # group is never on the canvas — it is not an obstacle, it is not
+ # classified, and it never appears in the outcome. The canopy hovers
+ # directly over `top`, so treating it as present would block (or flag)
+ # the straight +Z removal.
+ base = _box_part("base", (100, 100, 10), (0, 0, 5))
+ top = _box_part("top", (40, 40, 10), (0, 0, 15.05))
+ canopy = _box_part("canopy", (100, 100, 10), (0, 0, 30))
+
+ outcome, _warnings = _plan_fixed([base, top, canopy], [["base"], ["top"]])
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert outcome.sequence == ["base", "top"]
+ assert "canopy" not in by_id
+ # `top` lifts straight up as if the canopy didn't exist
+ assert by_id["top"].motion["type"] == "linear"
+ assert by_id["top"].removal_direction == [0.0, 0.0, 1.0]
+ assert by_id["top"].verified
+
+
+def test_fixed_sequence_tie_break_prefers_less_entangled_sense():
+ # (g) Both channel exits are collision-free against the PLACED parts, but
+ # the +X exit sweeps through the seat of `plug` (a later group in the
+ # sequence). The least-entanglement tie-break must pick the -X sense —
+ # committing to the first clear candidate would risk sliding the block
+ # through a part that installs later.
+ rail_mesh = trimesh.creation.box(extents=(100, 40, 30))
+ rail_mesh.apply_translation((0, 0, 15))
+ channel = trimesh.creation.box(extents=(102, 22, 12))
+ channel.apply_translation((0, 0, 15)) # through-pocket, open at both ±X
+ rail = _mesh_part("rail", rail_mesh.difference(channel).subdivide_to_size(5.0))
+
+ slider = _box_part("slider", (40, 20, 10), (0, 0, 15))
+ plug = _box_part("plug", (20, 20, 10), (62, 0, 15)) # beyond the +X exit
+
+ outcome, _warnings = _plan_fixed(
+ [rail, slider, plug], [["rail"], ["slider"], ["plug"]]
+ )
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+
+ assert by_id["slider"].motion["type"] == "linear"
+ direction = by_id["slider"].removal_direction
+ assert direction is not None
+ # Removal exits -X (away from the plug's seat); insertion reverses it
+ assert direction[0] == pytest.approx(-1.0, abs=1e-6)
+ assert by_id["slider"].verified
+
+
+# --- Connected-growth ordering -------------------------------------------
+# The assembly must grow as a CONNECTED body from a principled base: the
+# base is the part everything mounts into (highest mate degree + volume),
+# every pick must touch the already-placed set, and caller-authored units
+# never lose their identity inside another part's step.
+
+
+def test_reselect_base_prefers_connected_massive_part():
+ from app.plan import PlannedComponent, _reselect_base
+
+ seal = _box_part("seal", (40, 40, 2), (0, 0, 41))
+ box = _box_part("box", (60, 60, 40), (0, 0, 20))
+ lid = _box_part("lid", (40, 40, 5), (0, 0, 45))
+ units_by_id = {"seal": seal, "box": box, "lid": lid}
+ planned = [
+ PlannedComponent("seal", {"type": "none"}, "high", None, tier="base"),
+ PlannedComponent(
+ "box",
+ {"type": "none"},
+ "low",
+ None,
+ blocked_by=["seal", "lid"],
+ tier="flagged",
+ ),
+ PlannedComponent(
+ "lid",
+ {"type": "linear", "direction": [0, 0, -1], "distance": 20},
+ "high",
+ [0, 0, 1],
+ tier="linear",
+ ),
+ ]
+ adjacency = {
+ "box": {"seal", "lid", "screw1", "screw2"},
+ "seal": {"box", "lid"},
+ "lid": {"box", "seal"},
+ }
+ warnings: list[str] = []
+
+ _reselect_base(planned, units_by_id, adjacency, {}, warnings)
+
+ by_id = {entry.node_id: entry for entry in planned}
+ assert by_id["box"].tier == "base"
+ assert by_id["box"].motion == {"type": "none"}
+ assert by_id["box"].confidence == "high"
+ assert by_id["seal"].tier == "flagged"
+ assert by_id["seal"].motion == {"type": "none"}
+ assert any("re-anchored" in warning for warning in warnings)
+
+
+def test_reselect_base_requires_a_clear_margin():
+ from app.plan import PlannedComponent, _reselect_base
+
+ # The challenger matches the base on degree (no 1.5x dominance) — no churn.
+ base = _box_part("base", (40, 40, 10), (0, 0, 5))
+ other = _box_part("other", (50, 50, 12), (0, 0, 20))
+ units_by_id = {"base": base, "other": other}
+ planned = [
+ PlannedComponent("base", {"type": "none"}, "high", None, tier="base"),
+ PlannedComponent(
+ "other", {"type": "none"}, "low", None, tier="flagged"
+ ),
+ ]
+ adjacency = {"base": {"other", "x"}, "other": {"base", "y"}}
+ warnings: list[str] = []
+
+ _reselect_base(planned, units_by_id, adjacency, {}, warnings)
+
+ by_id = {entry.node_id: entry for entry in planned}
+ assert by_id["base"].tier == "base"
+ assert by_id["other"].tier == "flagged"
+ assert warnings == []
+
+
+def _connected_growth_fixture():
+ from app.plan import PlannedComponent
+
+ linear = {"type": "linear", "direction": [0.0, 0.0, -1.0], "distance": 10}
+ units = {
+ "a": _box_part("a", (20, 20, 10), (0, 0, 5)),
+ "b": _box_part("b", (10, 10, 10), (15, 0, 5)),
+ "c": _box_part("c", (10, 10, 10), (30, 0, 5)),
+ # d is the biggest, most central-looking part: without the
+ # connectivity filter the structural preference picks it right
+ # after the base
+ "d": _box_part("d", (30, 30, 30), (55, 0, 15)),
+ }
+ planned = [
+ PlannedComponent("a", {"type": "none"}, "high", None, tier="base"),
+ PlannedComponent("b", dict(linear), "high", [0, 0, 1], tier="linear"),
+ PlannedComponent("c", dict(linear), "high", [0, 0, 1], tier="linear"),
+ PlannedComponent("d", dict(linear), "high", [0, 0, 1], tier="linear"),
+ ]
+ edges: dict[str, set] = {node_id: set() for node_id in units}
+ return planned, units, edges
+
+
+def test_topo_sort_grows_connected():
+ from app.plan import _preference_topo_sort
+
+ planned, units, edges = _connected_growth_fixture()
+ adjacency = {"a": {"b"}, "b": {"a", "c"}, "c": {"b", "d"}, "d": {"c"}}
+
+ unconstrained = _preference_topo_sort(
+ planned, units, {k: set(v) for k, v in edges.items()},
+ {}, {}, list(units), [],
+ )
+ connected = _preference_topo_sort(
+ planned, units, {k: set(v) for k, v in edges.items()},
+ {}, {}, list(units), [], adjacency=adjacency,
+ )
+
+ # Without the filter the big part jumps the queue and installs in
+ # space next to nothing; with it the assembly grows hand over hand.
+ assert unconstrained.index("d") < unconstrained.index("c")
+ assert connected == ["a", "b", "c", "d"]
+
+
+def test_topo_sort_anchors_detached_island_with_warning():
+ from app.plan import _preference_topo_sort
+
+ planned, units, edges = _connected_growth_fixture()
+ from app.plan import PlannedComponent
+
+ units["e"] = _box_part("e", (8, 8, 8), (200, 0, 4))
+ planned.append(
+ PlannedComponent(
+ "e",
+ {"type": "linear", "direction": [0.0, 0.0, -1.0], "distance": 10},
+ "high",
+ [0, 0, 1],
+ tier="linear",
+ )
+ )
+ edges["e"] = set()
+ adjacency = {
+ "a": {"b"},
+ "b": {"a", "c"},
+ "c": {"b", "d"},
+ "d": {"c"},
+ "e": set(),
+ }
+ warnings: list[str] = []
+
+ order = _preference_topo_sort(
+ planned, units, edges, {}, {}, list(units), warnings,
+ adjacency=adjacency,
+ )
+
+ assert order[:4] == ["a", "b", "c", "d"]
+ assert order[-1] == "e"
+ assert any("detached island" in warning for warning in warnings)
+
+
+def test_protected_unit_never_rides_another_part():
+ # Same captive fixture that normally rigid-merges inner -> shell; as a
+ # caller-authored unit (protected) the captive keeps its own identity —
+ # here the greedy simply lifts the shell off instead, leaving the inner
+ # block as the placed base (block first, shell lowered over it).
+ def hollow(outer_extent, cavity_extent, name):
+ outer = trimesh.creation.box(
+ extents=(outer_extent, outer_extent, outer_extent)
+ )
+ cavity = trimesh.creation.box(
+ extents=(cavity_extent, cavity_extent, cavity_extent)
+ )
+ return _mesh_part(name, outer.difference(cavity))
+
+ parts = [
+ hollow(50, 40, "shell"),
+ _box_part("inner", (30, 30, 30), (0, 0, 0)),
+ ]
+ outcome = _plan_parts(
+ parts, trimesh, clearance=0.5, path_samples=40, warnings=[],
+ protected={"inner"},
+ )
+
+ by_id = {entry.node_id: entry for entry in outcome.planned}
+ assert outcome.merged_into.get("inner") is None
+ assert "inner" in outcome.sequence
+ # Never fabricated and never absorbed: the unit is either the placed
+ # base or fades in as its own step
+ assert by_id["inner"].tier in ("base", "flagged")
+ assert by_id["inner"].motion["type"] == "none"
+
+
+def test_fastener_classification_ignores_connectors_and_structure():
+ from app.plan import _classify_fasteners, _is_fastener
+
+ # "36 Pin" is a connector pin count — "pin" alone never marks hardware
+ housing = _box_part(
+ "housing", (120, 120, 51), (0, 0, 25), name="Electronics Box - 36 Pin"
+ )
+ assert not _is_fastener(housing)
+ # Dowel pins still classify via "dowel"
+ dowel = _box_part("dowel", (4, 4, 20), (0, 0, 10), name="Dowel Pin 4x20")
+ assert _is_fastener(dowel)
+
+ # Size sanity: a structural part with a spec-suffixed name (matches M8)
+ # is too big to be hardware and keeps its structural role
+ rail = _box_part(
+ "rail", (300, 40, 40), (0, 0, 20), name="Rail M8 slot pattern"
+ )
+ plate = _box_part("plate", (400, 200, 10), (0, 0, -10))
+ fasteners = _classify_fasteners([plate, rail, dowel], {})
+ assert "rail" not in fasteners
+ assert "dowel" in fasteners
diff --git a/skills-lock.json b/skills-lock.json
index 088ea29585..15f5446697 100644
--- a/skills-lock.json
+++ b/skills-lock.json
@@ -1,6 +1,12 @@
{
"version": 1,
"skills": {
+ "rust-best-practices": {
+ "source": "apollographql/skills",
+ "sourceType": "github",
+ "skillPath": "skills/rust-best-practices/SKILL.md",
+ "computedHash": "fd336f2f772eb46ddf8658de5f9dd8faa1f35615b316665307fc82eeb4b2e658"
+ },
"supabase-postgres-best-practices": {
"source": "supabase/agent-skills",
"sourceType": "github",